forked from google/next-prediction
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstep4_generate_traj.py
executable file
·335 lines (261 loc) · 12.1 KB
/
step4_generate_traj.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
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Generate trajectory files and scene, person box, other box, activity files."""
# pylint: disable=g-importing-member
# pylint: disable=g-bad-import-order
import argparse
import os
import operator
import numpy as np
import cPickle as pickle
from tqdm import tqdm
from glob import glob
from utils import activity2id
from utils import actev_scene2imgsize
from utils import get_scene
parser = argparse.ArgumentParser()
parser.add_argument("npzpath")
parser.add_argument("split_path")
parser.add_argument("out_path")
parser.add_argument("--drop_frame", default=1, type=int,
help="drop frame to match different fps, assuming "
"the virat fps is 30fps, so to get 2.5fps, "
"need to drop 12 frames every time")
parser.add_argument("--scene_feat_path",
help="the scene segmentation output path,"
"under it should be frame_name.npy")
# the following are the output paths
parser.add_argument("--scene_map_path",
help="frameidx mapping to actual scene feature file output")
parser.add_argument("--person_box_path",
help="Person box output")
parser.add_argument("--other_box_path",
help="Other object box output")
parser.add_argument("--activity_path",
help="activity annotation output")
# for ETH/UCY you need to write your own video size mapping
# In the PeekingFuture paper we resize ETH/UCY to 720x576 to extract features
scene2imgsize = actev_scene2imgsize
actid2name = {activity2id[n]: n for n in activity2id}
def resize_xy(xy, vname, resize_w, resize_h):
"""Resize the xy coordinates."""
x_, y_ = xy
w, h = scene2imgsize[get_scene(vname)]
diff_w = resize_w / float(w)
diff_h = resize_h / float(h)
x_ *= diff_w
y_ *= diff_h
# normalize coordinates?
return [x_, y_]
def resize_box(box, vname, resize_w, resize_h):
"""Resize the box coordintates."""
x1, y1, x2, y2 = [float(o) for o in box]
w, h = scene2imgsize[get_scene(vname)]
diff_w = resize_w / float(w)
diff_h = resize_h / float(h)
x1 *= diff_w
x2 *= diff_w
y1 *= diff_h
y2 *= diff_h
return [x1, y1, x2, y2]
# frame_lst is [(videoname,frameidx)], assume sorted by the frameidx
def get_nearest(frame_lst_, frame_idx):
"""Since we don't run scene seg on every frame, we want to find the nearest one."""
frame_idxs = np.array([i_ for _, i_ in frame_lst_])
cloests_idx = (np.abs(frame_idxs - frame_idx)).argmin()
vname, closest_frame_idx = frame_lst_[cloests_idx]
return vname, closest_frame_idx, cloests_idx
def get_act_list(act_data, frameidx, bgid):
"""Given a frameidx, get this person' activities."""
# act_data is a list of sorted (start,end,actclassid)
# return current act list,
current_act_list = [(actid, e - frameidx) for s, e, actid in act_data
if (frameidx >= s) and (frameidx <= e)]
current_act_list.sort(key=operator.itemgetter(1)) # dist to current act's end
current_actid_list_ = [actid for actid, _ in current_act_list]
current_dist_list_ = [dist for _, dist in current_act_list]
if not current_act_list:
current_actid_list_, current_dist_list_ = [bgid], [-1]
future_act_list = [(actid, s - frameidx) for s, e, actid in act_data
if frameidx < s]
future_act_list.sort(key=operator.itemgetter(1))
if not future_act_list:
return (current_actid_list_, current_dist_list_, [bgid], [-1])
# only the nearest future activity?
# smallest_dist = future_act_list[0][1]
# future_act_list = [(actid,dist) for actid, dist in future_act_list
# if dist == smallest_dist]
future_actid_list_ = [actid for actid, _ in future_act_list]
future_dist_list_ = [dist for _, dist in future_act_list]
return (current_actid_list_, current_dist_list_,
future_actid_list_, future_dist_list_)
def check_traj(newdata_, vname):
"""Check and filter data."""
checkdata = np.array(newdata_, dtype="float")
frames_ = np.unique(checkdata[:, 0]).tolist()
checked_data_ = []
for frame_ in frames_:
# all personid in this frame
this_frame_data = checkdata[frame_ == checkdata[:, 0], :] # [K,4]
ped_ids = this_frame_data[:, 1]
unique_ped_ids, unique_idxs = np.unique(ped_ids, return_index=True)
if len(ped_ids) != len(unique_ped_ids):
tqdm.write("\twarning, %s frame %s has duplicate person annotation person"
" ids: %s/%s, removed the duplicate ones"
% (vname, frame_, len(unique_ped_ids), len(ped_ids)))
this_frame_data = this_frame_data[unique_idxs]
for f_, p_, x_, y_ in this_frame_data:
checked_data_.append((f_, p_, x_, y_))
checked_data_.sort(key=operator.itemgetter(0))
return checked_data_
if __name__ == "__main__":
args = parser.parse_args()
# Hard coded for ActEV experiment.
# :P
args.resize = True
args.resize_h = 1080
args.resize_w = 1920
filelst = {
"train": [os.path.splitext(os.path.basename(line.strip()))[0]
for line in open(os.path.join(args.split_path,
"train.lst"), "r").readlines()],
"val": [os.path.splitext(os.path.basename(line.strip()))[0]
for line in open(os.path.join(args.split_path,
"val.lst"), "r").readlines()],
"test": [os.path.splitext(os.path.basename(line.strip()))[0]
for line in open(os.path.join(args.split_path,
"test.lst"), "r").readlines()],
}
for split in tqdm(filelst, ascii=True):
out_path = os.path.join(args.out_path, split)
if not os.path.exists(out_path):
os.makedirs(out_path)
if not os.path.exists(os.path.join(args.person_box_path, split)):
os.makedirs(os.path.join(args.person_box_path, split))
if not os.path.exists(os.path.join(args.other_box_path, split)):
os.makedirs(os.path.join(args.other_box_path, split))
if not os.path.exists(os.path.join(args.activity_path, split)):
os.makedirs(os.path.join(args.activity_path, split))
scene_map_path = os.path.join(args.scene_map_path, split)
if not os.path.exists(scene_map_path):
os.makedirs(scene_map_path)
for videoname in tqdm(filelst[split]):
npzfile = os.path.join(args.npzpath, "%s.npz" % videoname)
data = np.load(npzfile, allow_pickle=True)
# each frame's all boxes, for getting other boxes
frameidx2boxes = data["frameidx2boxes"]
# personId -> all related activity with timespan, sorted by timespan start
# (start, end, act_classid)
personid2acts = data["personid2acts"]
# load all the frames for this video first
frame_lst = glob(os.path.join(args.scene_feat_path,
"%s_F_*.npy"%videoname))
assert frame_lst
frame_lst = [(os.path.basename(frame),
int(os.path.basename(frame).split(".")[0].split("_F_")[-1]))
for frame in frame_lst]
frame_lst.sort(key=operator.itemgetter(1))
newdata = [] # (frame_id, person_id,x,y) # all float
# key is frameidx, person_id
scene_data = {} # frame ->
person_box_data = {} # key -> person boxes
other_box_data = {} # key -> other box + boxclassids
activity_data = {} # key ->
for person_id in data["person_tracks"]:
for d in data["person_tracks"][person_id]:
# resize or normalize
d["point"] = resize_xy(d["point"], videoname,
args.resize_w, args.resize_h)
newdata.append((
d["f"],
float(person_id),
d["point"][0],
d["point"][1]
))
person_key = "%d_%d" % (d["f"], person_id)
# 1. get person boxes
person_box = resize_box(d["box"], videoname,
args.resize_w, args.resize_h)
person_box_data[person_key] = person_box
# done 1
# 2. get other boxes
all_boxes = frameidx2boxes[d["f"]]
# remove itself in the object boxes
this_person_idx = all_boxes["trackids"].index(person_id)
all_other_boxes = [all_boxes["boxes"][i]
for i in xrange(len(all_boxes["boxes"]))
if i != this_person_idx]
all_other_boxclassids = [all_boxes["classids"][i]
for i in xrange(len(all_boxes["classids"]))
if i != this_person_idx]
# resize the box if needed
for i in xrange(len(all_other_boxes)):
all_other_boxes[i] = resize_box(all_other_boxes[i], videoname,
args.resize_w, args.resize_h)
other_box_data[person_key] = (all_other_boxes, all_other_boxclassids)
# done 2
# 3. get activity annotations
if person_id in personid2acts:
this_person_acts = personid2acts[person_id]
# get the current activitylist, future activity list
# and timestep to future activities
current_actid_list, current_dist_list, future_actid_list, \
future_dist_list = get_act_list(this_person_acts,
d["f"], activity2id["BG"])
else:
# so some person has no activity?
current_actid_list, current_dist_list, future_actid_list, \
future_dist_list = ([activity2id["BG"]], [-1], [activity2id["BG"]],
[-1])
activity_data[person_key] = (current_actid_list,
current_dist_list,
future_actid_list,
future_dist_list)
for lst in activity_data[person_key]:
assert lst
# done 3
# 4. get scene segmentation features
# find the nearest scene out file to this frame
this_frame_idx = d["f"]
target_file, target_frame_idx, idx = get_nearest(frame_lst,
this_frame_idx)
# print("this frame %s, found target_file %s and target frame idx %s,"
# "since the frame list is like %s"
# % (this_frame_idx, target_file, target_frame_idx,
# frame_lst[idx-2:idx+2]))
scene_data[d["f"]] = target_file
# done 4
newdata.sort(key=operator.itemgetter(0))
if args.drop_frame > 1:
frames = np.unique([one[0] for one in newdata]).tolist()
# uniformly drop frames
frames_to_keep = frames[::args.drop_frame]
drop_newdata = [one for one in newdata if one[0] in frames_to_keep]
newdata = drop_newdata
# do a data check, each frame"s person id should be unique
# check and filter
checked_data = check_traj(newdata, videoname)
if len(checked_data) != len(newdata):
tqdm.write("checked data vs original data:%s/%s" % (len(checked_data),
len(newdata)))
newdata = checked_data
desfile = os.path.join(args.out_path, split, "%s.txt" % videoname)
delim = "\t"
with open(desfile, "w") as f:
for i, p, x, y in newdata:
f.writelines("%d%s%.1f%s%.6f%s%.6f\n" % (i, delim, p, delim, x,
delim, y))
with open(os.path.join(args.person_box_path,
split, "%s.p" % videoname), "w") as f:
pickle.dump(person_box_data, f)
with open(os.path.join(args.other_box_path,
split, "%s.p" % videoname), "w") as f:
pickle.dump(other_box_data, f)
with open(os.path.join(args.activity_path,
split, "%s.p" % videoname), "w") as f:
pickle.dump(activity_data, f)
with open(os.path.join(args.scene_map_path,
split, "%s.p" % videoname), "w") as f:
pickle.dump(scene_data, f)