import cv2 import numpy as np import sys import signal areaArray = [] count = 1 end = False # -------------------------------------- def signal_handler(signal, frame): global end end = True # -------------------------------------- cap = cv2.VideoCapture(3) if (cap.isOpened() == False): print("Error reading video file") fourcc = cv2.VideoWriter_fourcc(*'DIVX') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) signal.signal(signal.SIGINT, signal_handler) print('Capturando o vĂ­deo da webcam -- pressione Ctrl+C para encerrar...') while (not end): ret, framer = cap.read() if ret == True: frame = resized = cv2.resize(framer, None, fx=1, fy=1) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Transform image to gray hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) kernel = np.ones((20,20),np.uint8) mask = cv2.inRange(hsv,np.array([0,0,201],np.uint8), np.array([255,10,255],np.uint8)) mask = cv2.erode(mask,kernel) mask = cv2.dilate(mask,kernel) V_contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in V_contours: if len(V_contours) >= 2 : for i, c in enumerate(V_contours): area = cv2.contourArea(c) areaArray.append(area) sorteddata = sorted(zip(areaArray, V_contours), key=lambda x: x[0], reverse=True) secondlargestcontour = sorteddata[1][1] maior = max(V_contours,key=cv2.contourArea) M = cv2.moments(maior) M1 = cv2.moments(secondlargestcontour) if M["m00"] !=0 : cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) if M1["m00"] !=0 : cx1 = int(M1['m10']/M1['m00']) cy1 = int(M1['m01']/M1['m00']) cv2.circle(frame, (cx,cy), 25, (255,0,0), -1) cv2.circle(frame, (cx1,cy1), 25, (0,255,0), -1) cv2.imshow("Range mask ", mask) cv2.imshow("Frame",frame) out.write(frame) if cv2.waitKey(30) & 0xff == ord('q'): # 1 is the time in ms break else: break cap.release() out.release() cv2.destroyAllWindows() print("The video was successfully saved")