-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetector.py
More file actions
65 lines (50 loc) · 2.16 KB
/
detector.py
File metadata and controls
65 lines (50 loc) · 2.16 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
import cv2
import imutils
import psutil
from utils import *
def detector_log(message: str):
log("DTCT", message)
def detect_from_stream(input_pipe, output_pipe, pid):
counter = 0
firstFrame = None
while input_pipe.poll(3) or psutil.pid_exists(pid):
frame_string = input_pipe.recv()
counter += 1
if frame_string is None or frame_string == '':
if not psutil.pid_exists(pid):
break
else:
continue
gray_frame = string_to_frame(frame_string)
gray_frame = cv2.GaussianBlur(gray_frame, (21, 21), 0)
# if the first frame is None, initialize it
if firstFrame is None:
detector_log("starting background model...")
firstFrame = gray_frame.copy().astype("float")
continue
# accumulate the weighted average between the current frame and
# previous frames, then compute the difference between the current
# frame and running average
cv2.accumulateWeighted(gray_frame, firstFrame, 0.05)
frameDelta = cv2.absdiff(cv2.convertScaleAbs(gray_frame), cv2.convertScaleAbs(firstFrame))
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
# dilate the thresholded image to fill in holes, then find contours
# on thresholded image
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
motion_rectangles = []
# loop over the contours
for c in cnts:
# if the contour is too small, ignore it
if cv2.contourArea(c) < 50:
continue
# compute the bounding box for the contour, draw it on the frame,
# and update the text
(x, y, w, h) = cv2.boundingRect(c)
motion_rectangles += [((x, y), (x + w, y + h))]
frame_and_detections = frame_string + "|" + str(motion_rectangles) + '\n'
output_pipe.send(frame_and_detections)
detector_log("finished detecting " + str(counter) + " frames")
output_pipe.close()