forked from IntelligentSensingAndRehabilitation/PosePipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.py
1976 lines (1521 loc) · 67.5 KB
/
pipeline.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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import cv2
import tempfile
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import shutil
import datajoint as dj
from .utils.keypoint_matching import match_keypoints_to_bbox
from .env import add_path
if "custom" not in dj.config:
dj.config["custom"] = {}
db_prefix = dj.config["custom"].get("database.prefix", "")
schema = dj.schema(db_prefix + "pose_pipeline")
@schema
class Video(dj.Manual):
definition = """
# Table containing raw videos, grouped by project and filename, with their start time
video_project : varchar(50)
filename : varchar(100)
---
video : attach@localattach # datajoint managed video file
start_time : timestamp(3) # time of beginning of video, as accurately as known
import_time = CURRENT_TIMESTAMP : timestamp
"""
@staticmethod
def make_entry(filepath, session_id=None):
from datetime import datetime
import os
_, fn = os.path.split(filepath)
date = datetime.strptime(fn[:16], "%Y%m%d-%H%M%SZ")
d = {"filename": fn, "video": filepath, "start_time": date}
if session_id is not None:
d.update({"session_id": session_id})
return d
@staticmethod
def get_robust_reader(key, return_cap=True):
import subprocess
import tempfile
# fetch video and place in temp directory
video = (Video & key).fetch1("video")
fd, outfile = tempfile.mkstemp(suffix=".mp4")
os.close(fd)
shutil.move(video, outfile)
video = outfile
cap = cv2.VideoCapture(video)
# check all the frames are readable
expected_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
completed = True
def compress(video):
fd, outfile = tempfile.mkstemp(suffix=".mp4")
print(f"Unable to read all the fails. Transcoding {video} to {outfile}")
subprocess.run(["ffmpeg", "-y", "-i", video, "-c:v", "libx264", "-b:v", "1M", outfile])
os.close(fd)
return outfile
for i in range(expected_frames):
ret, frame = cap.read()
if not ret or frame is None:
cap.release()
video = compress(video)
cap = cv2.VideoCapture(video)
break
if return_cap:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
return cap
else:
cap.release()
return video
@schema
class VideoInfo(dj.Computed):
definition = """
# Video info including timestamps, delta times, num frames, height and width
-> Video
---
timestamps : longblob
delta_time : longblob
fps : float
height : int
width : int
num_frames : int
"""
def make(self, key, override=False):
key = key.copy()
video, start_time = (Video & key).fetch1("video", "start_time")
cap = cv2.VideoCapture(video)
key["fps"] = fps = cap.get(cv2.CAP_PROP_FPS)
if (key["fps"] < 1):
cap.release()
raise Exception("FPS is less than 1")
key["num_frames"] = frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
key["width"] = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
key["height"] = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
key["timestamps"] = [start_time + timedelta(0, i / fps) for i in range(frames)]
key["delta_time"] = [timedelta(0, i / fps).total_seconds() for i in range(frames)]
cap.release()
os.remove(video)
self.insert1(key, allow_direct_insert=override)
def fetch_timestamps(self):
assert len(self) == 1, "Restrict to single entity"
timestamps = self.fetch1("timestamps")
timestamps = np.array([(t - timestamps[0]).total_seconds() for t in timestamps])
return timestamps
@schema
class BottomUpMethodLookup(dj.Lookup):
definition = """
bottom_up_method_name : varchar(50)
"""
contents = [
{"bottom_up_method_name": "OpenPose"},
{"bottom_up_method_name": "OpenPose_BODY25B"},
{"bottom_up_method_name": "OpenPose_HR"},
{"bottom_up_method_name": "OpenPose_LR"},
{"bottom_up_method_name": "MMPose"},
# this uses the COCO25 keypoints but in the same order as OpenPose
{"bottom_up_method_name": "Bridging_OpenPose"},
]
@schema
class BottomUpMethod(dj.Manual):
definition = """
-> Video
-> BottomUpMethodLookup
"""
@schema
class BottomUpPeople(dj.Computed):
definition = """
-> BottomUpMethod
---
keypoints : longblob
timestamp=CURRENT_TIMESTAMP : timestamp # automatic timestamp
"""
def make(self, key):
if key["bottom_up_method_name"] == "OpenPose":
from pose_pipeline.wrappers.openpose import openpose_process_key
params = {"model_pose": "BODY_25", "scale_number": 4, "scale_gap": 0.25}
key = openpose_process_key(key, **params)
# to standardize with MMPose, drop other info
key["keypoints"] = [k["keypoints"] for k in key["keypoints"]]
elif key["bottom_up_method_name"] == "OpenPose_BODY25B":
from pose_pipeline.wrappers.openpose import openpose_process_key
params = {"model_pose": "BODY_25B", "scale_number": 4, "scale_gap": 0.25}
with add_path(os.path.join(os.environ["OPENPOSE_PATH"], "build/python")):
key = openpose_process_key(key, **params)
# to standardize with MMPose, drop other info
key["keypoints"] = [k["keypoints"] for k in key["keypoints"]]
elif key["bottom_up_method_name"] == "OpenPose_HR":
from pose_pipeline.wrappers.openpose import openpose_process_key
# adopted from https://github.com/stanfordnmbl/opencap-core/blob/0f633d1d6f1e4ddc40ffe49306a1584af9c3af32/docker/openpose/loop.py#L43
width, height = (VideoInfo & key).fetch1("width", "height")
if width > height:
params = {"model_pose": "BODY_25", "scale_number": 4, "scale_gap": 0.25, "net_resolution": "1008x-1"}
else:
params = {"model_pose": "BODY_25", "scale_number": 4, "scale_gap": 0.25, "net_resolution": "-1x1008"}
with add_path(os.path.join(os.environ["OPENPOSE_PATH"], "build/python")):
key = openpose_process_key(key, **params)
# to standardize with MMPose, drop other info
key["keypoints"] = [k["keypoints"] for k in key["keypoints"]]
elif key["bottom_up_method_name"] == "OpenPose_LR":
from pose_pipeline.wrappers.openpose import openpose_process_key
params = {"model_pose": "BODY_25"}
with add_path(os.path.join(os.environ["OPENPOSE_PATH"], "build/python")):
key = openpose_process_key(key, **params)
# to standardize with MMPose, drop other info
key["keypoints"] = [k["keypoints"] for k in key["keypoints"]]
elif key["bottom_up_method_name"] == "MMPose":
from .wrappers.mmpose import mmpose_bottom_up
key["keypoints"] = mmpose_bottom_up(key)
elif key["bottom_up_method_name"] == "Bridging_OpenPose":
from .wrappers.bridging import filter_skeleton, normalized_joint_name_dictionary, noise_to_conf
assert BottomUpBridging & key, f"Bridging not computed: {key}"
openpose_reorder_idx = [normalized_joint_name_dictionary['coco_25'].index(j)
for j in OpenPosePerson.joint_names()]
keypoints2d, keypoint_noise = (BottomUpBridging & key).fetch1('keypoints2d', 'keypoint_noise')
final_keypoints = []
for kp, noise in zip(keypoints2d, keypoint_noise):
if len(kp) == 0:
kp = np.concatenate([kp, noise[..., None]], axis=-1)
final_keypoints.append(kp)
continue
# concatenate noise to final dimension
noise = noise_to_conf(noise).numpy()
kp = np.concatenate([kp, noise[:, :, None]], axis=-1)
# filter and reorder to match OpenPose order, for compatibility downstream
kp = filter_skeleton(kp, 'coco_25')
kp = kp[:, openpose_reorder_idx]
final_keypoints.append(kp)
key["keypoints"] = final_keypoints
else:
raise Exception("Method not implemented")
self.insert1(key)
@schema
class BottomUpVideo(dj.Computed):
definition = """
-> BottomUpPeople
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
from pose_pipeline.utils.visualization import video_overlay, draw_keypoints
video = (BlurredVideo & key).fetch1("output_video")
keypoints = (BottomUpPeople & key).fetch1("keypoints")
def get_color(i):
import numpy as np
c = np.array([np.cos(i * np.pi / 2), np.cos(i * np.pi / 4), np.cos(i * np.pi / 8)]) * 127 + 127
return c.astype(int).tolist()
def overlay_fn(image, idx):
if keypoints[idx] is None:
return image
for person_idx in range(keypoints[idx].shape[0]):
image = draw_keypoints(image, keypoints[idx][person_idx], color=get_color(person_idx))
return image
fd, out_file_name = tempfile.mkstemp(suffix=".mp4")
video_overlay(video, out_file_name, overlay_fn, downsample=1)
os.close(fd)
key["output_video"] = out_file_name
self.insert1(key)
os.remove(out_file_name)
os.remove(video)
@schema
class BottomUpBridging(dj.Computed):
definition = """
-> Video
---
boxes : longblob
keypoints2d : longblob
keypoints3d : longblob
keypoint_noise : longblob
"""
def make(self, key):
from pose_pipeline.wrappers.bridging import bridging_formats_bottom_up
res = bridging_formats_bottom_up(key)
key.update(res)
self.insert1(key)
@schema
class BottomUpBridgingVideoLookup(dj.Lookup):
definition = """
skeleton : varchar(32)
"""
contents = [
{"skeleton": "bml_movi_87"},
{"skeleton": "h36m_25"},
{"skeleton": "smpl+head_30"},
{"skeleton": "mpi_inf_3dhp_28"},
{"skeleton": "coco_19"},
{"skeleton": "coco_25"},
]
@schema
class BottomUpBridgingVideo(dj.Computed):
definition = """
-> BottomUpBridging
-> BottomUpBridgingVideoLookup
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
skeleton = key["skeleton"]
from pose_pipeline.wrappers.bridging import get_overlay_callback, filter_skeleton, get_skeleton_edges
from pose_pipeline.utils.visualization import video_overlay
video = (BlurredVideo & key).fetch1("output_video")
boxes, keypoints2d = (BottomUpBridging & key).fetch1("boxes", "keypoints2d")
joint_edges = get_skeleton_edges(skeleton)
keypoints2d = filter_skeleton(keypoints2d, skeleton)
overlay_fn = get_overlay_callback(boxes, keypoints2d, joint_edges)
fd, out_file_name = tempfile.mkstemp(suffix=".mp4")
os.close(fd)
video_overlay(video, out_file_name, overlay_fn, downsample=1)
key["output_video"] = out_file_name
self.insert1(key)
os.remove(out_file_name)
os.remove(video)
@schema
class OpenPose(dj.Computed):
definition = """
-> Video
---
keypoints : longblob
pose_ids : longblob
pose_scores : longblob
face_keypoints : longblob
hand_keypoints : longblob
"""
def make(self, key):
video = Video.get_robust_reader(key, return_cap=False)
cap = cv2.VideoCapture(video)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
if width > height:
params = {"model_pose": "BODY_25", "scale_number": 4, "scale_gap": 0.25, "net_resolution": "1008x-1"}
else:
params = {"model_pose": "BODY_25", "scale_number": 4, "scale_gap": 0.25, "net_resolution": "-1x1008"}
with add_path(os.path.join(os.environ["OPENPOSE_PATH"], "build/python")):
from pose_pipeline.wrappers.openpose import openpose_parse_video
res = openpose_parse_video(video, face=False, hand=True, **params)
key["keypoints"] = [r["keypoints"] for r in res]
key["pose_ids"] = [r["pose_ids"] for r in res]
key["pose_scores"] = [r["pose_scores"] for r in res]
key["hand_keypoints"] = [r["hand_keypoints"] for r in res]
key["face_keypoints"] = [r["face_keypoints"] for r in res]
self.insert1(key)
# remove the downloaded video to avoid clutter
os.remove(video)
@schema
class OpenPoseVideo(dj.Computed):
definition = """
-> OpenPose
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
from pose_pipeline.utils.visualization import video_overlay, draw_keypoints
video = (BlurredVideo & key).fetch1("output_video")
keypoints = (OpenPose & key).fetch1("keypoints")
def overlay_fn(image, idx):
if keypoints[idx] is None:
return image
for person_idx in range(keypoints[idx].shape[0]):
image = draw_keypoints(image, keypoints[idx][person_idx])
return image
fd, out_file_name = tempfile.mkstemp(suffix=".mp4")
video_overlay(video, out_file_name, overlay_fn, downsample=1)
os.close(fd)
key["output_video"] = out_file_name
self.insert1(key)
os.remove(out_file_name)
os.remove(video)
@schema
class BlurredVideo(dj.Computed):
definition = """
-> Video
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
from pose_pipeline.utils.visualization import video_overlay
video = Video.get_robust_reader(key, return_cap=False)
keypoints = (BottomUpPeople & key & 'bottom_up_method_name="Bridging_OpenPose"').fetch1("keypoints")
def overlay_callback(image, idx):
image = image.copy()
if keypoints[idx] is None:
return image
found_noses = keypoints[idx][:, 0, -1] > 0.1
nose_positions = keypoints[idx][found_noses, 0, :2]
neck_positions = keypoints[idx][found_noses, 1, :2]
radius = np.linalg.norm(neck_positions - nose_positions, axis=1)
radius = np.clip(radius, 10, 250)
for i in range(nose_positions.shape[0]):
center = (int(nose_positions[i, 0]), int(nose_positions[i, 1]))
cv2.circle(image, center, int(radius[i]), (255, 255, 255), -1)
return image
fd, out_file_name = tempfile.mkstemp(suffix=".mp4")
os.close(fd)
video_overlay(video, out_file_name, overlay_callback, downsample=1)
key["output_video"] = out_file_name
self.insert1(key)
os.remove(out_file_name)
os.remove(video)
@schema
class TrackingBboxMethodLookup(dj.Lookup):
definition = """
tracking_method : int
---
tracking_method_name : varchar(50)
"""
contents = [
{"tracking_method": 0, "tracking_method_name": "DeepSortYOLOv4"},
{"tracking_method": 1, "tracking_method_name": "MMTrack_tracktor"},
{"tracking_method": 2, "tracking_method_name": "FairMOT"},
{"tracking_method": 3, "tracking_method_name": "TransTrack"},
{"tracking_method": 4, "tracking_method_name": "TraDeS"},
{"tracking_method": 5, "tracking_method_name": "MMTrack_deepsort"},
{"tracking_method": 6, "tracking_method_name": "MMTrack_bytetrack"},
{"tracking_method": 7, "tracking_method_name": "MMTrack_qdtrack"},
]
@schema
class TrackingBboxMethod(dj.Manual):
definition = """
-> Video
tracking_method : int
---
"""
@schema
class TrackingBbox(dj.Computed):
definition = """
-> TrackingBboxMethod
---
tracks : longblob
num_tracks : int
"""
def make(self, key):
video = Video.get_robust_reader(key, return_cap=False)
if (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "DeepSortYOLOv4":
from pose_pipeline.wrappers.deep_sort_yolov4.parser import tracking_bounding_boxes
tracks = tracking_bounding_boxes(video)
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") in "MMTrack_tracktor":
from pose_pipeline.wrappers.mmtrack import mmtrack_bounding_boxes
tracks = mmtrack_bounding_boxes(video, "tracktor")
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "MMTrack_deepsort":
from pose_pipeline.wrappers.mmtrack import mmtrack_bounding_boxes
tracks = mmtrack_bounding_boxes(video, "deepsort")
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "MMTrack_bytetrack":
from pose_pipeline.wrappers.mmtrack import mmtrack_bounding_boxes
tracks = mmtrack_bounding_boxes(video, "bytetrack")
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "MMTrack_qdtrack":
from pose_pipeline.wrappers.mmtrack import mmtrack_bounding_boxes
tracks = mmtrack_bounding_boxes(video, "qdtrack")
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "FairMOT":
from pose_pipeline.wrappers.fairmot import fairmot_bounding_boxes
tracks = fairmot_bounding_boxes(video)
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "TransTrack":
from pose_pipeline.wrappers.transtrack import transtrack_bounding_boxes
tracks = transtrack_bounding_boxes(video)
key["tracks"] = tracks
elif (TrackingBboxMethodLookup & key).fetch1("tracking_method_name") == "TraDeS":
from pose_pipeline.wrappers.trades import trades_bounding_boxes
tracks = trades_bounding_boxes(video)
key["tracks"] = tracks
else:
os.remove(video)
raise Exception(f"Unsupported tracking method: {key['tracking_method']}")
track_ids = np.unique([t["track_id"] for track in tracks for t in track])
key["num_tracks"] = len(track_ids)
self.insert1(key)
# remove the downloaded video to avoid clutter
if os.path.exists(video):
os.remove(video)
@schema
class TrackingBboxVideo(dj.Computed):
definition = """
-> BlurredVideo
-> TrackingBbox
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
import matplotlib
from pose_pipeline.utils.visualization import video_overlay
video = (BlurredVideo & key).fetch1("output_video")
tracks = (TrackingBbox & key).fetch1("tracks")
N = len(np.unique([t["track_id"] for track in tracks for t in track]))
colors = matplotlib.cm.get_cmap("hsv", lut=N)
def overlay_callback(image, idx):
image = image.copy()
for track in tracks[idx]:
c = colors(track["track_id"])
c = (int(c[0] * 255.0), int(c[1] * 255.0), int(c[2] * 255.0))
small = int(5e-3 * np.max(image.shape))
large = 2 * small
bbox = track["tlbr"]
cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (255, 255, 255), large)
cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), c, small)
label = str(track["track_id"])
textsize = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, int(5.0e-3 * image.shape[0]), 4)[0]
x = int((bbox[0] + bbox[2]) / 2 - textsize[0] / 2)
y = int((bbox[3] + bbox[1]) / 2 + textsize[1] / 2)
cv2.putText(image, label, (x, y), 0, 5.0e-3 * image.shape[0], (255, 255, 255), thickness=large)
cv2.putText(image, label, (x, y), 0, 5.0e-3 * image.shape[0], c, thickness=small)
return image
fd, fname = tempfile.mkstemp(suffix=".mp4")
os.close(fd)
video_overlay(video, fname, overlay_callback, downsample=1)
key["output_video"] = fname
self.insert1(key)
# remove the downloaded video to avoid clutter
os.remove(video)
os.remove(fname)
@schema
class PersonBboxValid(dj.Manual):
definition = """
-> TrackingBbox
video_subject_id : int
---
keep_tracks : longblob
"""
@schema
class PersonBbox(dj.Computed):
definition = """
-> PersonBboxValid
---
bbox : longblob
present : longblob
"""
def make(self, key):
tracks = (TrackingBbox & key).fetch1("tracks")
keep_tracks = (PersonBboxValid & key).fetch1("keep_tracks")
def extract_person_track(tracks):
def process_timestamp(track_timestep):
valid = [t for t in track_timestep if t["track_id"] in keep_tracks]
if len(valid) == 1:
return {"present": True, "bbox": valid[0]["tlhw"]}
else:
return {"present": False, "bbox": [0.0, 0.0, 0.0, 0.0]}
return [process_timestamp(t) for t in tracks]
LD = main_track = extract_person_track(tracks)
dict_lists = {k: [dic[k] for dic in LD] for k in LD[0]}
present = np.array(dict_lists["present"])
bbox = np.array(dict_lists["bbox"])
# smooth any brief missing frames
df = pd.DataFrame(bbox)
df.iloc[~present] = np.nan
df = df.fillna(method="bfill", axis=0, limit=2)
df = df.fillna(method="ffill", axis=0, limit=2)
# get smoothed version
key["present"] = ~df.isna().any(axis=1).values
key["bbox"] = df.values
self.insert1(key)
@staticmethod
def get_overlay_fn(key):
bboxes = (PersonBbox & key).fetch1("bbox")
def overlay_fn(image, idx, width=6, color=(255, 255, 255)):
bbox = bboxes[idx].copy()
bbox[2:] = bbox[:2] + bbox[2:]
if np.any(np.isnan(bbox)):
return image
cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, width)
return image
return overlay_fn
@property
def key_source(self):
return PersonBboxValid & "video_subject_id >= 0"
@schema
class DetectedFrames(dj.Computed):
definition = """
-> PersonBboxValid
-> VideoInfo
---
frames_detected : int
frames_missed : int
fraction_found : float
mean_other_people : float
median_confidence : float
frame_data : longblob
"""
def make(self, key):
if (PersonBboxValid & key).fetch1("video_subject_id") < 0:
key["frames_detected"] = 0
key["frames_missed"] = (VideoInfo & key).fetch1("num_frames")
# compute statistics
tracks = (TrackingBbox & key).fetch1("tracks")
keep_tracks = (PersonBboxValid & key).fetch1("keep_tracks")
def extract_person_stats(tracks):
def process_timestamp(track_timestep):
valid = [t for t in track_timestep if t["track_id"] in keep_tracks]
total_tracks = len(track_timestep)
if len(valid) == 1:
if "confidence" in valid[0].keys():
return {"present": True, "confidence": valid[0]["confidence"], "others": total_tracks - 1}
else:
return {"present": True, "confidence": 1.0, "others": total_tracks - 1}
else:
return {"present": False, "confidence": 0, "others": total_tracks}
return [process_timestamp(t) for t in tracks]
stats = extract_person_stats(tracks)
present = np.array([x["present"] for x in stats])
key["frames_detected"] = np.sum(present)
key["frames_missed"] = np.sum(~present)
key["fraction_found"] = key["frames_detected"] / (key["frames_missed"] + key["frames_detected"])
if key["frames_detected"] > 0:
key["median_confidence"] = np.median([x["confidence"] for x in stats if x["present"]])
else:
key["median_confidence"] = 0.0
key["mean_other_people"] = np.nanmean([x["others"] for x in stats])
key["frame_data"] = stats
self.insert1(key)
@property
def key_source(self):
return PersonBboxValid & "video_subject_id >= 0"
@schema
class BestDetectedFrames(dj.Computed):
definition = """
-> DetectedFrames
"""
def make(self, key):
detected_frames = (DetectedFrames & key).fetch("fraction_found", "KEY", as_dict=True)
best = np.argmax([d["fraction_found"] for d in detected_frames])
res = detected_frames[best]
res.pop("fraction_found")
self.insert1(res)
@property
def key_source(self):
return Video & DetectedFrames
@schema
class BottomUpPerson(dj.Computed):
definition = """
-> PersonBbox
-> BottomUpPeople
---
keypoints : longblob
"""
def make(self, key):
print(key)
# fetch data
keypoints = (BottomUpPeople & key).fetch1("keypoints")
bbox = (PersonBbox & key).fetch1("bbox")
res = [match_keypoints_to_bbox(bbox[idx], keypoints[idx]) for idx in range(bbox.shape[0])]
keypoints, _ = list(zip(*res))
keypoints = np.array(keypoints)
key["keypoints"] = keypoints
self.insert1(key)
@schema
class BottomUpBridgingPerson(dj.Computed):
definition = """
-> PersonBbox
-> BottomUpBridging
---
bbox : longblob
keypoints : longblob
keypoints3d : longblob
keypoint_noise : longblob
"""
def make(self, key):
from pose_pipeline.utils.keypoint_matching import compute_iou
from pose_pipeline.wrappers.bridging import noise_to_conf
bbox, present = (PersonBbox & key).fetch1("bbox", "present")
boxes, keypoints2d, keypoints3d, keypoint_noise = (BottomUpBridging & key).fetch1(
"boxes", "keypoints2d", "keypoints3d", "keypoint_noise"
)
def match_bbox(bbox1, bbox2, thresh=0.25):
iou = compute_iou(bbox1[:, :4], bbox2[None, ...])
idx = np.argmax(iou)
if iou[idx] > thresh:
return idx
return None
idx = [match_bbox(b1, b2) if b1.shape[0] > 0 else None for b1, b2 in zip(boxes, bbox)]
boxes = np.array([b[i] if i is not None else np.zeros((5,)) for b, i in zip(boxes, idx)])
keypoint_noise = np.array([k[i] if i is not None else np.zeros((580,)) for k, i in zip(keypoint_noise, idx)])
conf = noise_to_conf(keypoint_noise)
keypoints2d = np.array(
[
np.concatenate([k[i], c[:, None]], axis=1) if i is not None else np.zeros((580, 3))
for k, c, i in zip(keypoints2d, conf, idx)
]
)
keypoints3d = np.array(
[
np.concatenate([k[i], c[:, None]], axis=1) if i is not None else np.zeros((580, 4))
for k, c, i in zip(keypoints3d, conf, idx)
]
)
key["bbox"] = boxes
key["keypoints"] = keypoints2d
key["keypoints3d"] = keypoints3d
key["keypoint_noise"] = keypoint_noise
self.insert1(key)
@schema
class OpenPosePerson(dj.Computed):
definition = """
-> PersonBbox
-> OpenPose
---
keypoints : longblob
hand_keypoints : longblob
openpose_ids : longblob
"""
def make(self, key):
# fetch data
keypoints, hand_keypoints = (OpenPose & key).fetch1("keypoints", "hand_keypoints")
bbox = (PersonBbox & key).fetch1("bbox")
res = [match_keypoints_to_bbox(bbox[idx], keypoints[idx]) for idx in range(bbox.shape[0])]
keypoints, openpose_ids = list(zip(*res))
keypoints = np.array(keypoints)
openpose_ids = np.array(openpose_ids)
key["keypoints"] = keypoints
key["openpose_ids"] = openpose_ids
key["hand_keypoints"] = []
for openpose_id, hand_keypoint in zip(openpose_ids, hand_keypoints):
if openpose_id is None:
key["hand_keypoints"].append(np.zeros((2, 21, 3)))
else:
key["hand_keypoints"].append([hand_keypoint[0][openpose_id], hand_keypoint[1][openpose_id]])
key["hand_keypoints"] = np.asarray(key["hand_keypoints"])
self.insert1(key)
@staticmethod
def joint_names():
return [
"Nose",
"Sternum",
"Right Shoulder",
"Right Elbow",
"Right Wrist",
"Left Shoulder",
"Left Elbow",
"Left Wrist",
"Pelvis",
"Right Hip",
"Right Knee",
"Right Ankle",
"Left Hip",
"Left Knee",
"Left Ankle",
"Right Eye",
"Left Eye",
"Right Ear",
"Left Ear",
"Left Big Toe",
"Left Little Toe",
"Left Heel",
"Right Big Toe",
"Right Little Toe",
"Right Heel",
]
@schema
class OpenPosePersonVideo(dj.Computed):
definition = """
-> OpenPosePerson
-> BlurredVideo
---
output_video : attach@localattach # datajoint managed video file
"""
def make(self, key):
from pose_pipeline.utils.visualization import video_overlay, draw_keypoints
# fetch data
keypoints, hand_keypoints = (OpenPosePerson & key).fetch1("keypoints", "hand_keypoints")
video_filename = (BlurredVideo & key).fetch1("output_video")
fd, fname = tempfile.mkstemp(suffix=".mp4")
os.close(fd)
video = (BlurredVideo & key).fetch1("output_video")
keypoints = (OpenPosePerson & key).fetch1("keypoints")
def overlay(image, idx):
image = draw_keypoints(image, keypoints[idx])
image = draw_keypoints(image, hand_keypoints[idx, 0], threshold=0.02)
image = draw_keypoints(image, hand_keypoints[idx, 1], threshold=0.02)
return image
ofd, out_file_name = tempfile.mkstemp(suffix=".mp4")
os.close(ofd)
video_overlay(video, out_file_name, overlay, downsample=4)
key["output_video"] = out_file_name
self.insert1(key)
os.remove(out_file_name)
os.remove(video)
@schema
class TopDownMethodLookup(dj.Lookup):
definition = """
top_down_method : int
---
top_down_method_name : varchar(50)
"""
contents = [
{"top_down_method": 0, "top_down_method_name": "MMPose"},
{"top_down_method": 1, "top_down_method_name": "MMPoseWholebody"},
{"top_down_method": 2, "top_down_method_name": "MMPoseHalpe"},
{"top_down_method": 3, "top_down_method_name": "MMPoseHrformerCoco"},
{"top_down_method": 4, "top_down_method_name": "OpenPose"},
{"top_down_method": 6, "top_down_method_name": "OpenPose_BODY25B"},
{"top_down_method": 7, "top_down_method_name": "MMPoseTCFormerWholebody"},
{"top_down_method": 8, "top_down_method_name": "OpenPose_HR"},
{"top_down_method": 9, "top_down_method_name": "OpenPose_LR"},
{"top_down_method": 11, "top_down_method_name": "Bridging_COCO_25"},
{"top_down_method": 12, "top_down_method_name": "Bridging_bml_movi_87"},
{"top_down_method": 13, "top_down_method_name": "Bridging_smpl+head_30"},
{"top_down_method": 14, "top_down_method_name": "Bridging_smplx_42"},
]