跟踪OpenCV(Python)中的2个最大对象

问题描述 投票:0回答:1

我想使用Background Substract方法跟踪两个最大的对象。我知道如何跟踪所有对象或最大的对象或第二大的对象,但我找不到跟踪最大的对象和第二大对象的方法。而且我找不到质心的问题。它给了我所有物体一个质心。但是我要为每个对象提供质心。

到目前为止的代码:

print(cv2.__version__)    #show version ID
import numpy as np
import tkinter as tk      #import Tkinter library for start button

#Define video capture device (0= webcam)
cap = cv2.VideoCapture(0)

#set picture dimensions
cap.set(3,800) #Width
cap.set(4,600) #Weight

while(True):
    # Capture frame-by-frame
    ret, frame1 = cap.read()
    frame1


    cv2.imshow('Press (c)-to capture the background image', frame1)
    if cv2.waitKey(1) & 0xFF == ord('c'):
        cv2.imwrite('Background.png',frame1)
        break

# Saves background to object img for later use
frame1 = cv2.imread('Background.png',1)


# When the background image is captured, release the capture
cap.release()
cv2.destroyAllWindows()

# Creates a "pause" button that has to be pushed to start the experiment
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, 
                   text="Start the experiment!", 
                   fg="black",
                   command=root.destroy)
button.pack(side=tk.LEFT)
root.mainloop()

#Define video capture device (0= webcam)
cap = cv2.VideoCapture(0)

#set picture dimensions
cap.set(3,800) #Width
cap.set(4,600) #Weight

# Define BGR colors
BGR_COLOR = {'red': (0,0,255),
             'green': (127,255,0),
             'blue': (255,127,0),
             'yellow': (0,127,255),
             'black': (0,0,0),
             'white': (255,255,255)}


ret, frame2 = cap.read()

while cap.isOpened():
    frame1 = cv2.imread('Background.png',1)
    diff = cv2.absdiff(frame2, frame1)
    gray = cv2.cvtColor (diff, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    _, thresh = cv2.threshold (blur, 20, 255, cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None, iterations=3)
    im2,contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    print("\t size of contour %d objects." % len(contours))
    for (i,c) in enumerate (contours):
        print("\tSize of contour %d: %d" % (i,len(c)))

    cnt = sorted(contours, key = cv2.contourArea) 
    print (cnt)
#    area = cv2.contourArea(cnt[2])
    cv2.drawContours(frame2, cnt, -1, (0,255,0), 3)


    # Provides contour features (x and y of center)
    for c in contours:
     M = cv2.moments(c)

    if M["m00"] != 0:
        x = int(M["m10"] / M["m00"])
        y = int(M["m01"] / M["m00"])
    else:
        x, y = 0, 0
    cv2.circle(frame2, (x, y), 5, BGR_COLOR['yellow'], -1)

    cv2.imshow("MotionDetection-Press c to exit", frame2)

    ret, frame2 = cap.read()

    if cv2.waitKey(1) & 0xFF == ord('c'):
        break

cv2.destroyAllWindows()
cap.release()

python opencv tracking contour opencv-contour
1个回答
0
投票

要获得最大的2个轮廓,应按以下顺序对轮廓列表进行切片:

largest_2_contours = sorted(contours, key=cv2.contourArea)[-2:] 

现在您必须执行所有操作,例如绘制轮廓或使用以下轮廓找到它们各自的质心,仅作为:

for contour in largest_2_contours:
    # draw the contour
    cv2.drawContours(frame2, [contour], 0, (0,255,0), 3)

    # Find the centroid or some other fancy operations with the contour.
© www.soinside.com 2019 - 2024. All rights reserved.