-
Notifications
You must be signed in to change notification settings - Fork 0
/
vision.py
executable file
·306 lines (217 loc) · 9.76 KB
/
vision.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import cv2
import numpy as np
import logging
import math
from collections import deque
from constants import *
FRAME_SCALE = 3
BLUE_THRESH = 110
YELLOW_THRESH = 160
H = np.array([[ -1.07693537e+01, -1.03211106e+00, 4.41554723e+03],
[ -5.61158586e-02, 7.60254152e-01, -7.36972948e+03],
[ -3.59519827e-04, -5.10817084e-02, 1.00000000e+00]])
class droidVision():
def __init__(self):
self.dataAvailable = 0
self.failedFrame = 0
self.histVPHeading = deque([0],3)
self.histLeftOffset = deque([0],3)
self.histRightOffset = deque([0],3)
self.histObDist = deque([0],3)
self.obMissing = 0
self.frameNo = 0
self.kernel = np.ones((5,5),np.uint8)
self.vpX = 0
self.vpY = 0
self.leftOffset = 0
self.rightOffset = 0
self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
self.thetaThresh = np.pi/180 *1.5
self.rhoThresh = 80
self.minLineLength = 100 * FRAME_SCALE
self.maxLineGap = 30 * FRAME_SCALE
self.centreY = DEFAULT_CAM_H # Result of calibration
self.frame_edited = np.empty((DEFAULT_CAM_H,DEFAULT_CAM_W,3))
def raw2Frame(self,frame):
if frame is not None:
# Create frames for processing
frameLAB = cv2.cvtColor(frame,cv2.COLOR_BGR2LAB)
self.frame_edited = np.copy(frame)
l,a,b = cv2.split(frameLAB)
clA = self.clahe.apply(a) # histogram adjustment
clB = self.clahe.apply(b) # histogram adjustment
return clA,clB
else:
self.failedFrame +=1
def processFrame(self, frame):
width = frame.shape[1]
bM = None
yM = None
centreX = np.round(frame.shape[1]/2)
clA,clB = self.raw2Frame(frame)
thresh,purple = cv2.threshold(clA,160,1,cv2.THRESH_BINARY)
# Split into yellow and blue lines
retY,yellow = cv2.threshold(clB,YELLOW_THRESH,1,cv2.THRESH_BINARY)
retB,blue = cv2.threshold(clB,BLUE_THRESH,1,cv2.THRESH_BINARY)
blue = cv2.bitwise_not(blue)-254 # invert blue line
# process yellow line
yellow = cv2.morphologyEx(yellow, cv2.MORPH_OPEN, self.kernel)
yline = np.squeeze(cv2.HoughLinesP(yellow,1,self.thetaThresh,self.rhoThresh,self.minLineLength,self.maxLineGap))#detect lines
if yline.ndim >= 2:
ygrad = (yline[:,0]-yline[:,2])/(yline[:,1]-yline[:,3]+0.001)# find gradient of lines
yfilt = rejectOutliers(ygrad, m=5)
yM = np.median(yfilt)
#find intersection point with baseline centreY, using gradient and mean point
ypointX,ypointY = np.sum((yline[:,0] + yline[:,2])/(2*yline.shape[0])),np.sum((yline[:,1] + yline[:,3])/(2*yline.shape[0]))
yEdgeCrossing = ypointX + yM*(self.centreY-ypointY)
for x1,y1,x2,y2 in yline:
cv2.line(frame,(x1,y1),(x2,y2),(0,0,255),1)
# process blue line
blue = cv2.morphologyEx(blue, cv2.MORPH_OPEN, self.kernel)
bline = np.squeeze(cv2.HoughLinesP(blue,1,self.thetaThresh,self.rhoThresh,self.minLineLength,self.maxLineGap))#detect lines
if bline.ndim >= 2:
bgrad = (bline[:,0]-bline[:,2])/(bline[:,1]-bline[:,3]+0.0001)# find gradient of lines
bfilt = rejectOutliers(bgrad, m=5)
bM = np.median(bfilt)
#find intersection point with baseline centreY, using gradient and mean point
bpointX,bpointY = np.sum((bline[:,0] + bline[:,2])/(2*bline.shape[0])),np.sum((bline[:,1] + bline[:,3])/(2*bline.shape[0]))
bEdgeCrossing = bpointX + bM * (DEFAULT_CAM_H - bpointY)
for x1,y1,x2,y2 in bline:
cv2.line(frame,(x1,y1),(x2,y2),(0,255,0),1)
# process purple objects
purple = cv2.morphologyEx(purple, cv2.MORPH_OPEN, self.kernel)
__, contours, __ = cv2.findContours(purple,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
if contours:
# find centroid of largest blob
blob = max(contours, key=lambda el: cv2.contourArea(el))
M = cv2.moments(blob)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
# Find edges of obstacle
leftEdge = tuple(blob[blob[:,:,0].argmin()][0])
rightEdge = tuple(blob[blob[:,:,0].argmax()][0])
topEdge = tuple(blob[blob[:,:,1].argmin()][0])
bottomEdge = tuple(blob[blob[:,:,1].argmax()][0])
# Calculate distance to object
obDistance = objectDistance(DEFAULT_CAM_H, DEFAULT_CAM_TILT, DEFAULT_CAM_HEIGHT, bottomEdge)
# Draw outputs
try:
cv2.line(frame,(0,bottomEdge[1]),(width,bottomEdge[1]),(0,255,0),2)
cv2.circle(frame, center, 5, (0,0,255), -1)
except:
logging.debug('no object rect')
obstacle = True
else:
obstacle = False
# Conditional to create vP or virtual vP
# Both lines visible
if bM != None and yM != None:
self.vpY = (yEdgeCrossing - bEdgeCrossing)/(bM - yM) + self.centreY
self.vpX = bM * (self.vpY - self.centreY) + bEdgeCrossing
self.dataAvailable = 1
# Blue line visible
elif bM != None:
self.vpY = -10000 - self.centreY
self.vpX = bM * self.vpY + bEdgeCrossing
# Yellow line visible
elif yM != None:
self.vpY = -10000 - self.centreY
self.vpX = yM * self.vpY + yEdgeCrossing
# No lines visible
else:
self.dataAvailable = 0
if self.dataAvailable:
# Using Homography to compute heading angle
realCoords = np.dot(H, [self.vpX,self.vpY,1])
realCoords = realCoords/realCoords[2]
Heading = math.atan2(-realCoords[1], -realCoords[0])
heading_deg = Heading * 180/np.pi
# logging.debug("Heading: %.2f", heading_deg)
self.histVPHeading.append(Heading)
if bM != None:
leftOffset = findTrackOffset([bpointX,bpointY], realCoords)
self.histLeftOffset.append(leftOffset)
if yM != None:
rightOffset = findTrackOffset([ypointX,ypointY], realCoords)
self.histRightOffset.append(rightOffset)
else:
self.failedFrame += 1
# If lines are not detected for 10 frames, remove history
if self.failedFrame >= 3:
self.histVPHeading = deque([0],3)
self.histLeftOffset = deque([0],3)
self.histRightOffset = deque([0],3)
# logging.debug('10 failed frames')
if obstacle:
self.obMissing = 0
self.histObDist.append(obDistance)
else:
self.obMissing +=1
if self.obMissing >= 3:
self.histObDist = deque([0],3)
# logging.debug('Lost the obstacle')
# avHeading = np.nanmedian(self.histVPHeading)
# avLeftOffset = np.nanmedian(self.histLeftOffset)
# avRightOffset = np.nanmedian(self.histRightOffset)
# avObDist = np.nanmedian(self.histObDist)
avHeading = np.nanmean(self.histVPHeading)
avLeftOffset = np.nanmean(self.histLeftOffset)
avRightOffset = np.nanmean(self.histRightOffset)
avObDist = np.nanmean(self.histObDist)
try:
cv2.line(frame,(int(bEdgeCrossing),int(self.centreY)),(int(self.vpX),int(self.vpY)),(0,255,0),2)
cv2.line(frame,(int(yEdgeCrossing),int(self.centreY)),(int(self.vpX),int(self.vpY)),(0,255,0),2)
# Show direction to vanishing point
cv2.line(frame,(int(centreX),int(self.centreY)),(int(self.vpX),int(self.vpY)),(0,0,255),2)
except:
logging.debug('cant show lines')
self.frame_edited = np.copy(frame)
return avHeading, avLeftOffset, avRightOffset, obstacle, avObDist
def rejectOutliers(data, m = 10.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/(mdev if mdev else 1.)
return data[s<m]
def objectDistance(VertPix, tiltAngle, Height, bottomEdge):
Y = VertPix/2.0 - bottomEdge[1]
fieldAngle = 0.8517
pxAngle = ((Y * fieldAngle)/(VertPix))
obDist = Height * np.tan(tiltAngle + pxAngle - (3/2*np.pi))
print('Object!:',obDist)
return obDist
def findTrackOffset(Point, realCoords):
# Point on line
x1 = realCoords[0]
y1 = realCoords[1]
# Vanishing point
x2 = Point[0]
y2 = Point[1]
# Centre point of droid
x0 = 0
y0 = 0
dx = x2 - x1
dy = y2 - y1
mag = np.sqrt(dx*dx + dy*dy)
dx = dx/mag
dy = dy/mag
# translate the point and get the dot product
Lambda = (dx * (x0 - x1)) + (dy * (y0 - y1))
x4 = (dx * Lambda) + x1
y4 = (dy * Lambda) + y1
offset = np.sqrt((x4-x0)**2 + (y4-y0)**2)
return offset
'''
Use this to put a test video through the vision
processing algorithm to see how it performs.
Doesn't require the droid!
'''
if __name__=='__main__':
cap = cv2.VideoCapture('test_videos/output3.avi')
vis = droidVision()
while(cap.isOpened()):
ret, frame = cap.read()
if frame is not None:
vis.processFrame(frame)
cv2.imshow("Vision Testing", vis.frame_edited)
cv2.waitKey(5)
cap.release()
cv2.destroyAllWindows()