-
Notifications
You must be signed in to change notification settings - Fork 0
/
Motion_detection.py
69 lines (57 loc) · 1.77 KB
/
Motion_detection.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
import cv2
import imutils
import threading
import winsound
# Initialize the video capture object
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# Read the initial frame and preprocess it
_, start_frame = cap.read()
start_frame = imutils.resize(start_frame, width=500)
start_frame = cv2.cvtColor(start_frame, cv2.COLOR_BGR2GRAY)
start_frame = cv2.GaussianBlur(start_frame, (21, 21), 0)
alarm = False
alarm_mode = False
alarm_counter = 0
def beep_alarm():
global alarm
for _ in range(5):
if not alarm_mode:
break
print("ALARM")
winsound.Beep(2500, 1000)
alarm = False
while True:
# Capture the current frame and preprocess it
_, frame = cap.read()
frame = imutils.resize(frame, width=500)
if alarm_mode:
frame_bw = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame_bw = cv2.GaussianBlur(frame_bw, (21, 21), 0)
# Calculate the difference and threshold
difference = cv2.absdiff(frame_bw, start_frame)
threshold = cv2.threshold(difference, 25, 255, cv2.THRESH_BINARY)[1]
start_frame = frame_bw
# Check for significant motion
if threshold.sum() > 901:
alarm_counter += 1
else:
if alarm_counter > 0:
alarm_counter -= 1
cv2.imshow("Cam", threshold)
else:
cv2.imshow("Cam", frame)
if alarm_counter > 20:
if not alarm:
alarm = True
threading.Thread(target=beep_alarm).start()
key_pressed = cv2.waitKey(30)
if key_pressed == ord("t"):
alarm_mode = not alarm_mode
alarm_counter = 0
if key_pressed == ord("q"):
alarm_mode = False
break
cap.release()
cv2.destroyAllWindows()