-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplot_on_video.py
341 lines (262 loc) · 12.5 KB
/
plot_on_video.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
import os
import numpy as np
import pickle
import torch
import cv2
import matplotlib.pyplot as plt
def world2image(traj_w, H_inv, background):
# Converts points from Euclidean to homogeneous space, by (x, y) → (x, y, 1)
traj_homog = np.hstack((traj_w, np.ones((traj_w.shape[0], 1)))).T
# to camera frame
traj_cam = np.matmul(H_inv, traj_homog)
# to pixel coords
a = traj_cam[2]
traj_uvz = np.transpose(traj_cam/a)
traj_uv = traj_uvz[:, :2]
return traj_uv[:, :2].astype(int)
def get_st_ed(batch_num):
cumsum = torch.cumsum(batch_num, dim=0)
st_ed = []
for idx in range(1, cumsum.shape[0]):
st_ed.append((int(cumsum[idx - 1]), int(cumsum[idx])))
st_ed.insert(0, (0, int(cumsum[0])))
return st_ed
def plot_trajectories(true_trajs, pred_trajs, obs_length, name, plot_directory, H_inv, background):
data_len = 1
fig, axes = plt.subplots(1, data_len)
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# plt.subplots_adjust(bottom = 0.35, top = 0.95)
ax = axes
origin = true_trajs[0]
true_trajs = true_trajs[1:]
traj_length, numNodes, _ = true_trajs.shape
width = 2
height = 2
traj_data = {}
for tstep in range(obs_length, traj_length):
pred_pos = pred_trajs[tstep, :]
true_pos = true_trajs[tstep, :]
for ped in range(numNodes):
if ped not in traj_data:
traj_data[ped] = [[], []]
traj_data[ped][0].append(true_pos[ped, :])
traj_data[ped][1].append(pred_pos[ped, :])
# Ground Truth Trajectory
ped_index = 0
select_ped = [0]
for j in traj_data:
# if j not in select_ped:
# continue
c = np.random.rand(3).tolist()
true_traj_ped = traj_data[j][0] # List of [x,y] elements
pred_traj_ped = traj_data[j][1]
if true_traj_ped == [] or pred_traj_ped == []:
continue
true_x = [p[0] for p in true_traj_ped]
true_y = [p[1] for p in true_traj_ped]
pred_x = [p[0] for p in pred_traj_ped]
pred_y = [p[1] for p in pred_traj_ped]
origin_x = [origin[j,0]]
origin_y = [origin[j,1]]
observed_x = origin_x + true_x[:7]
observed_y = origin_y + true_y[:7]
ground_truth_x = true_x[7:]
ground_truth_y = true_y[7:]
predicted_x = pred_x[7:]
predicted_y = pred_y[7:]
observed_trajectory = np.zeros((len(observed_x), 2))
ground_truth_trajectory = np.zeros((len(ground_truth_x), 2))
predicted_trajectory = np.zeros((len(predicted_x), 2))
for i in range(len(observed_trajectory)):
observed_trajectory[i][1] = observed_x[i]
observed_trajectory[i][0] = observed_y[i]
for i in range(len(ground_truth_trajectory)):
ground_truth_trajectory[i][1] = ground_truth_x[i]
ground_truth_trajectory[i][0] = ground_truth_y[i]
predicted_trajectory[i][1] = predicted_x[i]
predicted_trajectory[i][0] = predicted_y[i]
observed_pixels = world2image(observed_trajectory, H_inv, background) # observed_trajectory: Tx2 numpy array
ground_truth_pixels = world2image(ground_truth_trajectory, H_inv, background)
predicted_pixels = world2image(predicted_trajectory, H_inv, background)
extent = [0, background.shape[1], background.shape[0], 0]
ax.imshow(background, extent=extent, aspect='auto')
ax.plot(observed_pixels[:,0], observed_pixels[:,1], color=c, linestyle='dotted', linewidth=5,
label=f'true observed trajectory of {ped_index}')
ax.plot(ground_truth_pixels[:,0], ground_truth_pixels[:,1], color=c, linestyle='solid', linewidth=5,
label=f'true predicted trajectory of {ped_index}')
ax.plot(predicted_pixels[:,0], predicted_pixels[:,1], color=c, linestyle='dashed', linewidth=5,
label=f'predicted trajectory of {ped_index}')
ax.scatter(ground_truth_pixels[-1,0], ground_truth_pixels[-1,1], color=c, marker='o', s=100,
label=f'ground truth endpoint of {ped_index}')
ax.scatter(predicted_pixels[-1,0], predicted_pixels[-1,1], color=c, marker='*', s=100,
label=f'predicted endpoint of {ped_index}')
ax.set_xlim([0, background.shape[1]])
ax.set_ylim([background.shape[0], 0])
ax.axis('off')
# ax.axes.xaxis.set_visible(False)
# ax.axes.yaxis.set_visible(False)
# ax.axis('equal')
ped_index += 1
plt.tight_layout(pad=0)
# plt.show()
print()
plt.savefig(plot_directory + '/' + name + '.png')
def plot_trajectories_multimodality(true_trajs, pred_trajs, obs_length, name, plot_directory, H_inv, background):
data_len = 1
fig, axes = plt.subplots(1, data_len)
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# plt.subplots_adjust(bottom = 0.35, top = 0.95)
ax = axes
origin = true_trajs[0]
true_trajs = true_trajs[1:]
traj_length, numNodes, _ = true_trajs.shape
width = 2
height = 2
traj_data = {}
for tstep in range(obs_length, traj_length):
pred_pos = pred_trajs[:, tstep, :]
true_pos = true_trajs[tstep, :]
for ped in range(numNodes):
if ped not in traj_data:
traj_data[ped] = [[], []]
traj_data[ped][0].append(true_pos[ped, :])
traj_data[ped][1].append(pred_pos[:, ped, :])
# Ground Truth Trajectory
ped_index = 0
select_ped = [0]
for j in traj_data:
# if j not in select_ped:
# continue
c1 = np.random.rand(3).tolist()
c2 = np.random.rand(3).tolist()
c3 = np.random.rand(3).tolist()
c4 = np.random.rand(3).tolist()
c5 = np.random.rand(3).tolist()
true_traj_ped = traj_data[j][0] # List of [x,y] elements
pred_traj_ped = traj_data[j][1]
if true_traj_ped == [] or pred_traj_ped == []:
continue
true_x = [p[0] for p in true_traj_ped]
true_y = [p[1] for p in true_traj_ped]
pred_x = [p[:, 0] for p in pred_traj_ped]
pred_y = [p[:, 1] for p in pred_traj_ped]
origin_x = [origin[j,0]]
origin_y = [origin[j,1]]
observed_x = origin_x + true_x[:7]
observed_y = origin_y + true_y[:7]
ground_truth_x = true_x[7:]
ground_truth_y = true_y[7:]
predicted_x = pred_x[7:]
predicted_y = pred_y[7:]
observed_trajectory = np.zeros((len(observed_x), 2))
ground_truth_trajectory = np.zeros((len(ground_truth_x), 2))
predicted_trajectory = np.zeros((len(predicted_x), 2, 20))
for i in range(len(observed_trajectory)):
observed_trajectory[i][1] = observed_x[i]
observed_trajectory[i][0] = observed_y[i]
for i in range(len(ground_truth_trajectory)):
ground_truth_trajectory[i][1] = ground_truth_x[i]
ground_truth_trajectory[i][0] = ground_truth_y[i]
predicted_trajectory[i][1] = predicted_x[i].cpu()
predicted_trajectory[i][0] = predicted_y[i].cpu()
predicted_trajectory = np.transpose(predicted_trajectory, (2, 0, 1))
observed_pixels = world2image(observed_trajectory, H_inv, background) # observed_trajectory: Tx2 numpy array
ground_truth_pixels = world2image(ground_truth_trajectory, H_inv, background)
predicted_pixels = np.zeros_like(predicted_trajectory)
for i in range(len(predicted_trajectory)):
predicted_pixels[i] = world2image(predicted_trajectory[i], H_inv, background)
extent = [0, background.shape[1], background.shape[0], 0]
ax.imshow(background, extent=extent, aspect='auto')
ax.plot(observed_pixels[:,0], observed_pixels[:,1], color=c1, linestyle='dotted', linewidth=5,
label=f'true observed trajectory of {ped_index}')
ax.plot(ground_truth_pixels[:-1,0], ground_truth_pixels[:-1,1], color=c2, linestyle='dashed', linewidth=5,
label=f'true predicted trajectory of {ped_index}')
for i in range(len(predicted_trajectory)):
ax.plot(predicted_pixels[i,:-1,0], predicted_pixels[i,:-1,1], color=c3, linestyle='solid', linewidth=2,
label=f'predicted trajectory of {ped_index}')
ax.scatter(predicted_pixels[:, -1, 0], predicted_pixels[:, -1, 1], color=c4, marker='*', s=30,
label=f'predicted endpoint of {ped_index}')
ax.scatter(ground_truth_pixels[-1,0], ground_truth_pixels[-1,1], color=c5, marker='o', s=30,
label=f'ground truth endpoint of {ped_index}')
ax.set_xlim([0, background.shape[1]])
ax.set_ylim([background.shape[0], 0])
ax.axis('off')
# ax.axes.xaxis.set_visible(False)
# ax.axes.yaxis.set_visible(False)
# ax.axis('equal')
plt.show()
ped_index += 1
plt.tight_layout(pad=0)
plt.show()
print()
# plt.savefig(plot_directory + '/' + name + '.png')
# choose your algorithm
algorithm_name = 'DDL'
# Dataset name
dataset_name = 'zara1'
# the path to store the generated trajectory and truth trajectory
save_directory = f'./all_trajectory_result/{algorithm_name}/{dataset_name}/'
# load the homography matrix
H = (np.loadtxt(os.path.join(f'./dataset_ethucy/processed_dataset/generate_homography/homography_matrix/{dataset_name}/H.txt')))
H_inv = np.linalg.inv(H)
# load background figure
background_image = cv2.imread(f'./plot_on_video/{dataset_name}/video_image/1.png')
background_image = cv2.cvtColor(background_image, cv2.COLOR_BGR2RGB)
# load the index range between the first pedestrian and the last pedestrian for all batches
with open(save_directory + f'batch_pednum_{dataset_name}.pkl', 'rb') as f:
batch_pednum = pickle.load(f)
batch_pednum = batch_pednum['batch_pednum']
# load the ground truth trajectory and all sampled predicted trajectories for all batches
with open(save_directory + f'true_predicted_trajectory_{dataset_name}.pkl', 'rb') as f:
trajectory = pickle.load(f)
true_trajectory = trajectory['true_traj']
predicted_trajectory = trajectory['pred_traj']
# load the best sampled predicted trajectory for all batches
with open(save_directory + f'best_predicted_trajectory_{dataset_name}.pkl', 'rb') as f:
best_pred_trajectory = pickle.load(f)
best_pred_trajectory = best_pred_trajectory['best_pred_traj']
# Plot directory (the plot of the trajectory is stored here)
plot_directory = f'./plot_on_video/{dataset_name}/plot_trajectory_on_image/'
multi_plot_directory = plot_directory + 'multi'
if not os.path.exists(multi_plot_directory):
os.makedirs(multi_plot_directory)
best_plot_directory = plot_directory + 'best'
if not os.path.exists(best_plot_directory):
os.makedirs(best_plot_directory)
withBackground = 0
test_len = len(true_trajectory)
count = 0
if_pick_scene = False
if_ploy_multimodality = True
pick_scene = [0]
for i in range(test_len):
st_ed = get_st_ed(batch_pednum[i])
len_st_ed = len(st_ed)
for j in range(len_st_ed):
print(count)
name = 'scene' + str(count)
st = st_ed[j][0]
ed = st_ed[j][1]
batch_true_trajectory = true_trajectory[i][:, st:ed, :]
batch_predicted_trajectory = predicted_trajectory[i][:, :, st:ed, :]
batch_best_pred_trajectory = best_pred_trajectory[i][:, st:ed, :]
if if_pick_scene:
if count in pick_scene:
if if_ploy_multimodality:
plot_trajectories_multimodality(batch_true_trajectory, batch_predicted_trajectory, 0, name, multi_plot_directory,
H_inv, background_image) # This is the core
else:
plot_trajectories(batch_true_trajectory, batch_best_pred_trajectory, 0, name, best_plot_directory,
H_inv, background_image) # This is the core
else:
if if_ploy_multimodality:
plot_trajectories_multimodality(batch_true_trajectory, batch_predicted_trajectory, 0, name,
multi_plot_directory,
H_inv, background_image) # This is the core
else:
plot_trajectories(batch_true_trajectory, batch_best_pred_trajectory, 0, name, best_plot_directory,
H_inv, background_image) # This is the core
# if count in pick_scene:
# plot_trajectories(batch_true_trajectory, batch_predicted_trajectory, 0, name, plot_directory,
# H_inv, background_image) # This is the core
count += 1