-
Notifications
You must be signed in to change notification settings - Fork 0
/
motion_detection.py
58 lines (46 loc) · 1.7 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
import logging
import time
import cv2
import imutils
log = logging.getLogger(__file__)
class FearsEye(object):
def __init__(self):
self.camera = cv2.VideoCapture(-1)
self.min_area = 500
self.first_frame = None
self.action_methods = list()
time.sleep(.2)
def begin(self):
while True:
try:
success, frame = self.camera.read()
if not success:
log.info('could not read camera')
break
gray_frame = self._get_generic_frame(frame)
if self.first_frame is None:
self.first_frame = gray_frame
continue
frame_delta = cv2.absdiff(self.first_frame, gray_frame)
threshold = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1]
threshold = cv2.dilate(threshold, None, iterations=2)
(_, contours, _) = cv2.findContours(
threshold.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < self.min_area:
continue
for action in self.action_methods:
action()
break
except KeyboardInterrupt:
break
except Exception as e:
log.info(e.message)
break
def end(self):
self.camera.release()
@staticmethod
def _get_generic_frame(frame):
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return cv2.GaussianBlur(gray, (21, 21), 0)