-
Notifications
You must be signed in to change notification settings - Fork 137
/
estimate_smpl.py
591 lines (519 loc) · 21.8 KB
/
estimate_smpl.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
import os
import os.path as osp
import shutil
import warnings
from argparse import ArgumentParser
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
inference_video_based_model,
init_model,
)
from mmhuman3d.core.visualization.visualize_smpl import visualize_smpl_hmr
from mmhuman3d.data.data_structures.human_data import HumanData
from mmhuman3d.utils.demo_utils import (
extract_feature_sequence,
get_speed_up_interval,
prepare_frames,
process_mmdet_results,
process_mmtracking_results,
smooth_process,
speed_up_interpolate,
speed_up_process,
)
from mmhuman3d.utils.ffmpeg_utils import array_to_images
from mmhuman3d.utils.transforms import rotmat_to_aa
try:
from mmdet.apis import inference_detector, init_detector
has_mmdet = True
except (ImportError, ModuleNotFoundError):
has_mmdet = False
try:
from mmtrack.apis import inference_mot
from mmtrack.apis import init_model as init_tracking_model
has_mmtrack = True
except (ImportError, ModuleNotFoundError):
has_mmtrack = False
def get_tracking_result(args, frames_iter, mesh_model, extractor):
tracking_model = init_tracking_model(
args.tracking_config, None, device=args.device.lower())
max_track_id = 0
max_instance = 0
result_list = []
frame_id_list = []
for i, frame in enumerate(mmcv.track_iter_progress(frames_iter)):
mmtracking_results = inference_mot(tracking_model, frame, frame_id=i)
# keep the person class bounding boxes.
result, max_track_id, instance_num = \
process_mmtracking_results(
mmtracking_results,
max_track_id=max_track_id,
bbox_thr=args.bbox_thr)
# extract features from the input video or image sequences
if mesh_model.cfg.model.type == 'VideoBodyModelEstimator' \
and extractor is not None:
result = feature_extract(
extractor, frame, result, args.bbox_thr, format='xyxy')
# drop the frame with no detected results
if result == []:
continue
# update max_instance
if instance_num > max_instance:
max_instance = instance_num
# vis bboxes
if args.draw_bbox:
bboxes = [res['bbox'] for res in result]
bboxes = np.vstack(bboxes)
mmcv.imshow_bboxes(
frame, bboxes, top_k=-1, thickness=2, show=False)
result_list.append(result)
frame_id_list.append(i)
return max_track_id, max_instance, frame_id_list, result_list
def get_detection_result(args, frames_iter, mesh_model, extractor):
person_det_model = init_detector(
args.det_config, args.det_checkpoint, device=args.device.lower())
frame_id_list = []
result_list = []
for i, frame in enumerate(mmcv.track_iter_progress(frames_iter)):
mmdet_results = inference_detector(person_det_model, frame)
# keep the person class bounding boxes.
results = process_mmdet_results(
mmdet_results, cat_id=args.det_cat_id, bbox_thr=args.bbox_thr)
# extract features from the input video or image sequences
if mesh_model.cfg.model.type == 'VideoBodyModelEstimator' \
and extractor is not None:
results = feature_extract(
extractor, frame, results, args.bbox_thr, format='xyxy')
# drop the frame with no detected results
if results == []:
continue
# vis bboxes
if args.draw_bbox:
bboxes = [res['bbox'] for res in results]
bboxes = np.vstack(bboxes)
mmcv.imshow_bboxes(
frame, bboxes, top_k=-1, thickness=2, show=False)
frame_id_list.append(i)
result_list.append(results)
return frame_id_list, result_list
def single_person_with_mmdet(args, frames_iter):
"""Estimate smpl parameters from single-person
images with mmdetection
Args:
args (object): object of argparse.Namespace.
frames_iter (np.ndarray,): prepared frames
"""
mesh_model, extractor = init_model(
args.mesh_reg_config,
args.mesh_reg_checkpoint,
device=args.device.lower())
pred_cams, verts, smpl_poses, smpl_betas, bboxes_xyxy = \
[], [], [], [], []
frame_id_list, result_list = \
get_detection_result(args, frames_iter, mesh_model, extractor)
frame_num = len(frame_id_list)
# speed up
if args.speed_up_type:
speed_up_interval = get_speed_up_interval(args.speed_up_type)
speed_up_frames = (frame_num -
1) // speed_up_interval * speed_up_interval
for i, result in enumerate(mmcv.track_iter_progress(result_list)):
frame_id = frame_id_list[i]
if mesh_model.cfg.model.type == 'VideoBodyModelEstimator':
if args.speed_up_type:
warnings.warn(
'Video based models do not support speed up. '
'By default we will inference with original speed.',
UserWarning)
feature_results_seq = extract_feature_sequence(
result_list, frame_idx=i, causal=True, seq_len=16, step=1)
mesh_results = inference_video_based_model(
mesh_model,
extracted_results=feature_results_seq,
with_track_id=False)
elif mesh_model.cfg.model.type == 'ImageBodyModelEstimator':
if args.speed_up_type and i % speed_up_interval != 0\
and i <= speed_up_frames:
mesh_results = [{
'bbox': np.zeros((5)),
'camera': np.zeros((3)),
'smpl_pose': np.zeros((24, 3, 3)),
'smpl_beta': np.zeros((10)),
'vertices': np.zeros((6890, 3)),
'keypoints_3d': np.zeros((17, 3)),
}]
else:
mesh_results = inference_image_based_model(
mesh_model,
frames_iter[frame_id],
result,
bbox_thr=args.bbox_thr,
format='xyxy')
else:
raise (f'{mesh_model.cfg.model.type} is not supported yet')
smpl_betas.append(mesh_results[0]['smpl_beta'])
smpl_pose = mesh_results[0]['smpl_pose']
smpl_poses.append(smpl_pose)
pred_cams.append(mesh_results[0]['camera'])
verts.append(mesh_results[0]['vertices'])
bboxes_xyxy.append(mesh_results[0]['bbox'])
smpl_poses = np.array(smpl_poses)
smpl_betas = np.array(smpl_betas)
pred_cams = np.array(pred_cams)
verts = np.array(verts)
bboxes_xyxy = np.array(bboxes_xyxy)
# release GPU memory
del mesh_model
del extractor
torch.cuda.empty_cache()
# speed up
if args.speed_up_type:
smpl_poses = speed_up_process(
torch.tensor(smpl_poses).to(args.device.lower()),
args.speed_up_type)
selected_frames = np.arange(0, len(frames_iter), speed_up_interval)
smpl_poses, smpl_betas, pred_cams, bboxes_xyxy = speed_up_interpolate(
selected_frames, speed_up_frames, smpl_poses, smpl_betas,
pred_cams, bboxes_xyxy)
# smooth
if args.smooth_type is not None:
smpl_poses = smooth_process(
smpl_poses.reshape(frame_num, 24, 9),
smooth_type=args.smooth_type).reshape(frame_num, 24, 3, 3)
verts = smooth_process(verts, smooth_type=args.smooth_type)
pred_cams = smooth_process(
pred_cams[:, np.newaxis],
smooth_type=args.smooth_type).reshape(frame_num, 3)
if smpl_poses.shape[1:] == (24, 3, 3):
smpl_poses = rotmat_to_aa(smpl_poses)
elif smpl_poses.shape[1:] == (24, 3):
smpl_poses = smpl_pose
else:
raise (f'Wrong shape of `smpl_pose`: {smpl_pose.shape}')
if args.output is not None:
body_pose_, global_orient_, smpl_betas_, verts_, pred_cams_, \
bboxes_xyxy_, image_path_, person_id_, frame_id_ = \
[], [], [], [], [], [], [], [], []
human_data = HumanData()
frames_folder = osp.join(args.output, 'images')
os.makedirs(frames_folder, exist_ok=True)
array_to_images(
np.array(frames_iter)[frame_id_list], output_folder=frames_folder)
for i, img_i in enumerate(sorted(os.listdir(frames_folder))):
body_pose_.append(smpl_poses[i][1:])
global_orient_.append(smpl_poses[i][:1])
smpl_betas_.append(smpl_betas[i])
verts_.append(verts[i])
pred_cams_.append(pred_cams[i])
bboxes_xyxy_.append(bboxes_xyxy[i])
image_path_.append(os.path.join('images', img_i))
person_id_.append(0)
frame_id_.append(frame_id_list[i])
smpl = {}
smpl['body_pose'] = np.array(body_pose_).reshape((-1, 23, 3))
smpl['global_orient'] = np.array(global_orient_).reshape((-1, 3))
smpl['betas'] = np.array(smpl_betas_).reshape((-1, 10))
human_data['smpl'] = smpl
human_data['verts'] = verts_
human_data['pred_cams'] = pred_cams_
human_data['bboxes_xyxy'] = bboxes_xyxy_
human_data['image_path'] = image_path_
human_data['person_id'] = person_id_
human_data['frame_id'] = frame_id_
human_data.dump(osp.join(args.output, 'inference_result.npz'))
if args.show_path is not None:
if args.output is not None:
frames_folder = os.path.join(args.output, 'images')
else:
frames_folder = osp.join(Path(args.show_path).parent, 'images')
os.makedirs(frames_folder, exist_ok=True)
array_to_images(
np.array(frames_iter)[frame_id_list],
output_folder=frames_folder)
body_model_config = dict(model_path=args.body_model_dir, type='smpl')
visualize_smpl_hmr(
poses=smpl_poses.reshape(-1, 24 * 3),
betas=smpl_betas,
cam_transl=pred_cams,
bbox=bboxes_xyxy,
output_path=args.show_path,
render_choice=args.render_choice,
resolution=frames_iter[0].shape[:2],
origin_frames=frames_folder,
body_model_config=body_model_config,
overwrite=True,
palette=args.palette,
read_frames_batch=True)
if args.output is None:
shutil.rmtree(frames_folder)
def multi_person_with_mmtracking(args, frames_iter):
"""Estimate smpl parameters from multi-person
images with mmtracking
Args:
args (object): object of argparse.Namespace.
frames_iter (np.ndarray,): prepared frames
"""
mesh_model, extractor = \
init_model(args.mesh_reg_config, args.mesh_reg_checkpoint,
device=args.device.lower())
max_track_id, max_instance, frame_id_list, result_list = \
get_tracking_result(args, frames_iter, mesh_model, extractor)
frame_num = len(frame_id_list)
verts = np.zeros([frame_num, max_track_id + 1, 6890, 3])
pred_cams = np.zeros([frame_num, max_track_id + 1, 3])
bboxes_xyxy = np.zeros([frame_num, max_track_id + 1, 5])
smpl_poses = np.zeros([frame_num, max_track_id + 1, 24, 3, 3])
smpl_betas = np.zeros([frame_num, max_track_id + 1, 10])
# speed up
if args.speed_up_type:
speed_up_interval = get_speed_up_interval(args.speed_up_type)
speed_up_frames = (frame_num -
1) // speed_up_interval * speed_up_interval
track_ids_lists = []
for i, result in enumerate(mmcv.track_iter_progress(result_list)):
frame_id = frame_id_list[i]
if mesh_model.cfg.model.type == 'VideoBodyModelEstimator':
if args.speed_up_type:
warnings.warn(
'Video based models do not support speed up. '
'By default we will inference with original speed.',
UserWarning)
feature_results_seq = extract_feature_sequence(
result_list, frame_idx=i, causal=True, seq_len=16, step=1)
mesh_results = inference_video_based_model(
mesh_model,
extracted_results=feature_results_seq,
with_track_id=True)
elif mesh_model.cfg.model.type == 'ImageBodyModelEstimator':
if args.speed_up_type and i % speed_up_interval != 0\
and i <= speed_up_frames:
mesh_results = []
for idx in range(len(result)):
mesh_result = result[idx].copy()
mesh_result['bbox'] = np.zeros((5))
mesh_result['camera'] = np.zeros((3))
mesh_result['smpl_pose'] = np.zeros((24, 3, 3))
mesh_result['smpl_beta'] = np.zeros((10))
mesh_result['vertices'] = np.zeros((6890, 3))
mesh_result['keypoints_3d'] = np.zeros((17, 3))
mesh_results.append(mesh_result)
else:
mesh_results = inference_image_based_model(
mesh_model,
frames_iter[frame_id],
result,
bbox_thr=args.bbox_thr,
format='xyxy')
else:
raise (f'{mesh_model.cfg.model.type} is not supported yet')
track_ids = []
for mesh_result in mesh_results:
instance_id = mesh_result['track_id']
bboxes_xyxy[i, instance_id] = mesh_result['bbox']
pred_cams[i, instance_id] = mesh_result['camera']
verts[i, instance_id] = mesh_result['vertices']
smpl_betas[i, instance_id] = mesh_result['smpl_beta']
smpl_poses[i, instance_id] = mesh_result['smpl_pose']
track_ids.append(instance_id)
track_ids_lists.append(track_ids)
# release GPU memory
del mesh_model
del extractor
torch.cuda.empty_cache()
# speed up
if args.speed_up_type:
smpl_poses = speed_up_process(
torch.tensor(smpl_poses).to(args.device.lower()),
args.speed_up_type)
selected_frames = np.arange(0, len(frames_iter), speed_up_interval)
smpl_poses, smpl_betas, pred_cams, bboxes_xyxy = speed_up_interpolate(
selected_frames, speed_up_frames, smpl_poses, smpl_betas,
pred_cams, bboxes_xyxy)
# smooth
if args.smooth_type is not None:
smpl_poses = smooth_process(
smpl_poses.reshape(frame_num, -1, 24, 9),
smooth_type=args.smooth_type).reshape(frame_num, -1, 24, 3, 3)
verts = smooth_process(verts, smooth_type=args.smooth_type)
pred_cams = smooth_process(
pred_cams[:, np.newaxis],
smooth_type=args.smooth_type).reshape(frame_num, -1, 3)
if smpl_poses.shape[2:] == (24, 3, 3):
smpl_poses = rotmat_to_aa(smpl_poses)
elif smpl_poses.shape[2:] == (24, 3):
smpl_poses = smpl_poses
else:
raise (f'Wrong shape of `smpl_pose`: {smpl_poses.shape}')
if args.output is not None:
body_pose_, global_orient_, smpl_betas_, verts_, pred_cams_, \
bboxes_xyxy_, image_path_, frame_id_, person_id_ = \
[], [], [], [], [], [], [], [], []
human_data = HumanData()
frames_folder = osp.join(args.output, 'images')
os.makedirs(frames_folder, exist_ok=True)
array_to_images(
np.array(frames_iter)[frame_id_list], output_folder=frames_folder)
for i, img_i in enumerate(sorted(os.listdir(frames_folder))):
for person_i in track_ids_lists[i]:
body_pose_.append(smpl_poses[i][person_i][1:])
global_orient_.append(smpl_poses[i][person_i][:1])
smpl_betas_.append(smpl_betas[i][person_i])
verts_.append(verts[i][person_i])
pred_cams_.append(pred_cams[i][person_i])
bboxes_xyxy_.append(bboxes_xyxy[i][person_i])
image_path_.append(os.path.join('images', img_i))
person_id_.append(person_i)
frame_id_.append(frame_id_list[i])
smpl = {}
smpl['body_pose'] = np.array(body_pose_).reshape((-1, 23, 3))
smpl['global_orient'] = np.array(global_orient_).reshape((-1, 3))
smpl['betas'] = np.array(smpl_betas_).reshape((-1, 10))
human_data['smpl'] = smpl
human_data['verts'] = verts_
human_data['pred_cams'] = pred_cams_
human_data['bboxes_xyxy'] = bboxes_xyxy_
human_data['image_path'] = image_path_
human_data['person_id'] = person_id_
human_data['frame_id'] = frame_id_
human_data.dump(osp.join(args.output, 'inference_result.npz'))
# To compress vertices array
compressed_verts = np.zeros([frame_num, max_instance, 6890, 3])
compressed_cams = np.zeros([frame_num, max_instance, 3])
compressed_bboxs = np.zeros([frame_num, max_instance, 5])
compressed_poses = np.zeros([frame_num, max_instance, 24, 3])
compressed_betas = np.zeros([frame_num, max_instance, 10])
for i, track_ids_list in enumerate(track_ids_lists):
instance_num = len(track_ids_list)
compressed_verts[i, :instance_num] = verts[i, track_ids_list]
compressed_cams[i, :instance_num] = pred_cams[i, track_ids_list]
compressed_bboxs[i, :instance_num] = bboxes_xyxy[i, track_ids_list]
compressed_poses[i, :instance_num] = smpl_poses[i, track_ids_list]
compressed_betas[i, :instance_num] = smpl_betas[i, track_ids_list]
assert len(frame_id_list) > 0
if args.show_path is not None:
if args.output is not None:
frames_folder = os.path.join(args.output, 'images')
else:
frames_folder = osp.join(Path(args.show_path).parent, 'images')
os.makedirs(frames_folder, exist_ok=True)
array_to_images(
np.array(frames_iter)[frame_id_list],
output_folder=frames_folder)
body_model_config = dict(model_path=args.body_model_dir, type='smpl')
visualize_smpl_hmr(
poses=compressed_poses.reshape(-1, max_instance, 24 * 3),
betas=compressed_betas,
cam_transl=compressed_cams,
bbox=compressed_bboxs,
output_path=args.show_path,
render_choice=args.render_choice,
resolution=frames_iter[0].shape[:2],
origin_frames=frames_folder,
body_model_config=body_model_config,
overwrite=True,
palette=args.palette,
read_frames_batch=True)
def main(args):
# prepare input
frames_iter = prepare_frames(args.input_path)
if args.single_person_demo:
single_person_with_mmdet(args, frames_iter)
elif args.multi_person_demo:
multi_person_with_mmtracking(args, frames_iter)
else:
raise ValueError(
'Only supports single_person_demo or multi_person_demo')
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument(
'mesh_reg_config',
type=str,
default=None,
help='Config file for mesh regression')
parser.add_argument(
'mesh_reg_checkpoint',
type=str,
default=None,
help='Checkpoint file for mesh regression')
parser.add_argument(
'--single_person_demo',
action='store_true',
help='Single person demo with MMDetection')
parser.add_argument('--det_config', help='Config file for detection')
parser.add_argument(
'--det_checkpoint', help='Checkpoint file for detection')
parser.add_argument(
'--det_cat_id',
type=int,
default=1,
help='Category id for bounding box detection model')
parser.add_argument(
'--multi_person_demo',
action='store_true',
help='Multi person demo with MMTracking')
parser.add_argument('--tracking_config', help='Config file for tracking')
parser.add_argument(
'--body_model_dir',
type=str,
default='data/body_models/',
help='Body models file path')
parser.add_argument(
'--input_path', type=str, default=None, help='Input path')
parser.add_argument(
'--output',
type=str,
default=None,
help='directory to save output result file')
parser.add_argument(
'--show_path',
type=str,
default=None,
help='directory to save rendered images or video')
parser.add_argument(
'--render_choice',
type=str,
default='hq',
help='Render choice parameters')
parser.add_argument(
'--palette', type=str, default='segmentation', help='Color theme')
parser.add_argument(
'--bbox_thr',
type=float,
default=0.99,
help='Bounding box score threshold')
parser.add_argument(
'--draw_bbox',
action='store_true',
help='Draw a bbox for each detected instance')
parser.add_argument(
'--smooth_type',
type=str,
default=None,
help='Smooth the data through the specified type.'
'Select in [oneeuro,gaus1d,savgol].')
parser.add_argument(
'--speed_up_type',
type=str,
default=None,
help='Speed up data processing through the specified type.'
'Select in [deciwatch].')
parser.add_argument(
'--focal_length', type=float, default=5000., help='Focal lenght')
parser.add_argument(
'--device',
choices=['cpu', 'cuda'],
default='cuda',
help='device used for testing')
args = parser.parse_args()
if args.single_person_demo:
assert has_mmdet, 'Please install mmdet to run the demo.'
assert args.det_config is not None
assert args.det_checkpoint is not None
if args.multi_person_demo:
assert has_mmtrack, 'Please install mmtrack to run the demo.'
assert args.tracking_config is not None
main(args)