-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_object_detector.py
62 lines (54 loc) · 2.27 KB
/
dynamic_object_detector.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
import numpy as np
import cv2
class moving_detector:
def __init__(self):
a = 1
def draw_flow(slef,img, flow, step=16):
h, w = img.shape[:2]
y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1)
fx, fy = flow[y, x].T
lines = np.vstack([x, y, x + fx, y + fy]).T.reshape(-1, 2, 2)
lines = np.int32(lines + 0.5)
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.polylines(vis, lines, 0, (0, 255, 0))
for (x1, y1), (x2, y2) in lines:
cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
return vis
def warp_flow(self,img, flow):
h, w = flow.shape[:2]
flow = -flow
flow[:, :, 0] += np.arange(w)
flow[:, :, 1] += np.arange(h)[:, np.newaxis]
res = cv2.remap(img, flow, None, cv2.INTER_LINEAR)
return res
def draw_hsv(self,flow):
h, w = flow.shape[:2]
fx, fy = flow[:, :, 0], flow[:, :, 1]
ang = np.arctan2(fy, fx) + np.pi
v = np.sqrt(fx * fx + fy * fy)
hsv = np.zeros((h, w, 3), np.uint8)
hsv[..., 0] = ang * (180 / np.pi / 2)
hsv[..., 1] = 255
hsv[..., 2] = np.minimum(v * 4, 255)
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return bgr
def show_flow (self,prev,cur):
prevgray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
img = cur
vis = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# apply color mask here
flow = cv2.calcOpticalFlowFarneback(prevgray, gray, 0.5, 5, 15, 3, 5, 1.1, cv2.OPTFLOW_FARNEBACK_GAUSSIAN)
flow_img = self.draw_flow(gray, flow)
gray1 = cv2.cvtColor(self.draw_hsv(flow), cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray1, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# loop over the contours
for c in cnts:
# if the contour is too small, ignore it
# modify parameters for detecting close objects.
(x, y, w, h) = cv2.boundingRect(c)
if w > 100 and h > 100 and w < 200 and h < 300:
cv2.rectangle(vis, (x, y), (x + w, y + h), (0, 0, 255), 4)
return (flow_img,vis)