forked from PaulKMueller/llama_traffic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaymo_visualize.py
791 lines (662 loc) · 20.4 KB
/
waymo_visualize.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
import time
import uuid
from matplotlib import cm
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import HTML
import itertools
import tensorflow as tf
import pandas as pd
def create_figure_and_axes(size_pixels):
"""Initializes a unique figure and axes for plotting."""
fig, ax = plt.subplots(1, 1, num=uuid.uuid4())
# Sets output image to pixel resolution.
dpi = 100
size_inches = size_pixels / dpi
fig.set_size_inches([size_inches, size_inches])
fig.set_dpi(dpi)
fig.set_facecolor("white")
ax.set_facecolor("white")
ax.xaxis.label.set_color("black")
ax.tick_params(axis="x", colors="black")
ax.yaxis.label.set_color("black")
ax.tick_params(axis="y", colors="black")
fig.set_tight_layout(True)
ax.grid(False)
return fig, ax
def fig_canvas_image(fig):
"""Returns a [H, W, 3] uint8 np.array
image from fig.canvas.tostring_rgb()."""
# Just enough margin in the figure to display xticks and yticks.
fig.subplots_adjust(
left=0.08, bottom=0.08, right=0.98, top=0.98, wspace=0.0, hspace=0.0
)
fig.canvas.draw()
data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
return data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
def get_colormap(num_agents):
"""Compute a color map array of shape [num_agents, 4]."""
colors = cm.get_cmap("jet", num_agents)
colors = colors(range(num_agents))
np.random.shuffle(colors)
return colors
def get_viewport(all_states, all_states_mask):
"""Gets the region containing the data.
Args:
all_states: states of agents as an array of shape [num_agents, num_steps,
2].
all_states_mask: binary mask of shape [num_agents, num_steps] for
`all_states`.
Returns:
center_y: float. y coordinate for center of data.
center_x: float. x coordinate for center of data.
width: float. Width of data.
"""
valid_states = all_states[all_states_mask]
all_y = valid_states[..., 1]
all_x = valid_states[..., 0]
center_y = (np.max(all_y) + np.min(all_y)) / 2
center_x = (np.max(all_x) + np.min(all_x)) / 2
range_y = np.ptp(all_y)
range_x = np.ptp(all_x)
width = max(range_y, range_x)
return center_y, center_x, width
def visualize_one_step(
states,
mask,
roadgraph,
title,
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids=None,
specific_id=None,
size_pixels=1000,
):
"""Generate visualization for a single step."""
# Create figure and axes.
fig, ax = create_figure_and_axes(size_pixels=size_pixels)
# Plot roadgraph.
rg_pts = roadgraph[:, :2].T
ax.plot(rg_pts[0, :], rg_pts[1, :], "k.", alpha=1, ms=2)
# If a specific ID is provided, filter the states,
# masks, and colors to only include that ID.
if specific_id is not None:
n = 128
mask = np.full(n, False)
index_of_id = np.where(agent_ids == float(specific_id))
mask[index_of_id] = True
masked_x = states[:, 0][mask]
masked_y = states[:, 1][mask]
colors = color_map[mask]
# Plot agent current position.
ax.scatter(
masked_x,
masked_y,
marker="o",
linewidths=3,
color=colors,
)
if with_ids:
for x, y, agent_id in zip(
# Iterate through the masked agent IDs
masked_x,
masked_y,
agent_ids[mask],
):
# Plot the ID
ax.text(
x,
y,
str(agent_id),
color="black",
fontsize=20,
ha="center",
va="center",
)
# Title.
ax.set_title(title)
# Set axes. Should be at least 10m on a side and cover 160% of agents.
size = max(10, width * 1.0)
ax.axis(
[
-size / 2 + center_x,
size / 2 + center_x,
-size / 2 + center_y,
size / 2 + center_y,
]
)
ax.set_aspect("equal")
image = fig_canvas_image(fig)
plt.close(fig)
return image
def visualize_all_agents_smooth(
decoded_example,
with_ids=False,
specific_id=None,
size_pixels=1000,
):
"""Visualizes all agent predicted trajectories in a serie of images.
Args:
decoded_example: Dictionary containing agent info about all modeled agents.
size_pixels: The size in pixels of the output image.
Returns:
T of [H, W, 3] uint8 np.arrays of the drawn matplotlib's figure canvas.
"""
agent_ids = decoded_example["state/id"].numpy()
# [num_agents, num_past_steps, 2] float32.
past_states = tf.stack(
[decoded_example["state/past/x"], decoded_example["state/past/y"]], -1
).numpy()
past_states_mask = decoded_example["state/past/valid"].numpy() > 0.0
# [num_agents, 1, 2] float32.
current_states = tf.stack(
[decoded_example["state/current/x"], decoded_example["state/current/y"]], -1
).numpy()
current_states_mask = decoded_example["state/current/valid"].numpy() > 0.0
# [num_agents, num_future_steps, 2] float32.
future_states = tf.stack(
[decoded_example["state/future/x"], decoded_example["state/future/y"]], -1
).numpy()
future_states_mask = decoded_example["state/future/valid"].numpy() > 0.0
# [num_points, 3] float32.
roadgraph_xyz = decoded_example["roadgraph_samples/xyz"].numpy()
num_agents, num_past_steps, _ = past_states.shape
num_future_steps = future_states.shape[1]
color_map = get_colormap(num_agents)
# [num_agens, num_past_steps + 1 + num_future_steps, depth] float32.
all_states = np.concatenate([past_states, current_states, future_states], 1)
# [num_agens, num_past_steps + 1 + num_future_steps] float32.
all_states_mask = np.concatenate(
[past_states_mask, current_states_mask, future_states_mask], 1
)
center_y, center_x, width = get_viewport(all_states, all_states_mask)
images = []
# Generate images from past time steps.
for i, (s, m) in enumerate(
zip(
np.split(past_states, num_past_steps, 1),
np.split(past_states_mask, num_past_steps, 1),
)
):
im = visualize_one_step(
s[:, 0],
m[:, 0],
roadgraph_xyz,
"past: %d" % (num_past_steps - i),
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
)
images.append(im)
# Generate one image for the current time step.
s = current_states
m = current_states_mask
im = visualize_one_step(
s[:, 0],
m[:, 0],
roadgraph_xyz,
"current",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
)
images.append(im)
# Generate images from future time steps.
for i, (s, m) in enumerate(
zip(
np.split(future_states, num_future_steps, 1),
np.split(future_states_mask, num_future_steps, 1),
)
):
im = visualize_one_step(
s[:, 0],
m[:, 0],
roadgraph_xyz,
"future: %d" % (i + 1),
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
)
images.append(im)
return images
def create_animation(images):
"""Creates a Matplotlib animation of the given images.
Args:
images: A list of numpy arrays representing the images.
Returns:
A matplotlib.animation.Animation.
Usage:
anim = create_animation(images)
anim.save('/tmp/animation.avi')
HTML(anim.to_html5_video())
"""
plt.ioff()
fig, ax = plt.subplots()
dpi = 100
size_inches = 1000 / dpi
fig.set_size_inches([size_inches, size_inches])
plt.ion()
def animate_func(i):
ax.imshow(images[i])
ax.set_xticks([])
ax.set_yticks([])
ax.grid("off")
anim = animation.FuncAnimation(
fig, animate_func, frames=len(images) // 2, interval=100
)
plt.close(fig)
return anim
def visualize_trajectory_one_step(
ax,
states,
mask,
roadgraph,
title,
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids=None,
specific_id=None,
size_pixels=1000,
alpha=1.0,
):
"""Generate visualization for a single step."""
# Plot roadgraph.
rg_pts = roadgraph[:, :2].T
# Reduced alpha for roadgraph to keep it subtle
ax.plot(rg_pts[0, :], rg_pts[1, :], "k.", alpha=0.5, ms=2)
if specific_id is not None:
n = 128 # For example, an array of size 5
mask = np.full(n, False)
index_of_id = np.where(agent_ids == float(specific_id))
mask[index_of_id] = True
masked_x = states[:, 0][mask]
masked_y = states[:, 1][mask]
colors = color_map[mask]
# Plot agent current position.
ax.scatter(
masked_x,
masked_y,
marker="o",
linewidths=3,
color=colors,
alpha=alpha, # You can adjust the alpha depending on your preference.
)
if with_ids:
for x, y, agent_id in zip(masked_x, masked_y, agent_ids[mask]):
ax.text(
x,
y,
str(agent_id),
color="black",
fontsize=20,
ha="center",
va="center",
)
# Set axes.
size = max(10, width * 1.0)
ax.axis(
[
-size / 2 + center_x,
size / 2 + center_x,
-size / 2 + center_y,
size / 2 + center_y,
]
)
ax.set_aspect("equal")
def visualize_coordinates(decoded_example, coordinates, size_pixels=1000):
plot = visualize_map(decoded_example=decoded_example)
print(type(coordinates))
# Plot coordinates on map
for _, coordinate in coordinates.iterrows():
plot.plot(coordinate["X"], coordinate["Y"], "ro", markersize=5)
return plot
def visualize_coordinates_one_step(
ax,
states,
mask,
roadgraph,
title,
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids=None,
specific_id=None,
size_pixels=1000,
alpha=1.0,
):
"""Generate visualization for a single step."""
# Plot roadgraph.
rg_pts = roadgraph[:, :2].T
# Reduced alpha for roadgraph to keep it subtle
ax.plot(rg_pts[0, :], rg_pts[1, :], "k.", alpha=0.5, ms=2)
if specific_id is not None:
n = 128 # For example, an array of size 5
mask = np.full(n, False)
index_of_id = np.where(agent_ids == float(specific_id))
mask[index_of_id] = True
masked_x = states[:, 0][mask]
masked_y = states[:, 1][mask]
colors = color_map[mask]
# Plot agent current position.
ax.scatter(
masked_x,
masked_y,
marker="o",
linewidths=3,
color=colors,
alpha=alpha, # You can adjust the alpha depending on your preference.
)
if with_ids:
for x, y, agent_id in zip(masked_x, masked_y, agent_ids[mask]):
ax.text(
x,
y,
str(agent_id),
color="black",
fontsize=20,
ha="center",
va="center",
)
# Set axes.
size = max(10, width * 1.0)
ax.axis(
[
-size / 2 + center_x,
size / 2 + center_x,
-size / 2 + center_y,
size / 2 + center_y,
]
)
ax.set_aspect("equal")
def visualize_raw_coordinates_without_scenario(
coordinates, title="Trajectory Visualization", padding=10
):
"""
Visualize the trajectory specified by coordinates, scaling to fit the trajectory size.
Args:
- coordinates: A DataFrame with 'X' and 'Y' columns, or an array-like structure representing trajectory points.
- title: The title of the plot.
- padding: Extra space around the trajectory bounds.
"""
fig, ax = plt.subplots(figsize=(10, 10)) # Create a figure and a set of subplots
# Check if coordinates is a Pandas DataFrame and convert if necessary
if isinstance(coordinates, np.ndarray):
coordinates = pd.DataFrame(coordinates, columns=["X", "Y"])
elif isinstance(coordinates, list):
coordinates = pd.DataFrame(coordinates, columns=["X", "Y"])
# Plot the trajectory
ax.plot(
coordinates["X"], coordinates["Y"], "ro-", markersize=5, linewidth=2
) # 'ro-' creates a red line with circle markers
# Determine the bounds of the trajectory
x_min, x_max = coordinates["X"].min(), coordinates["X"].max()
y_min, y_max = coordinates["Y"].min(), coordinates["Y"].max()
# Set the scale of the plot to the bounds of the trajectory with some padding
ax.set_xlim(x_min - padding, x_max + padding)
ax.set_ylim(y_min - padding, y_max + padding)
# Set aspect of the plot to be equal
ax.set_aspect("equal")
# Set title of the plot
ax.set_title(title)
# Remove axes for a cleaner look since there's no map
ax.axis("off")
return plt
def visualize_trajectory(
decoded_example, with_ids=False, specific_id=None, size_pixels=1000
):
"""Visualizes all agent predicted trajectories in a single image.
Args:
decoded_example: Dictionary containing agent info about all modeled agents.
size_pixels: The size in pixels of the output image.
"""
agent_ids = decoded_example["state/id"].numpy()
past_states = tf.stack(
[decoded_example["state/past/x"], decoded_example["state/past/y"]], -1
).numpy()
past_states_mask = decoded_example["state/past/valid"].numpy() > 0.0
current_states = tf.stack(
[decoded_example["state/current/x"], decoded_example["state/current/y"]], -1
).numpy()
current_states_mask = decoded_example["state/current/valid"].numpy() > 0.0
future_states = tf.stack(
[decoded_example["state/future/x"], decoded_example["state/future/y"]], -1
).numpy()
future_states_mask = decoded_example["state/future/valid"].numpy() > 0.0
roadgraph_xyz = decoded_example["roadgraph_samples/xyz"].numpy()
color_map = get_colormap(agent_ids.shape[0])
all_states = np.concatenate([past_states, current_states, future_states], 1)
all_states_mask = np.concatenate(
[past_states_mask, current_states_mask, future_states_mask], 1
)
center_y, center_x, width = get_viewport(all_states, all_states_mask)
# Creating one figure and axis to visualize all steps on the same plot
_, ax = create_figure_and_axes(size_pixels=size_pixels)
# Visualize past states
for s, m in zip(
np.split(past_states, past_states.shape[1], 1),
np.split(past_states_mask, past_states_mask.shape[1], 1),
):
visualize_trajectory_one_step(
ax,
s[:, 0],
m[:, 0],
roadgraph_xyz,
"past",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=0.5,
)
# Visualize current state
visualize_trajectory_one_step(
ax,
current_states[:, 0],
current_states_mask[:, 0],
roadgraph_xyz,
"current",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=1.0,
)
# Visualize future states
for s, m in zip(
np.split(future_states, future_states.shape[1], 1),
np.split(future_states_mask, future_states_mask.shape[1], 1),
):
visualize_trajectory_one_step(
ax,
s[:, 0],
m[:, 0],
roadgraph_xyz,
"future",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=0.7,
)
return plt
def visualize_map(decoded_example, with_ids=False, specific_id=None, size_pixels=1000):
"""Visualizes all agent predicted trajectories in a single image.
Args:
decoded_example: Dictionary containing agent info about all modeled agents.
size_pixels: The size in pixels of the output image.
"""
agent_ids = decoded_example["state/id"].numpy()
past_states = tf.stack(
[decoded_example["state/past/x"], decoded_example["state/past/y"]], -1
).numpy()
past_states_mask = decoded_example["state/past/valid"].numpy() > 0.0
current_states = tf.stack(
[decoded_example["state/current/x"], decoded_example["state/current/y"]], -1
).numpy()
current_states_mask = decoded_example["state/current/valid"].numpy() > 0.0
future_states = tf.stack(
[decoded_example["state/future/x"], decoded_example["state/future/y"]], -1
).numpy()
future_states_mask = decoded_example["state/future/valid"].numpy() > 0.0
roadgraph_xyz = decoded_example["roadgraph_samples/xyz"].numpy()
color_map = get_colormap(agent_ids.shape[0])
all_states = np.concatenate([past_states, current_states, future_states], 1)
all_states_mask = np.concatenate(
[past_states_mask, current_states_mask, future_states_mask], 1
)
center_y, center_x, width = get_viewport(all_states, all_states_mask)
# Creating one figure and axis to visualize all steps on the same plot
_, ax = create_figure_and_axes(size_pixels=size_pixels)
# Visualize past states
for s, m in zip(
np.split(past_states, past_states.shape[1], 1),
np.split(past_states_mask, past_states_mask.shape[1], 1),
):
visualize_map_one_step(
ax,
s[:, 0],
m[:, 0],
roadgraph_xyz,
"past",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=0.5,
)
# Visualize current state
visualize_map_one_step(
ax,
current_states[:, 0],
current_states_mask[:, 0],
roadgraph_xyz,
"current",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=1.0,
)
# Visualize future states
for s, m in zip(
np.split(future_states, future_states.shape[1], 1),
np.split(future_states_mask, future_states_mask.shape[1], 1),
):
visualize_map_one_step(
ax,
s[:, 0],
m[:, 0],
roadgraph_xyz,
"future",
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids,
specific_id,
size_pixels,
alpha=0.7,
)
return plt
def visualize_map_one_step(
ax,
states,
mask,
roadgraph,
title,
center_y,
center_x,
width,
color_map,
with_ids,
agent_ids=None,
specific_id=None,
size_pixels=1000,
alpha=1.0,
):
"""Generate visualization for a single step."""
# Plot roadgraph.
rg_pts = roadgraph[:, :2].T
# Reduced alpha for roadgraph to keep it subtle
ax.plot(rg_pts[0, :], rg_pts[1, :], "k.", alpha=0.5, ms=2)
n = 128 # For example, an array of size 5
mask = np.full(n, False)
masked_x = states[:, 0][mask]
masked_y = states[:, 1][mask]
colors = color_map[mask]
# Plot agent current position.
ax.scatter(
masked_x,
masked_y,
marker="o",
linewidths=3,
color=colors,
alpha=alpha, # You can adjust the alpha depending on your preference.
)
if with_ids:
for x, y, agent_id in zip(masked_x, masked_y, agent_ids[mask]):
ax.text(
x,
y,
str(agent_id),
color="black",
fontsize=20,
ha="center",
va="center",
)
# Set axes.
size = max(10, width * 1.0)
ax.axis(
[
-size / 2 + center_x,
size / 2 + center_x,
-size / 2 + center_y,
size / 2 + center_y,
]
)
ax.set_aspect("equal")