-
Notifications
You must be signed in to change notification settings - Fork 4
/
RedTracker.py
194 lines (155 loc) · 6.12 KB
/
RedTracker.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python
# -*- coding: utf-8 -*
# assuming python3
import cv2
import numpy as np
class RedTracker:
def __init__(self,frame,initialize_with_hand=1,tracker='KCF',showimage=0,bboxsize=20):
self.bboxsize = bboxsize
self.refreshTHDtracker = 5 # the maximum acceptable center of mass position error
self.pos = [] # tracked 2d point
# if init with hand:
if initialize_with_hand:
rect = cv2.selectROI(frame, False)
self.bbox = (rect[0]+rect[2]/2-self.bboxsize/2,rect[1]+rect[3]/2-self.bboxsize/2,self.bboxsize,self.bboxsize)
cv2.destroyAllWindows()
else: # if init automatically
self.bbox,_ = self.find_largest_redzone_rect(frame,bboxsize=self.bboxsize)
# show rect
self.showrect(frame,waittime=0)
cv2.destroyAllWindows()
# initialize tracker
self.get_tracker(tracker)
self.ok = self.boxtracker.init(frame, self.bbox)
self.showimage = showimage
def get_tracker(self,name):
"""
Choose tracker from key word
"""
self.boxtracker = {
'Boosting': cv2.TrackerBoosting_create(),
'MIL': cv2.TrackerMIL_create(),
'KCF' : cv2.TrackerKCF_create(),
'TLD' : cv2.TrackerTLD_create(),
'MedianFlow' : cv2.TrackerMedianFlow_create()
}.get(name, 0)
def extractROI(self,frame,roi):
return frame[int(roi[1]):int(roi[1]+roi[3]),int(roi[0]):int(roi[0]+roi[2])]
def drawrect(self,frame,bbox,color=(0,255,0)):
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, color, 2, 1)
return frame
def showrect(self,frame,waittime=1):
# show bounding box
framewithrect = self.drawrect(frame.copy(),self.bbox)
cv2.putText(framewithrect, "Press Any Key to Start! Rect is " + str(self.bbox), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1, cv2.LINE_AA)
cv2.imshow("show bbox",framewithrect)
cv2.waitKey(waittime)
## Function to be called every update
def track(self,frame):
self.ok, self.bbox = self.boxtracker.update(frame)
# track is succeed:
if self.ok:
_,centers,_,validnum = self.extractRed(self.extractROI(frame,self.bbox))
self.pos = [self.bbox[0]+centers[0],self.bbox[1]+centers[1]]
self.validpixelnum = validnum
if self.refreshTHDtracker < max(abs(self.bboxsize/2 - centers[0]),abs(self.bboxsize/2 - centers[1])):
self.bbox = (self.pos[0]-self.bboxsize/2,self.pos[1]-self.bboxsize/2,self.bboxsize,self.bboxsize)
self.boxtracker.init(frame,self.bbox)
print('reinit tracker!')
if self.showimage:
cv2.imshow("tracked", self.drawrect(frame.copy(),self.bbox))
cv2.waitKey(1)
else:
print("Failed to track!")
def getpos(self):
return self.pos
def getrect(self):
return self.bbox
def getvalidpixelnumber(self):
return self.validpixelnum
def find_largest_redzone_rect(self,image,bboxsize=30):
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL)
h = hsv[:, :, 0]
s = hsv[:, :, 1]
mask = np.zeros(h.shape, dtype=np.uint8)
mask[((h < 15) | (h > 200)) & (s > 128)] = 255
# Get boundary
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rects = []
for contour in contours:
approx = cv2.convexHull(contour)
rect = cv2.boundingRect(approx)
rects.append(np.array(rect))
largest = max(rects, key=(lambda x: x[2] * x[3])) #return maximum rectangle
centerx = largest[0]+largest[2]/2
centery = largest[1]+largest[3]/2
bbox = (centerx-bboxsize/2,centery-bboxsize/2,bboxsize,bboxsize)
return bbox, largest
def extractRed(self,image):
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL)
h = hsv[:, :, 0]
s = hsv[:, :, 1]
mask = np.zeros(h.shape, dtype=np.uint8)
mask[((h < 10) | (h > 200)) & (s > 128)] = 255
# get RED size
validnum = sum(mask.reshape(-1))/255
hei,wid,_ = image.shape
Mmt = cv2.moments(mask)
if Mmt["m00"] != 0:
cx = Mmt['m10']/Mmt['m00']
cy = Mmt['m01']/Mmt['m00']
flag = True
else:
cx,cy = wid/2,hei/2
flag = False
#print([cx,cy])
return mask,[cx,cy],flag,validnum
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except:
fname = 0
cap = cv2.VideoCapture(fname)
ok,frame = cap.read()
if not ok:
sys.exit(-1)
tracker = RedTracker(frame,showimage=1,initialize_with_hand=0)
pos1 = []
pix = []
# Start timer
while 1:
ok,frame = cap.read()
timer = cv2.getTickCount()
if not ok:
break
tracker.track(frame)
pos1.append(tracker.getpos())
pix.append(tracker.getvalidpixelnumber())
# show FPS
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
print("FPS: "+str(fps),flush=True)
k = cv2.waitKey(1)
if k == 27 :
break
import matplotlib.pyplot as plt
p1 = np.array(pos1).reshape(-1,2)
pix1 = np.array(pix).reshape(-1)
plt.figure(1)
plt.plot(p1[:,0],-p1[:,1],label='Coarse&Fine')
plt.legend()
plt.figure(2)
plt.subplot(121)
plt.plot(p1[:,0],label='Coarse&Fine x')
plt.subplot(122)
plt.plot(p1[:,1],label='Coarse&Fine y')
plt.legend()
plt.figure(3)
plt.plot(pix1,label='number of valid pixel')
plt.legend()
plt.show()
# キャプチャをリリースして、ウィンドウをすべて閉じる
cap.release()
cv2.destroyAllWindows()