-
Notifications
You must be signed in to change notification settings - Fork 19
/
demo06_motion_detection_04.py
47 lines (37 loc) · 1.39 KB
/
demo06_motion_detection_04.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
import cv2
import datetime
camera = cv2.VideoCapture(0)
background = None
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 4))
while True:
grabbed, frame = camera.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_frame = cv2.GaussianBlur(gray_frame, (25, 25), 3)
if background is None:
background = gray_frame
continue
diff = cv2.absdiff(background, gray_frame)
diff = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)[1]
diff = cv2.dilate(diff, es, iterations=3)
contours, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
is_detected = False
for c in contours:
if cv2.contourArea(c) < 2000:
continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
is_detected = True
cv2.putText(frame, "Motion: Undetected", (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.putText(frame,
datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.35, (0, 255, 0), 1)
cv2.imshow('video', frame)
cv2.imshow('diff', diff)
key = cv2.waitKey(1) & 0xFFf
if key == ord('q'):
break
camera.release()
cv2.destroyAllWindows()