Nov-12-2019, 11:08 AM
i want to track the 2 biggest objects with the Background Substract method. I know how to track all objects or the biggest one or the second biggest one, but i can't find a way to track just the biggest and the second biggest one. And i cant find the problem with the centroid. It gaves me one centroid for all of the objects. But i want centroids for every objects.
The Code so far:
The Code so far:
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()