import cv2 import numpy as np import time cap = cv2.VideoCapture(0) k = np.ones((3, 3), np.uint8) t0 = cap.read()[1] t1 = cap.read()[1] allcontours = [] whiteBackground = 0 autoClear = 0 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH )) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT )) thresholdW = int(width / 2) outputTitleB = "Press ESC to exit. Try a or e or r or (m or l) or (i or k)" sense = 35 maxContoursBuffer = 500 cColor1 = 255 addToColor = 1 activeDetect = 1 holdLeftRight = 0 # 1 = L, 2 = R frame_rate = 12 prev = 0 while(True): time_elapsed = time.time() - prev if time_elapsed > 1./frame_rate: prev = time.time() else: continue d=cv2.absdiff(t1, t0) grey = cv2.cvtColor(d, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(grey, (3, 3), 0) ret, th = cv2.threshold( blur,sense, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(th, k, iterations=4) contours, hierarchy = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) t2=t0 if whiteBackground == 1: cv2.rectangle(t2, (0,0), (width,height), (10,10,10), cv2.FILLED) cColor1 = 1 for x in allcontours: cColor1 += 0.5 cv2.drawContours(t2, x, -1, (cColor1,0,0), 3) if activeDetect == 1: if len(allcontours) < maxContoursBuffer: allcontours += contours[:20] #Add a max. of n data points if contours: if thresholdW > allcontours[-1][0][0][0]: holdLeftRight = 1 elif width - thresholdW < allcontours[-1][0][0][0]: holdLeftRight = 2 allcontours = allcontours[8:] if holdLeftRight == 1: cv2.rectangle(t2, (0,0), (20,height), (0,0,255), cv2.FILLED) elif holdLeftRight == 2: cv2.rectangle(t2, (width-20,0), (width,height), (0,0,255), cv2.FILLED) cv2.drawContours(t2, contours, -1, (0, 255, 0), 2) imS = cv2.resize(t2, (1060, 700)) cv2.imshow(outputTitleB, imS) #t0=t2 t0=t1 t1=cap.read()[1] cKey = cv2.waitKey(15) if cKey == 27 : break elif cKey == ord('a'): whiteBackground = 1 - whiteBackground elif cKey == ord('m'): sense += 1 print(sense) elif cKey == ord('r'): allcontours = [] print("reset") elif cKey == ord('l'): sense -= 1 print(sense) elif cKey == ord('e'): activeDetect = 1 - activeDetect print("Is active:" + str(activeDetect)) elif cKey == ord('i'): addToColor += 1 print("Current addColor:" + str(addToColor)) elif cKey == ord('k'): addToColor -= 1 print("Current addColor:" + str(addToColor)) cv2.destroyAllWindows() cap.release()