-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmotion_detection.py
More file actions
67 lines (52 loc) · 2 KB
/
motion_detection.py
File metadata and controls
67 lines (52 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import cv2
import numpy as np
def main():
"""Detect motion using frame differencing."""
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open webcam")
return
print("Webcam opened successfully!")
print("Press 'q' to quit")
# Use a background subtractor for robust motion detection
back_sub = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=25, detectShadows=True)
while True:
ret, frame = cap.read()
if not ret:
print("Error: Could not read frame")
break
# Apply background subtraction to detect motion
fg_mask = back_sub.apply(frame)
# Clean up the mask to reduce noise
kernel = np.ones((3, 3), np.uint8)
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel)
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_DILATE, kernel, iterations=2)
# Highlight the motion on the original frame
motion_highlight = cv2.bitwise_and(frame, frame, mask=fg_mask)
# Find contours of moving regions to draw bounding boxes
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 500:
continue # skip small clusters to reduce noise
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(
frame,
"Motion",
(x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 255, 0),
1,
cv2.LINE_AA,
)
# Display the results
cv2.imshow("Original", frame)
cv2.imshow("Motion Mask", fg_mask)
cv2.imshow("Motion Highlight", motion_highlight)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()