|
| 1 | +import cv2 |
| 2 | + |
| 3 | +def detect_motion(video_source=0): |
| 4 | + cap = cv2.VideoCapture(video_source) |
| 5 | + ret, frame1 = cap.read() |
| 6 | + ret, frame2 = cap.read() |
| 7 | + |
| 8 | + while cap.isOpened(): |
| 9 | + diff = cv2.absdiff(frame1, frame2) |
| 10 | + gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) |
| 11 | + blur = cv2.GaussianBlur(gray, (5,5), 0) |
| 12 | + _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) |
| 13 | + dilated = cv2.dilate(thresh, None, iterations=3) |
| 14 | + contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) |
| 15 | + |
| 16 | + for contour in contours: |
| 17 | + if cv2.contourArea(contour) < 1000: |
| 18 | + continue |
| 19 | + (x, y, w, h) = cv2.boundingRect(contour) |
| 20 | + cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2) |
| 21 | + |
| 22 | + cv2.imshow("Motion Detection", frame1) |
| 23 | + frame1 = frame2 |
| 24 | + ret, frame2 = cap.read() |
| 25 | + |
| 26 | + if not ret or cv2.waitKey(40) == 27: |
| 27 | + break |
| 28 | + |
| 29 | + cap.release() |
| 30 | + cv2.destroyAllWindows() |
0 commit comments