forked from koyeongmin/PINet_new
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
353 lines (313 loc) · 13.2 KB
/
test.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#############################################################################################################
##
## Source code for testing
##
#############################################################################################################
import cv2
import json
import os
import glob
import torch
import agent
import numpy as np
from copy import deepcopy
from data_loader import Generator
import time
from parameters import Parameters
import util
from tqdm import tqdm
import csaps
p = Parameters()
############################################################################
## linear interpolation for fixed y value on the test dataset, if you want to use python2, use this code
############################################################################
def find_target(x, y, target_h, ratio_w, ratio_h):
# find exact points on target_h
out_x = []
out_y = []
x_size = p.x_size/ratio_w
y_size = p.y_size/ratio_h
count = 0
for x_batch, y_batch in zip(x,y):
predict_x_batch = []
predict_y_batch = []
for i, j in zip(x_batch, y_batch):
min_y = min(j)
max_y = max(j)
temp_x = []
temp_y = []
for h in target_h[count]:
temp_y.append(h)
if h < min_y:
temp_x.append(-2)
elif min_y <= h and h <= max_y:
for k in range(len(j)-1):
if j[k] >= h and h >= j[k+1]:
#linear regression
if i[k] < i[k+1]:
temp_x.append(int(i[k+1] - float(abs(j[k+1] - h))*abs(i[k+1]-i[k])/abs(j[k+1]+0.0001 - j[k])))
else:
temp_x.append(int(i[k+1] + float(abs(j[k+1] - h))*abs(i[k+1]-i[k])/abs(j[k+1]+0.0001 - j[k])))
break
else:
if i[0] < i[1]:
l = int(i[1] - float(-j[1] + h)*abs(i[1]-i[0])/abs(j[1]+0.0001 - j[0]))
if l > x_size or l < 0 :
temp_x.append(-2)
else:
temp_x.append(l)
else:
l = int(i[1] + float(-j[1] + h)*abs(i[1]-i[0])/abs(j[1]+0.0001 - j[0]))
if l > x_size or l < 0 :
temp_x.append(-2)
else:
temp_x.append(l)
predict_x_batch.append(temp_x)
predict_y_batch.append(temp_y)
out_x.append(predict_x_batch)
out_y.append(predict_y_batch)
count += 1
return out_x, out_y
def fitting(x, y, target_h, ratio_w, ratio_h):
out_x = []
out_y = []
count = 0
x_size = p.x_size/ratio_w
y_size = p.y_size/ratio_h
for x_batch, y_batch in zip(x,y):
predict_x_batch = []
predict_y_batch = []
for i, j in zip(x_batch, y_batch):
min_y = min(j)
max_y = max(j)
temp_x = []
temp_y = []
jj = []
pre = -100
for temp in j[::-1]:
if temp > pre:
jj.append(temp)
pre = temp
else:
jj.append(pre+0.00001)
pre = pre+0.00001
sp = csaps.CubicSmoothingSpline(jj, i[::-1], smooth=0.0001)
last = 0
last_second = 0
last_y = 0
last_second_y = 0
for h in target_h[count]:
temp_y.append(h)
if h < min_y:
temp_x.append(-2)
elif min_y <= h and h <= max_y:
temp_x.append( sp([h])[0] )
last = temp_x[-1]
last_y = temp_y[-1]
if len(temp_x)<2:
last_second = temp_x[-1]
last_second_y = temp_y[-1]
else:
last_second = temp_x[-2]
last_second_y = temp_y[-2]
else:
if last < last_second:
l = int(last_second - float(-last_second_y + h)*abs(last_second-last)/abs(last_second_y+0.0001 - last_y))
if l > x_size or l < 0 :
temp_x.append(-2)
else:
temp_x.append(l)
else:
l = int(last_second + float(-last_second_y + h)*abs(last_second-last)/abs(last_second_y+0.0001 - last_y))
if l > x_size or l < 0 :
temp_x.append(-2)
else:
temp_x.append(l)
predict_x_batch.append(temp_x)
predict_y_batch.append(temp_y)
out_x.append(predict_x_batch)
out_y.append(predict_y_batch)
count += 1
return out_x, out_y
############################################################################
## write result
############################################################################
def write_result_json(result_data, x, y, testset_index):
for index, batch_idx in enumerate(testset_index):
for i in x[index]:
result_data[batch_idx]['lanes'].append(i)
result_data[batch_idx]['run_time'] = 1
return result_data
############################################################################
## save result by json form
############################################################################
def save_result(result_data, fname):
with open(fname, 'w') as make_file:
for i in result_data:
json.dump(i, make_file, separators=(',', ': '))
make_file.write("\n")
############################################################################
## test on the input test image
############################################################################
def test(lane_agent, test_images, thresh = p.threshold_point, index= -1):
result = lane_agent.predict_lanes_test(test_images)
torch.cuda.synchronize()
confidences, offsets, instances = result[index]
num_batch = len(test_images)
out_x = []
out_y = []
out_images = []
for i in range(num_batch):
# test on test data set
image = deepcopy(test_images[i])
image = np.rollaxis(image, axis=2, start=0)
image = np.rollaxis(image, axis=2, start=0)*255.0
image = image.astype(np.uint8).copy()
confidence = confidences[i].view(p.grid_y, p.grid_x).cpu().data.numpy()
offset = offsets[i].cpu().data.numpy()
offset = np.rollaxis(offset, axis=2, start=0)
offset = np.rollaxis(offset, axis=2, start=0)
instance = instances[i].cpu().data.numpy()
instance = np.rollaxis(instance, axis=2, start=0)
instance = np.rollaxis(instance, axis=2, start=0)
# generate point and cluster
raw_x, raw_y = generate_result(confidence, offset, instance, thresh)
# eliminate fewer points
in_x, in_y = eliminate_fewer_points(raw_x, raw_y)
# sort points along y
in_x, in_y = util.sort_along_y(in_x, in_y)
result_image = util.get_egolane_from_points(in_x, in_y, deepcopy(image), True)
'''
util.get_egolane_from_points(in_x, in_y)
'''
out_x.append(in_x)
out_y.append(in_y)
out_images.append(result_image)
return out_x, out_y, out_images
############################################################################
## eliminate result that has fewer points than threshold
############################################################################
def eliminate_fewer_points(x, y):
# eliminate fewer points
out_x = []
out_y = []
for i, j in zip(x, y):
if len(i)>2:
out_x.append(i)
out_y.append(j)
return out_x, out_y
############################################################################
## generate raw output
############################################################################
def generate_result(confidance, offsets,instance, thresh):
mask = confidance > thresh
grid = p.grid_location[mask]
offset = offsets[mask]
feature = instance[mask]
lane_feature = []
x = []
y = []
for i in range(len(grid)):
if (np.sum(feature[i]**2))>=0:
point_x = int((offset[i][0]+grid[i][0])*p.resize_ratio)
point_y = int((offset[i][1]+grid[i][1])*p.resize_ratio)
if point_x > p.x_size or point_x < 0 or point_y > p.y_size or point_y < 0:
continue
if len(lane_feature) == 0:
lane_feature.append(feature[i])
x.append([point_x])
y.append([point_y])
else:
min_feature_index = -1
min_feature_dis = 10000
for feature_idx, j in enumerate(lane_feature):
dis = np.linalg.norm((feature[i] - j)**2)
if min_feature_dis > dis:
min_feature_dis = dis
min_feature_index = feature_idx
if min_feature_dis <= p.threshold_instance:
lane_feature[min_feature_index] = (lane_feature[min_feature_index]*len(x[min_feature_index]) + feature[i])/(len(x[min_feature_index])+1)
x[min_feature_index].append(point_x)
y[min_feature_index].append(point_y)
elif len(lane_feature) < 12:
lane_feature.append(feature[i])
x.append([point_x])
y.append([point_y])
return x, y
if __name__ == '__main__':
print('Testing')
#########################################################################
## Get dataset
#########################################################################
print("Get dataset")
loader = Generator(test_mode=True)
##############################
## Get agent and model
##############################
lane_agent = agent.Agent()
if p.model_path != "":
lane_agent.load_weights(804, "tensor(0.5786)")
##############################
## Check GPU
##############################
if torch.cuda.is_available():
lane_agent.cuda()
lane_agent.evaluate_mode()
if p.mode == 0 : # check model with test data
for _, _, _, test_image in loader.Generate():
_, _, ti = test(lane_agent, np.array([test_image]))
cv2.imshow("test", ti[0])
cv2.waitKey(0)
elif p.mode == 1: # check model with video
cap = cv2.VideoCapture("/home/kym/research/autonomous_car_vision/lane_detection/code/Tusimple/git_version/LocalDataset_Day.mp4")
while(cap.isOpened()):
ret, frame = cap.read()
torch.cuda.synchronize()
prevTime = time.time()
frame = cv2.resize(frame, (512,256))/255.0
frame = np.rollaxis(frame, axis=2, start=0)
_, _, ti = test(lane_agent, np.array([frame]))
curTime = time.time()
sec = curTime - prevTime
fps = 1/(sec)
s = "FPS : "+ str(fps)
ti[0] = cv2.resize(ti[0], (1280,800))
cv2.putText(ti[0], s, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))
cv2.imshow('frame',ti[0])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
elif p.mode == 2: # check model with pictures in folder
total_duration = 0
test_image_list = glob.glob(os.path.join(p.test_root_url, 'images', '*'))
test_image_list = sorted(test_image_list)
for test_image_name in test_image_list:
test_image = cv2.imread(test_image_name)
test_image = cv2.resize(test_image, (512,256))/255.0
test_image = np.rollaxis(test_image, axis=2, start=0)
start = time.time()
x, y, ti = test(lane_agent, np.array([test_image]))
total_duration += time.time() - start
cv2.imshow("test", ti[0])
#ti[0] = cv2.resize(ti[0], (1280, 672))
cv2.imwrite(os.path.join(p.test_root_url, 'results2', test_image_name.split(os.path.sep)[-1]), ti[0])
cv2.waitKey(1)
print("FPS: {:.3f}, time: {:.3f}s".format(len(test_image_list)/total_duration, total_duration))
elif p.mode == 3: #evaluation
print("evaluate")
result_data = deepcopy(loader.test_data)
progressbar = tqdm(range(loader.size_test//4))
for test_image, target_h, ratio_w, ratio_h, testset_index, gt in loader.Generate_Test():
x, y, _ = test(lane_agent, test_image)
x_ = []
y_ = []
for i, j in zip(x, y):
temp_x, temp_y = util.convert_to_original_size(i, j, ratio_w, ratio_h)
x_.append(temp_x)
y_.append(temp_y)
x_, y_ = fitting(x_, y_, target_h, ratio_w, ratio_h)
result_data = write_result_json(result_data, x_, y_, testset_index)
progressbar.update(1)
progressbar.close()
save_result(result_data, "test_result.json")