This program uses your webcam to detect motion. It shows a green box around moving parts and prints 'Motion detected!' when movement is found.
import cv2
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while cap.isOpened():
frame_diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
motion_detected = False
for contour in contours:
if cv2.contourArea(contour) > 1000:
motion_detected = True
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)
if motion_detected:
print('Motion detected!')
cv2.imshow('Motion Detection', frame1)
frame1 = frame2
ret, frame2 = cap.read()
if cv2.waitKey(30) & 0xFF == 27: # Press ESC to exit
break
cap.release()
cv2.destroyAllWindows()