-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMotion_detect_v2.py
185 lines (151 loc) · 5.57 KB
/
Motion_detect_v2.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
Motion detect and save v2
By Steve Shambles
Original code Dec 2019, updated may 2023
Tested on Win7
pip install opencv-python
pip install numpy
Based on intel detection algo, found here:
https://software.intel.com/en-us/node/754940
"""
import os
import time
from tkinter import messagebox, Tk
import webbrowser
import cv2
import numpy as np
root = Tk()
motion_detect = 0
md_switch = 'OFF'
# check for folder.
my_dir = ('detected-images')
check_folder = os.path.isdir(my_dir)
# If folder doesn't exist, then create it.
if not check_folder:
os.makedirs(my_dir)
# Make that folder current dir.
os.chdir(my_dir)
# Change sdthresh (sensitivty) to suit camera and conditions,
# 10-15 is usually within the threshold range.
sdThresh = 15
# Used to count individualy named frames as jpgs.
img_index = 0
# Use this cv2 font.
font = cv2.FONT_HERSHEY_SIMPLEX
def open_folder():
"""open systems file browser to view images folder."""
cwd = os.getcwd()
webbrowser.open(cwd)
def distMap(frame1, frame2):
"""outputs pythagorean distance between two frames."""
frame1_32 = np.float32(frame1)
frame2_32 = np.float32(frame2)
diff32 = frame1_32 - frame2_32
norm32 = np.sqrt(diff32[:, :, 0]**2 + diff32[:, :, 1]**2 + diff32[:, :, 2]
** 2)/np.sqrt(255**2 + 255**2 + 255**2)
dist = np.uint8(norm32*255)
return dist
def print_date_time():
"""Updates current date and time and keys info on to video."""
current_time = time.asctime()
cv2.putText(frame2, str(current_time), (280, 24),
font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)
cv2.putText(frame2, ' Press h for options : Sensitivity = '
+ str(sdThresh) + ' : Save detected images is: '
+ str(md_switch),
(10, 470), font, 0.5, (255, 255, 255), 1)
# Capture video stream.
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # added cv2.CAP_DSHOW fix cv.
ret, frame1 = cap.read() # added ret, to fix update in cv2 module.
ret, frame2 = cap.read() # added ret, to fix update in cv2 module.
# Main loop.
while True:
ret, frame3 = cap.read() # added ret, to fix update in cv2 module.
# Report error if camera not found.
try:
rows, cols, _ = np.shape(frame3)
except ValueError as ve:
print("Webcam not found or no data from camera error")
exit(0)
dist = distMap(frame1, frame3)
frame1 = frame2
frame2 = frame3
keyPress = cv2.waitKey(20)
# Apply Gaussian smoothing.
mod = cv2.GaussianBlur(dist, (9, 9), 0)
# Apply thresholding.
thresh = cv2.threshold(mod, 100, 255, 0)
# Calculate st dev test.
mean, stDev = cv2.meanStdDev(mod)
# If motion is dectected. some changes made in next few lines by claude+
# damned if i can recall but it fixed cv2 update.
if stDev > sdThresh:
# Motion is detected.
cv2.putText(frame2, 'MD '+str(img_index),
(0, 20), font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)
print_date_time()
# Save a timestamped jpg if motion detected.
if motion_detect == 1:
frame_name = (str(img_index)+str('.jpg'))
cv2.imwrite(frame_name, frame2)
img_index += 1
print_date_time()
cv2.imshow('Live video', frame2)
# Enter key pauses video stream.
if keyPress & 0xFF == 13:
cv2.putText(frame2, 'PAUSED', (210, 260), font, 2,
(0, 255, 0), 8, cv2.LINE_AA)
cv2.imshow('Live video', frame2)
cv2.waitKey(0)
# q key to quit program.
if keyPress & 0xFF == ord('q'):
root.withdraw()
ask_yn = messagebox.askyesno('Quit Motion Detector?',
'Are you sure?')
if ask_yn:
break
root.update_idletasks()
# Motion detect off. s key.
if keyPress & 0xFF == ord('s'):
motion_detect = 0
md_switch = 'OFF'
# Motion detect on. m key.
if keyPress & 0xFF == ord('m'):
motion_detect = 1
md_switch = 'ON'
# Camera sensitivity + key.
if keyPress & 0xFF == ord('+'):
sdThresh += 1
# Camera sensitivity - key.
if keyPress & 0xFF == ord('-'):
sdThresh -= 1
# View images folder v key.
if keyPress & 0xFF == ord('v'):
open_folder()
# Snapshot x key.
if keyPress & 0xFF == ord('x'):
frame_name = (str(img_index)+str('-snapshot.jpg'))
cv2.imwrite(frame_name, frame2)
img_index += 1
# Help keys msg box.
if keyPress & 0xFF == ord('h'):
root.withdraw()
messagebox.showinfo('Motion Detector help - Keys',
'H ~ This menu\n\n'
'M ~ Start motion dectect\n\n'
'S ~ Stop motion detect\n\n'
'X ~ Take a single snaphot\n\n'
'V ~ View images folder\n\n'
'+ ~ Camera sensitivity increase\n\n'
'- ~ Camera sensitivity deccrease\n\n'
'Q ~ Quit\n\n'
'ENTER - Pause video stream\n\n'
'Motion Detector V2 is Freeware.\n'
'By Steve Shambles, May 2023.\n\n'
'Tip: Make sure video window is selected\n'
'for key presses to work.\n'
)
# Close down.
cap.release()
cv2.destroyAllWindows()
root.mainloop()