-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVITA_post_process.py
302 lines (234 loc) · 10.3 KB
/
VITA_post_process.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
#!/usr/bin/env python
import re
import os
import math
import time
import json
import glob
import scipy
import argparse
import numpy as np
import scipy.ndimage
from PIL import Image
from collections import deque
class Control:
steer = 0
throttle = 0
brake = 0
hand_brake = 0
reverse = 0
# Configurations for this script
sensors = {'RGB': 3, 'labels': 3, 'depth': 0}
resolution = [800, 600]
# Position to cut the image before reshapping
# This is used to cut out the sky (Kind of useless for learning)
IMAGE_CUT = [90, 485]
def purge(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
def join_classes(labels_image, join_dic):
compressed_labels_image = np.copy(labels_image)
for key, value in join_dic.iteritems():
compressed_labels_image[np.where(labels_image == key)] = value
return compressed_labels_image
def join_classes_for(labels_image, join_dic):
compressed_labels_image = np.copy(labels_image)
# print compressed_labels_image.shape
for i in range(labels_image.shape[0]):
for j in range(labels_image.shape[1]):
compressed_labels_image[i, j, 0] = join_dic[labels_image[i, j, 0]]
return compressed_labels_image
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
def resize(image_type, episode, data_point_number):
""" Function for reshaping all the images of an episode and save it again on the
Params:
image_type: The type of images that is going to be reshaped. """
if image_type == 'SemanticSeg':
interp_type = 'nearest'
else:
interp_type = 'bicubic'
center_name = 'Central' + image_type + '_' + data_point_number + '.png'
top_name = 'Top' + image_type + '_' + data_point_number + '.png'
center = scipy.ndimage.imread(os.path.join(episode, center_name))
top = scipy.ndimage.imread(os.path.join(episode, top_name))
if center.shape[0] == 600:
center = scipy.misc.imresize(center, (150, 200), interp=interp_type)
scipy.misc.imsave(os.path.join(episode, center_name), center)
if top.shape[0] == 600:
top = scipy.misc.imresize(top, (150, 200), interp=interp_type)
scipy.misc.imsave(os.path.join(episode, top_name), top)
def convert_segmented(image_type, episode, data_point_number):
""" Function for converting semantic segmented images
Params:
image_type: The type of images that is going to be reshaped. """
center_name = 'Central' + image_type + '_' + data_point_number + '.png'
top_name = 'Top' + image_type + '_' + data_point_number + '.png'
center = scipy.ndimage.imread(os.path.join(episode, center_name))
top = scipy.ndimage.imread(os.path.join(episode, top_name))
def conversion(img):
img[(img==np.array([0,0,0]))[:,:,0]] = np.array([0, 0, 0])
img[(img==np.array([1,0,0]))[:,:,0]] = np.array([70, 70, 70])
img[(img==np.array([2,0,0]))[:,:,0]] = np.array([190, 153, 153])
img[(img==np.array([3,0,0]))[:,:,0]] = np.array([250, 170, 160])
img[(img==np.array([4,0,0]))[:,:,0]] = np.array([220, 20, 60])
img[(img==np.array([5,0,0]))[:,:,0]] = np.array([153, 153, 153])
img[(img==np.array([6,0,0]))[:,:,0]] = np.array([157, 234, 50])
img[(img==np.array([7,0,0]))[:,:,0]] = np.array([128, 64, 128])
img[(img==np.array([8,0,0]))[:,:,0]] = np.array([244, 35, 232])
img[(img==np.array([9,0,0]))[:,:,0]] = np.array([107, 142, 35])
img[(img==np.array([10,0,0]))[:,:,0]] = np.array([0, 0, 142])
img[(img==np.array([11,0,0]))[:,:,0]] = np.array([102, 102, 156])
img[(img==np.array([12,0,0]))[:,:,0]] = np.array([220, 220, 0])
return img
center = conversion(center)
scipy.misc.imsave(os.path.join(episode, center_name), center)
top = conversion(top)
scipy.misc.imsave(os.path.join(episode, top_name), top)
# ***** main loop *****
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Path viewer')
# parser.add_argument('model', type=str, help='Path to model definition json. Model weights should be on the same path.')
parser.add_argument('-pt', '--path', default="")
parser.add_argument(
'--episodes',
nargs='+',
dest='episodes',
type=str,
default='all'
)
parser.add_argument(
'-s', '--start_episode',
default=0,
type=int,
help=' the first episode'
)
""" You should pass this extra arguments if you want to delete the semantic segmenation labels"""
parser.add_argument(
'-ds', '--delete-semantic-segmentation',
dest='delete_semantic_segmentation',
action='store_true',
help='Flag to tell the system to NOT erase the semantic segmentation labels from the dataset'
)
""" You should pass this extra arguments if you want to delete the depth labels"""
parser.add_argument(
'-dd', '--delete-depth',
dest='delete_depth',
action='store_true',
help='Flag to tell the system to NOT erase the semantic segmentation labels from the dataset'
)
args = parser.parse_args()
path = args.path
# By setting episodes as all, it means that all episodes should be visualized
if args.episodes == 'all':
episodes_list = glob.glob(os.path.join(path, 'episode_*'))
sort_nicely(episodes_list)
else:
episodes_list = args.episodes
data_configuration_name = 'VITA_coil_training_dataset'
print ( data_configuration_name)
print ('dataset_configurations.' + (data_configuration_name) )
settings_module = __import__('dataset_configurations.' + (data_configuration_name),
fromlist=['dataset_configurations'] )
first_time = True
count = 0
steering_pred = []
steering_gt = []
step_size = 1
image_queue = deque()
actions_queue = deque()
# Start a screen to show everything. The way we work is that we do IMAGES x Sensor.
# But maybe a more arbitrary configuration may be useful
ts = []
for episode in episodes_list[args.start_episode:]:
print ('Episode ', episode)
if 'episode' not in episode:
episode = 'episode_' + episode
if os.path.exists(os.path.join(episode, "checked")) or os.path.exists(
os.path.join(episode, "processed2")) \
or os.path.exists(os.path.join(episode, "bad_episode")):
# Episode was not checked. So we dont load it.
print(" This episode was already checked ")
continue
# Take all the measurements from a list
try:
measurements_list = glob.glob(os.path.join(episode, 'measurement*'))
sort_nicely(measurements_list)
print (" Purging other data")
print (episode)
if args.delete_depth:
print ("***Depth***")
purge(episode, "CentralDepth*")
purge(episode, "TopDepth*")
if args.delete_semantic_segmentation:
print ("***Purging SemanticSeg***")
purge(episode, "CentralSemanticSeg*")
purge(episode, "TopSemanticSeg*")
bad_episode = False
if len(measurements_list) <= 1:
print (" Episode is empty")
purge(episode, '.')
bad_episode = True
continue
for measurement in measurements_list[:-3]:
data_point_number = measurement.split('_')[-1].split('.')[0]
with open(measurement) as f:
measurement_data = json.load(f)
resize("RGB", episode, data_point_number)
if not args.delete_semantic_segmentation:
resize("SemanticSeg", episode, data_point_number)
convert_segmented("SemanticSeg", episode, data_point_number)
if 'forwardSpeed' in measurement_data['playerMeasurements']:
speed = measurement_data['playerMeasurements']['forwardSpeed']
else:
speed = 0
float_dicts = {'steer': measurement_data['steer'],
'throttle': measurement_data['throttle'],
'brake': measurement_data['brake'],
'speed_module': speed,
'directions': measurement_data['directions'],
"pedestrian": measurement_data['stop_pedestrian'],
"traffic_lights": measurement_data['stop_traffic_lights'],
"vehicle": measurement_data['stop_vehicle'],
'angle': -30.0}
for measurement in measurements_list[-3:]:
data_point_number = measurement.split('_')[-1].split('.')[0]
purge(episode, "CentralRGB_" + data_point_number + '.png')
purge(episode, "TopRGB_" + data_point_number + '.png')
purge(episode, "CentralSemanticSeg_" + data_point_number + '.png')
purge(episode, "TopSemanticSeg_" + data_point_number + '.png')
os.remove(measurement)
if not bad_episode:
done_file = open(os.path.join(episode, "processed2"), 'w')
done_file.close()
except:
import traceback
traceback.print_exc()
print (" Error on processing")
done_file = open(os.path.join(episode, "bad"), 'w')
done_file.close()
continue
# The last one we delete
data_point_number = measurements_list[-1].split('_')[-1].split('.')[0]
print (data_point_number)
purge(episode, "CentralRGB_" + data_point_number + '.png')
purge(episode, "TopRGB_" + data_point_number + '.png')
"""
if ss_center.shape[0] == 600:
ss_center = rgb_center[IMAGE_CUT[0]:IMAGE_CUT[1], ...]
ss_center = scipy.misc.imresize(rgb_center, (88, 200))
scipy.misc.imsave(os.path.join(episode, rgb_center_name), rgb_center)
"""