-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
371 lines (326 loc) · 15.7 KB
/
data.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import os
import json
from PIL import Image
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
import torch.nn.functional as F
from tqdm import tqdm
import sys
class CARLA_Data(Dataset):
def __init__(self, root, config):
self.seq_len = config.seq_len
self.pred_len = config.pred_len
self.ignore_sides = config.ignore_sides
self.ignore_rear = config.ignore_rear
self.input_resolution = config.input_resolution
self.scale = config.scale
self.seg_dir = config.seg_dir #hs
self.lidar = []
self.front = []
self.left = []
self.right = []
self.rear = []
self.seg = []
self.seg_gt = []
self.json = []
self.x = []
self.y = []
self.x_command = []
self.y_command = []
self.theta = []
self.steer = []
self.throttle = []
self.brake = []
self.command = []
self.velocity = []
for sub_root in tqdm(root, file=sys.stdout):
preload_file = os.path.join(sub_root, 'rg_lidar_diag_pl_'+str(self.seq_len)+'_'+str(self.pred_len)+'.npy')
sub_root_name = sub_root.split('/')[-1]
# dump to npy if no preload
if not os.path.exists(preload_file):
# if True: #hs # make preload file again if needed
preload_front = []
preload_left = []
preload_right = []
preload_rear = []
preload_lidar = []
preload_seg = [] #hs
preload_seg_gt = []
preload_json = []
preload_x = []
preload_y = []
preload_x_command = []
preload_y_command = []
preload_theta = []
preload_steer = []
preload_throttle = []
preload_brake = []
preload_command = []
preload_velocity = []
# list sub-directories in root
root_files = os.listdir(sub_root)
routes = [folder for folder in root_files if not os.path.isfile(os.path.join(sub_root,folder))]
for route in routes:
route_dir = os.path.join(sub_root, route)
seg_dir = os.path.join(self.seg_dir, sub_root_name, route) #hs
print(route_dir)
# subtract final frames (pred_len) since there are no future waypoints
# first frame of sequence not used
num_seq = (len(os.listdir(route_dir+"/rgb_front/"))-self.pred_len-2)//self.seq_len
for seq in range(num_seq):
fronts = []
lefts = []
rights = []
rears = []
lidars = []
segs = [] #hs
seg_gts = []
jsons = []
xs = []
ys = []
thetas = []
# read files sequentially (past and current frames)
for i in range(self.seq_len):
# images
filename = f"{str(seq*self.seq_len+1+i).zfill(4)}.png"
fronts.append(route_dir+"/rgb_front/"+filename)
lefts.append(route_dir+"/rgb_left/"+filename)
rights.append(route_dir+"/rgb_right/"+filename)
rears.append(route_dir+"/rgb_rear/"+filename)
segs.append(seg_dir+"/rgb_front/"+filename[:-3]+'npy') #hs
seg_gts.append(route_dir+"/seg_front/"+filename)
jsons.append(route_dir+"/measurements/"+filename[:-3]+'json')
# point cloud
lidars.append(route_dir + f"/lidar/{str(seq*self.seq_len+1+i).zfill(4)}.npy")
# position
with open(route_dir + f"/measurements/{str(seq*self.seq_len+1+i).zfill(4)}.json", "r") as read_file:
data = json.load(read_file)
xs.append(data['x'])
ys.append(data['y'])
thetas.append(data['theta'])
# get control value of final frame in sequence
preload_x_command.append(data['x_command'])
preload_y_command.append(data['y_command'])
preload_steer.append(data['steer'])
preload_throttle.append(data['throttle'])
preload_brake.append(data['brake'])
preload_command.append(data['command'])
preload_velocity.append(data['speed'])
# read files sequentially (future frames)
for i in range(self.seq_len, self.seq_len + self.pred_len):
# point cloud
lidars.append(route_dir + f"/lidar/{str(seq*self.seq_len+1+i).zfill(4)}.npy")
# position
with open(route_dir + f"/measurements/{str(seq*self.seq_len+1+i).zfill(4)}.json", "r") as read_file:
data = json.load(read_file)
xs.append(data['x'])
ys.append(data['y'])
# fix for theta=nan in some measurements
if np.isnan(data['theta']):
thetas.append(0)
else:
thetas.append(data['theta'])
preload_front.append(fronts)
preload_left.append(lefts)
preload_right.append(rights)
preload_rear.append(rears)
preload_lidar.append(lidars)
preload_seg.append(segs) #hs
preload_seg_gt.append(seg_gts)
preload_json.append(jsons)
preload_x.append(xs)
preload_y.append(ys)
preload_theta.append(thetas)
# dump to npy
preload_dict = {}
preload_dict['front'] = preload_front
preload_dict['left'] = preload_left
preload_dict['right'] = preload_right
preload_dict['rear'] = preload_rear
preload_dict['lidar'] = preload_lidar
preload_dict['seg'] = preload_seg #hs
preload_dict['json'] = preload_json
preload_dict['seg_gt'] = preload_seg_gt
preload_dict['x'] = preload_x
preload_dict['y'] = preload_y
preload_dict['x_command'] = preload_x_command
preload_dict['y_command'] = preload_y_command
preload_dict['theta'] = preload_theta
preload_dict['steer'] = preload_steer
preload_dict['throttle'] = preload_throttle
preload_dict['brake'] = preload_brake
preload_dict['command'] = preload_command
preload_dict['velocity'] = preload_velocity
np.save(preload_file, preload_dict)
# load from npy if available
preload_dict = np.load(preload_file, allow_pickle=True)
self.front += preload_dict.item()['front']
self.left += preload_dict.item()['left']
self.right += preload_dict.item()['right']
self.rear += preload_dict.item()['rear']
self.lidar += preload_dict.item()['lidar']
self.seg += preload_dict.item()['seg']#hs
self.seg_gt += preload_dict.item()['seg_gt']
self.json += preload_dict.item()['json']
self.x += preload_dict.item()['x']
self.y += preload_dict.item()['y']
self.x_command += preload_dict.item()['x_command']
self.y_command += preload_dict.item()['y_command']
self.theta += preload_dict.item()['theta']
self.steer += preload_dict.item()['steer']
self.throttle += preload_dict.item()['throttle']
self.brake += preload_dict.item()['brake']
self.command += preload_dict.item()['command']
self.velocity += preload_dict.item()['velocity']
print("Preloading " + str(len(preload_dict.item()['front'])) + " sequences from " + preload_file)
def __len__(self):
"""Returns the length of the dataset. """
return len(self.front)
def __getitem__(self, index):
"""Returns the item at index idx. """
data = dict()
data['fronts'] = []
data['lefts'] = []
data['rights'] = []
data['rears'] = []
data['lidars'] = []
data['segs'] = []
data['seg_gts'] = []
data['tl_gts'] = []
seq_fronts = self.front[index]
seq_lefts = self.left[index]
seq_rights = self.right[index]
seq_rears = self.rear[index]
seq_lidars = self.lidar[index]
seq_segs = self.seg[index]
seq_seg_gts = self.seg_gt[index] #hs
seq_jsons = self.json[index]
seq_x = self.x[index]
seq_y = self.y[index]
seq_theta = self.theta[index]
full_lidar = []
pos = []
neg = []
for i in range(self.seq_len):
data['fronts'].append(torch.from_numpy(np.array(
scale_and_crop_image(Image.open(seq_fronts[i]), scale=self.scale, crop=self.input_resolution))))
# data['seg_gts'].append(F.one_hot(torch.from_numpy(np.array(
# scale_and_crop_image(Image.open(seq_seg_gts[i]), scale=self.scale, crop=self.input_resolution, is_seg_gt=True))).to(dtype=torch.int64),28).permute(2,0,1))
temp = np.load(seq_segs[i])
temp = np.repeat(temp, repeats=3, axis=2)
data['segs'].append(torch.from_numpy(temp).permute(2,0,1))
data['seg_gts'].append(torch.from_numpy(np.array(
scale_and_crop_image(Image.open(seq_seg_gts[i]), scale=self.scale, crop=self.input_resolution, is_seg_gt=True))))
if not self.ignore_sides:
data['lefts'].append(torch.from_numpy(np.array(
scale_and_crop_image(Image.open(seq_lefts[i]), scale=self.scale, crop=self.input_resolution))))
data['rights'].append(torch.from_numpy(np.array(
scale_and_crop_image(Image.open(seq_rights[i]), scale=self.scale, crop=self.input_resolution))))
if not self.ignore_rear:
data['rears'].append(torch.from_numpy(np.array(
scale_and_crop_image(Image.open(seq_rears[i]), scale=self.scale, crop=self.input_resolution))))
lidar_unprocessed = np.load(seq_lidars[i])[...,:3] # lidar: XYZI
full_lidar.append(lidar_unprocessed)
tl_json_data = json.load(open(seq_jsons[i],'r'))
data['tl_gts'].append(tl_json_data['is_red_light_present'])
# fix for theta=nan in some measurements
if np.isnan(seq_theta[i]):
seq_theta[i] = 0.
ego_x = seq_x[i]
ego_y = seq_y[i]
ego_theta = seq_theta[i]
# future frames
for i in range(self.seq_len, self.seq_len + self.pred_len):
lidar_unprocessed = np.load(seq_lidars[i])
full_lidar.append(lidar_unprocessed)
# lidar and waypoint processing to local coordinates
waypoints = []
for i in range(self.seq_len + self.pred_len):
# waypoint is the transformed version of the origin in local coordinates
# we use 90-theta instead of theta
# LBC code uses 90+theta, but x is to the right and y is downwards here
local_waypoint = transform_2d_points(np.zeros((1,3)),
np.pi/2-seq_theta[i], -seq_x[i], -seq_y[i], np.pi/2-ego_theta, -ego_x, -ego_y)
waypoints.append(tuple(local_waypoint[0,:2]))
# process only past lidar point clouds
if i < self.seq_len:
# convert coordinate frame of point cloud
full_lidar[i][:,1] *= -1 # inverts x, y
full_lidar[i] = transform_2d_points(full_lidar[i],
np.pi/2-seq_theta[i], -seq_x[i], -seq_y[i], np.pi/2-ego_theta, -ego_x, -ego_y)
lidar_processed = lidar_to_histogram_features(full_lidar[i], crop=self.input_resolution)
data['lidars'].append(lidar_processed)
data['waypoints'] = waypoints
# convert x_command, y_command to local coordinates
# taken from LBC code (uses 90+theta instead of theta)
R = np.array([
[np.cos(np.pi/2+ego_theta), -np.sin(np.pi/2+ego_theta)],
[np.sin(np.pi/2+ego_theta), np.cos(np.pi/2+ego_theta)]
])
local_command_point = np.array([self.x_command[index]-ego_x, self.y_command[index]-ego_y])
local_command_point = R.T.dot(local_command_point)
data['target_point'] = tuple(local_command_point)
data['steer'] = self.steer[index]
data['throttle'] = self.throttle[index]
data['brake'] = self.brake[index]
data['command'] = self.command[index]
data['velocity'] = self.velocity[index]
return data
def lidar_to_histogram_features(lidar, crop=256):
"""
Convert LiDAR point cloud into 2-bin histogram over 256x256 grid
"""
def splat_points(point_cloud):
# 256 x 256 grid
pixels_per_meter = 8
hist_max_per_pixel = 5
x_meters_max = 16
y_meters_max = 32
xbins = np.linspace(-2*x_meters_max, 2*x_meters_max+1, 2*x_meters_max*pixels_per_meter+1)
ybins = np.linspace(-y_meters_max, 0, y_meters_max*pixels_per_meter+1)
hist = np.histogramdd(point_cloud[...,:2], bins=(xbins, ybins))[0]
hist[hist>hist_max_per_pixel] = hist_max_per_pixel
overhead_splat = hist/hist_max_per_pixel
return overhead_splat
below = lidar[lidar[...,2]<=-2.0]
above = lidar[lidar[...,2]>-2.0]
below_features = splat_points(below)
above_features = splat_points(above)
features = np.stack([below_features, above_features], axis=-1)
features = np.transpose(features, (2, 0, 1)).astype(np.float32)
return features
def scale_and_crop_image(image, scale=1, crop=256, is_seg_gt=False):
"""
Scale and crop a PIL image, returning a channels-first numpy array.
"""
# image = Image.open(filename)
(width, height) = (int(image.width // scale), int(image.height // scale))
im_resized = image.resize((width, height))
image = np.asarray(im_resized)
start_x = height//2 - crop//2
start_y = width//2 - crop//2
cropped_image = image[start_x:start_x+crop, start_y:start_y+crop]
if is_seg_gt:
return cropped_image
cropped_image = np.transpose(cropped_image, (2,0,1))
return cropped_image
def transform_2d_points(xyz, r1, t1_x, t1_y, r2, t2_x, t2_y):
"""
Build a rotation matrix and take the dot product.
"""
# z value to 1 for rotation
xy1 = xyz.copy()
xy1[:,2] = 1
c, s = np.cos(r1), np.sin(r1)
r1_to_world = np.matrix([[c, s, t1_x], [-s, c, t1_y], [0, 0, 1]])
# np.dot converts to a matrix, so we explicitly change it back to an array
world = np.asarray(r1_to_world @ xy1.T)
c, s = np.cos(r2), np.sin(r2)
r2_to_world = np.matrix([[c, s, t2_x], [-s, c, t2_y], [0, 0, 1]])
world_to_r2 = np.linalg.inv(r2_to_world)
out = np.asarray(world_to_r2 @ world).T
# reset z-coordinate
out[:,2] = xyz[:,2]
return out