-
Notifications
You must be signed in to change notification settings - Fork 2
/
data.py
493 lines (464 loc) · 21 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import random
from typing import List
from .jaad_trans import *
from .pie_trans import *
from .titan_trans import *
class TransDataset:
"""
Unified class for using data from JAAD, PIE and TITAN dataset.
"""
def __init__(self, data_paths, image_set="all", subset='default', verbose=False):
dataset = {}
assert image_set in ['train', 'test', 'val', "all"], " Name should be train, test, val or all"
for d in list(data_paths.keys()):
assert d in ['JAAD', 'PIE', 'TITAN'], " Available datasets are JAAD, PIE and TITAN"
if d == "JAAD":
dataset['JAAD'] = JaadTransDataset(
jaad_anns_path=data_paths['JAAD']['anns'],
split_vids_path=data_paths['JAAD']['split'],
image_set=image_set,
subset=subset, verbose=verbose)
elif d == "PIE":
dataset['PIE'] = PieTransDataset(
pie_anns_path=data_paths['PIE']['anns'],
image_set=image_set, verbose=verbose)
elif d == "TITAN":
dataset['TITAN'] = TitanTransDataset(
anns_dir=data_paths['TITAN']['anns'],
split_vids_path=data_paths['TITAN']['split'],
image_set=image_set, verbose=verbose)
self.dataset = dataset
self.name = image_set
self.subset = subset
def __repr__(self):
return f"TransDataset(image_set={self.name}, jaad_subset={self.subset})"
def extract_trans_frame(self, mode="GO", frame_ahead=0, fps=10, verbose=False) -> dict:
ds = list(self.dataset.keys())
samples = {}
for d in ds:
samples_new = self.dataset[d].extract_trans_frame(mode=mode, frame_ahead=frame_ahead, fps=fps)
samples.update(samples_new)
if verbose:
ids = list(samples.keys())
pids = []
for idx in ids:
pids.append(samples[idx]['old_id'])
print(f"Extract {len(pids)} {mode} frame samples from {self.name} dataset,")
print(f"samples contain {len(set(pids))} unique pedestrians.")
return samples
def extract_trans_history(self, mode="GO", fps=10, max_frames=None, post_frames=0, verbose=False) -> dict:
"""
Extract the whole history of pedestrian up to the frame when transition happens
:params: mode: target transition type, "GO" or "STOP"
fps: frame-per-second, sampling rate of extracted sequences, default 10
max_frames: maximum number of frames in one history
post_frames: number of frames included after the transition
verbose: optional printing of sample statistics
"""
assert isinstance(fps, int) and 30 % fps == 0, "impossible fps"
ds = list(self.dataset.keys())
samples = {}
for d in ds:
samples_new = self.dataset[d].extract_trans_history(mode=mode, fps=fps, max_frames=max_frames,
post_frames=post_frames)
samples.update(samples_new)
if verbose:
ids = list(samples.keys())
pids = []
num_frames = 0
for idx in ids:
pids.append(samples[idx]['old_id'])
num_frames += len(samples[idx]['frame'])
print(f"Extract {len(pids)} {mode} history samples from {self.name} dataset,")
print(f"samples contain {len(set(pids))} unique pedestrians and {num_frames} frames.")
return samples
def extract_non_trans(self, fps=10, max_frames=None, verbose=False) -> dict:
assert isinstance(fps, int) and 30 % fps == 0, "impossible fps"
ds = list(self.dataset.keys())
samples = {'walking': {}, 'standing': {}}
for d in ds:
# Set the number of samples needed in TITAN
if d == 'TITAN':
if self.name == 'all':
n_titan = 600
elif self.name == 'train':
n_titan = 300
elif self.name == 'val':
n_titan = 200
else:
n_titan = 100
samples_new = self.dataset[d].extract_non_trans(fps=fps, max_frames=max_frames, max_samples=n_titan)
else:
samples_new = self.dataset[d].extract_non_trans(fps=fps, max_frames=max_frames)
samples['walking'].update(samples_new['walking'])
samples['standing'].update(samples_new['standing'])
if verbose:
keys_w = list(samples['walking'].keys())
keys_s = list(samples['standing'].keys())
pid_w = []
pid_s = []
n_w = 0
n_s = 0
for kw in keys_w:
pid_w.append(samples['walking'][kw]['old_id'])
n_w += len(samples['walking'][kw]['frame'])
for ks in keys_s:
pid_s.append(samples['standing'][ks]['old_id'])
n_s += len(samples['standing'][ks]['frame'])
print(f"Extract Non-transition samples from {self.name} dataset :")
print(f"Walking: {len(pid_w)} samples, {len(set(pid_w))} unique pedestrians and {n_w} frames.")
print(f"Standing: {len(pid_s)} samples, {len(set(pid_s))} unique pedestrians and {n_s} frames.")
return samples
def balance_frame_sample(samples, seed=99, balancing_ratio=1, verbose=True) -> dict:
"""
Balances the number of positive and negative samples by randomly sampling
from the more represented samples with given ratio. Only works for binary classes.
"""
random.seed(seed)
ids = list(samples.keys())
ids_j = []
ids_p = []
ids_t = []
ids_new = []
for k in ids:
if samples[k]['source'] == "JAAD":
ids_j.append(k)
elif samples[k]['source'] == "PIE":
ids_p.append(k)
elif samples[k]['source'] == "TITAN":
ids_t.append(k)
# balance positive and negative samples within each dataset
for _ids in [ids_j, ids_p, ids_t]:
if len(_ids) == 0:
continue
source = samples[_ids[0]]['source']
ps = []
ns = []
for i in range(len(_ids)):
key = _ids[i]
if samples[key]['trans_label'] == 1:
ps.append(key)
else:
ns.append(key)
size = int(min(len(ps), len(ns)) * balancing_ratio)
size = max(len(ps), len(ns)) if size > max(len(ps), len(ns)) else size
ps_new = random.sample(ps, size) if len(ps) > len(ns) else ps
ns_new = random.sample(ns, size) if len(ps) < len(ns) else ns
if verbose:
print(f"Perform sample balancing for {source}:")
print(f'Orignal samples: P {len(ps)} , N {len(ns)}')
print(f'Balanced samples:P {len(ps_new)}, N {len(ns_new)}')
ids_new = ids_new + ps_new + ns_new
# balanced samples
random.shuffle(ids_new)
samples_new = {}
for key in ids_new:
samples_new[key] = copy.deepcopy(samples[key])
return samples_new
def extract_pred_frame(trans, non_trans=None, pred_ahead=0, balancing_ratio=None,
bbox_min=0, seed=None, neg_in_trans=True, verbose=False) -> dict:
"""
Extract the frames in history for transition prediction task.
:params: trans: transition history samples, i.e. GO or STOP
non-trans: history samples containing no transitions
pred_ahead: frame to predicted in advance, whether the trnasition occur in ~ frames.
balancing_ratio: ratio between positive and negative frame instances
bbox_min: minimum width of the pedestrian bounding box
seed: random used during balancing
verbose: optional printing
"""
assert isinstance(pred_ahead, int) and pred_ahead >= 0, "Invalid prediction length."
ids_trans = list(trans.keys())
samples = {}
n_1 = 0
if isinstance(bbox_min, int):
bbox_min = (bbox_min, bbox_min)
for idx in ids_trans:
frames = copy.deepcopy(trans[idx]['frame'])
bbox = copy.deepcopy(trans[idx]['bbox'])
action = copy.deepcopy(trans[idx]['action'])
if "behavior" in list(trans[idx].keys()):
behavior = copy.deepcopy(trans[idx]['behavior'])
else:
behavior = []
if "attributes" in list(trans[idx].keys()):
attributes = copy.deepcopy(trans[idx]['attributes'])
else:
attributes = []
if "traffic_light" in list(trans[idx].keys()):
traffic_light = copy.deepcopy(trans[idx]['traffic_light'])
else:
traffic_light = []
d_pre = trans[idx]['pre_state']
n_frames = len(frames)
fps = trans[idx]['fps']
source = trans[idx]['source']
step = 60 // fps if source == 'TITAN' else 30 // fps
for i in range(max(0, n_frames - d_pre), n_frames - 1):
if abs(bbox[i][2] - bbox[i][0]) < bbox_min[0]:
continue
key = idx + f"_f{frames[i]}"
TTE = (frames[-1] - frames[i]) / (step * fps)
if TTE > pred_ahead / fps:
trans_label = 0
key = None
if neg_in_trans:
key = idx + f"_f{frames[i]}"
else:
trans_label = 1
n_1 += 1
if key is not None:
samples[key] = {}
samples[key]['source'] = trans[idx]['source']
if samples[key]['source'] == 'PIE':
samples[key]['set_number'] = trans[idx]['set_number']
samples[key]['video_number'] = trans[idx]['video_number']
samples[key]['frame'] = frames[i]
samples[key]['bbox'] = bbox[i]
samples[key]['action'] = action[i]
samples[key]['behavior'] = behavior[i] if len(behavior) > 0 else float('nan')
samples[key]['attributes'] = attributes
samples[key]['traffic_light'] = traffic_light[i] if len(traffic_light) > 0 else float('nan')
samples[key]['trans_label'] = trans_label
samples[key]['TTE'] = TTE
# negative instances from all examples
if non_trans is not None:
action_type = 'walking' if trans[ids_trans[0]]['type'] == 'STOP' else 'standing'
ids_non_trans = list(non_trans[action_type].keys())
for idx in ids_non_trans:
frames = copy.deepcopy(non_trans[action_type][idx]['frame'])
bbox = copy.deepcopy(non_trans[action_type][idx]['bbox'])
action = copy.deepcopy(non_trans[action_type][idx]['action'])
if "behavior" in list(non_trans[action_type][idx].keys()):
behavior = copy.deepcopy(non_trans[action_type][idx]['behavior'])
else:
behavior = []
if "attributes" in list(non_trans[action_type][idx].keys()):
attributes = copy.deepcopy(non_trans[action_type][idx]['attributes'])
else:
attributes = []
if "traffic_light" in list(non_trans[action_type][idx].keys()):
traffic_light = copy.deepcopy(non_trans[action_type][idx]['traffic_light'])
else:
traffic_light = []
for i in range(len(frames)):
if abs(bbox[i][2] - bbox[i][0]) < bbox_min[1]:
continue
key = idx + f"_f{frames[i]}"
samples[key] = {}
samples[key]['source'] = non_trans[action_type][idx]['source']
if samples[key]['source'] == 'PIE':
samples[key]['set_number'] = non_trans[action_type][idx]['set_number']
samples[key]['video_number'] = non_trans[action_type][idx]['video_number']
samples[key]['frame'] = frames[i]
samples[key]['bbox'] = bbox[i]
samples[key]['action'] = action[i]
samples[key]['behavior'] = behavior[i] if len(behavior) > 0 else float('nan')
samples[key]['attributes'] = attributes
samples[key]['traffic_light'] = traffic_light[i] if len(traffic_light) > 0 else float('nan')
samples[key]['trans_label'] = 0
samples[key]['TTE'] = float('nan')
if verbose:
if n_1 > 0:
ratio = (len(samples.keys()) - n_1) / n_1
else:
ratio = 999.99
print(f'Extract {len(samples.keys())} frame samples from {len(trans.keys())} history sequences.')
print('1/0 ratio: 1 : {:.2f}'.format(ratio))
print(f'predicting-ahead frames: {pred_ahead}')
if balancing_ratio is not None:
samples = balance_frame_sample(samples=samples, seed=seed, balancing_ratio=balancing_ratio, verbose=verbose)
return samples
def extract_pred_sequence(trans, non_trans=None, pred_ahead=0, balancing_ratio=None,
bbox_min=0, max_frames=None, seed=None, neg_in_trans=True, verbose=False) -> dict:
"""
Extract sequences for transition prediction task.
:params: trans: transition history samples, i.e. GO or STOP
non-trans: history samples containing no transitions
pred_ahead: frame to predicted in advance, whether the trnasition occur in X frames.
balancing_ratio: ratio between positive and negative frame instances
bbox_min: minimum width of the pedestrian bounding box
max_frames: maximum frames in one sequence sample
seed: random used during balancing
verbose: optional printing
"""
assert isinstance(pred_ahead, int) and pred_ahead >= 0, "Invalid prediction length."
ids_trans = list(trans.keys())
samples = {}
n_1 = 0
if isinstance(bbox_min, int):
bbox_min = (bbox_min, bbox_min)
for idx in ids_trans:
frames = copy.deepcopy(trans[idx]['frame'])
bbox = copy.deepcopy(trans[idx]['bbox'])
action = copy.deepcopy(trans[idx]['action'])
if "behavior" in list(trans[idx].keys()):
behavior = copy.deepcopy(trans[idx]['behavior'])
else:
behavior = []
if "attributes" in list(trans[idx].keys()):
attributes = copy.deepcopy(trans[idx]['attributes'])
else:
attributes = []
if "traffic_light" in list(trans[idx].keys()):
traffic_light = copy.deepcopy(trans[idx]['traffic_light'])
else:
traffic_light = []
d_pre = trans[idx]['pre_state']
n_frames = len(frames)
fps = trans[idx]['fps']
source = trans[idx]['source']
step = 60 // fps if source == 'TITAN' else 30 // fps
for i in range(max(0, n_frames - d_pre), n_frames - 1):
if abs(bbox[i][2] - bbox[i][0]) < bbox_min[0]:
continue
key = idx + f"_f{frames[i]}"
TTE = (frames[-1] - frames[i]) / (step * fps)
if TTE > pred_ahead / fps:
trans_label = 0
key = None
if neg_in_trans:
key = idx + f"_f{frames[i]}"
else:
trans_label = 1
n_1 += 1
if key is not None:
samples[key] = {}
samples[key]['source'] = trans[idx]['source']
if samples[key]['source'] == 'PIE':
samples[key]['set_number'] = trans[idx]['set_number']
samples[key]['video_number'] = trans[idx]['video_number']
# t = 0 if max_frames is None else i - max_frames + 1
if max_frames is None:
t = 0
else:
if i < max_frames - 1:
t = 0
else:
t = i - max_frames + 1
samples[key]['frame'] = frames[t:i + 1]
samples[key]['bbox'] = bbox[t:i + 1]
samples[key]['action'] = action[t:i + 1]
if len(traffic_light) > 0:
samples[key]['traffic_light'] = traffic_light[t:i + 1]
else:
pass
if len(behavior) > 0:
samples[key]['behavior'] = behavior[t:i + 1]
else:
pass
if len(attributes) > 0:
samples[key]['attributes'] = attributes
else:
pass
samples[key]['trans_label'] = trans_label
samples[key]['TTE'] = TTE
# negative instances from all examples
if non_trans is not None:
action_type = 'walking' if trans[ids_trans[0]]['type'] == 'STOP' else 'standing'
ids_non_trans = list(non_trans[action_type].keys())
for idx in ids_non_trans:
frames = copy.deepcopy(non_trans[action_type][idx]['frame'])
bbox = copy.deepcopy(non_trans[action_type][idx]['bbox'])
action = copy.deepcopy(non_trans[action_type][idx]['action'])
if "behavior" in list(non_trans[action_type][idx].keys()):
behavior = copy.deepcopy(non_trans[action_type][idx]['behavior'])
else:
behavior = []
if "attributes" in list(non_trans[action_type][idx].keys()):
attributes = copy.deepcopy(non_trans[action_type][idx]['attributes'])
else:
attributes = []
if "traffic_light" in list(non_trans[action_type][idx].keys()):
traffic_light = copy.deepcopy(non_trans[action_type][idx]['traffic_light'])
else:
traffic_light = []
for i in range(len(frames)):
if abs(bbox[i][2] - bbox[i][0]) < bbox_min[1]:
continue
key = idx + f"_f{frames[i]}"
samples[key] = {}
samples[key]['source'] = non_trans[action_type][idx]['source']
if samples[key]['source'] == 'PIE':
samples[key]['set_number'] = non_trans[action_type][idx]['set_number']
samples[key]['video_number'] = non_trans[action_type][idx]['video_number']
# t = 0 if max_frames is None else i - max_frames + 1
if max_frames is None:
t = 0
else:
if i < max_frames - 1:
t = 0
else:
t = i - max_frames + 1
samples[key]['frame'] = frames[t:i + 1]
samples[key]['bbox'] = bbox[t:i + 1]
samples[key]['action'] = action[t:i + 1]
if len(traffic_light) > 0:
samples[key]['traffic_light'] = traffic_light[t:i + 1]
else:
pass
if len(behavior) > 0:
samples[key]['behavior'] = behavior[t:i + 1]
else:
pass
if len(attributes) > 0:
samples[key]['attributes'] = attributes
else:
pass
samples[key]['trans_label'] = 0
samples[key]['TTE'] = float('nan')
if verbose:
if n_1 > 0:
ratio = (len(samples.keys()) - n_1) / n_1
else:
ratio = 999.99
print(f'Extract {len(samples.keys())} sequence samples from {len(trans.keys())} history.')
print('1/0 ratio: 1 : {:.2f}'.format(ratio))
print(f'predicting-ahead frames: {pred_ahead}')
if balancing_ratio is not None:
samples = balance_frame_sample(samples=samples, seed=seed, balancing_ratio=balancing_ratio, verbose=verbose)
return samples
def mix_dataset_samples(datasets: List[dict], ratio=-1.0):
ids_1 = list(datasets[0].keys())
ids_2 = list(datasets[1].keys())
ids_p1 = []
ids_n1 = []
ids_p2 = []
ids_n2 = []
for idx in ids_1:
if datasets[0][idx]['TTE'] < 0:
ids_n1.append(idx)
else:
ids_p1.append(idx)
for idx in ids_2:
if datasets[1][idx]['TTE'] < 0:
ids_n2.append(idx)
else:
ids_p2.append(idx)
n_p = min(len(ids_p1), len(ids_p2))
if len(ids_p1) <= len(ids_p2):
size = min(int(len(ids_p1) * ratio), len(ids_p2)) if ratio > 0 else len(ids_p2)
ids_p1_new = ids_p1
ids_p2_new = ids_p2[: size]
else:
size = min(int(len(ids_p2) * ratio), len(ids_p1)) if ratio > 0 else len(ids_p1)
ids_p1_new = ids_p1[:size]
ids_p2_new = ids_p2
if len(ids_n1) <= len(ids_n2):
size = min(int(len(ids_n1) * ratio), len(ids_n2)) if ratio > 0 else len(ids_n2)
ids_n1_new = ids_n1
ids_n2_new = ids_n2[: size]
else:
size = min(int(len(ids_n2) * ratio), len(ids_n1)) if ratio > 0 else len(ids_n1)
ids_n1_new = ids_n1[:size]
ids_n2_new = ids_n2
ids_1_new = ids_p1_new + ids_n1_new
ids_2_new = ids_p2_new + ids_n2_new
d1_new = {}
d2_new = {}
for key in ids_1_new:
d1_new[key] = copy.deepcopy(datasets[0][key])
for key in ids_2_new:
d2_new[key] = copy.deepcopy(datasets[1][key])
d1_new.update(d2_new)
return d1_new