-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotion.py
83 lines (71 loc) · 2.56 KB
/
motion.py
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import cv2
import numpy as np
import os
from datetime import datetime
# Set the DISPLAY environment variable to use the monitor connected to the Raspberry Pi
os.environ['DISPLAY'] = ':0'
# Function to control the ACT LED
def set_led(state):
try:
with open('/sys/class/leds/ACT/brightness', 'w') as led_file: # Update this path based on your system
led_file.write('1' if state else '0')
except PermissionError:
print("Permission denied: Could not write to LED control file. Please run the script with sudo.")
# Initialize the camera
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open camera.")
exit()
# Create directory to save images
save_dir = "captured_images"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Read the first frame
ret, frame1 = cap.read()
if not ret:
print("Error: Could not read frame.")
exit()
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
gray1 = cv2.GaussianBlur(gray1, (21, 21), 0)
try:
while True:
# Read the next frame
ret, frame2 = cap.read()
if not ret:
break
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
gray2 = cv2.GaussianBlur(gray2, (21, 21), 0)
# Compute the absolute difference between frames
diff = cv2.absdiff(gray1, gray2)
thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
# Find contours in the thresholded image
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
motion_detected = False
for contour in contours:
if cv2.contourArea(contour) < 500:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 2)
motion_detected = True
if motion_detected:
# Turn on the ACT LED
set_led(True)
# Capture and save the image
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
cv2.imwrite(os.path.join(save_dir, f"motion_{timestamp}.jpg"), frame2)
else:
# Turn off the ACT LED
set_led(False)
# Display the resulting frame
cv2.imshow('Motion Detection', frame2)
# Update the previous frame
gray1 = gray2.copy()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
# Release the camera and close windows
cap.release()
cv2.destroyAllWindows()
# Turn off the ACT LED
set_led(False)