-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmotion.py
More file actions
97 lines (64 loc) · 2.36 KB
/
motion.py
File metadata and controls
97 lines (64 loc) · 2.36 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
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
from datetime import datetime
from dotenv.main import load_dotenv
import os
import cv2
import pandas
static_back = None
motion_list = [None, None]
time = []
load_dotenv()
display_setting = list(os.environ['DISPLAY_CONFIG'])
blur_int = int(os.environ['BLUR'])
scores_int = int(os.environ['SCORES'])
thresh_int = int(os.environ['THRESH'])
x_res_int = int(os.environ['X_RES'])
y_res_int = int(os.environ['Y_RES'])
df = pandas.DataFrame(columns=["Start", "End"])
video = cv2.VideoCapture(1)
video.set(cv2.CAP_PROP_FRAME_WIDTH, x_res_int)
video.set(cv2.CAP_PROP_FRAME_HEIGHT, y_res_int)
check, frame = video.read()
while True:
check, frame2 = video.read()
motion = 0
gray1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
gray1 = cv2.GaussianBlur(gray1, (blur_int, blur_int), 0)
gray2 = cv2.GaussianBlur(gray2, (blur_int, blur_int), 0)
if static_back is None:
static_back = gray1
continue
diff_frame = cv2.absdiff(gray1, gray2)
thresh_frame = cv2.threshold(diff_frame, thresh_int, 255, cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame, None, iterations=2)
display_frame = frame2.copy()
cnts, _ = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
scores = cv2.contourArea(contour)
if scores < scores_int:
continue
motion = 1
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(display_frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
motion_list.append(motion)
motion_list = motion_list[-2:]
if motion_list[-1] == 1 and motion_list[-2] == 0:
time.append(datetime.now())
if motion_list[-1] == 0 and motion_list[-2] == 1:
time.append(datetime.now())
if any(ext == "g" for ext in display_setting):
cv2.imshow("Gray Frame", gray2)
if any(ext == "d" for ext in display_setting):
cv2.imshow("Difference Frame", diff_frame)
if any(ext == "t" for ext in display_setting):
cv2.imshow("Threshold Frame", thresh_frame)
if any(ext == 'c' for ext in display_setting):
cv2.imshow("Color Frame", display_frame)
frame = frame2
key = cv2.waitKey(1)
if key == ord('q'):
if motion == 1:
time.append(datetime.now())
break
video.release()
cv2.destroyAllWindows()