-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
executable file
·1924 lines (1593 loc) · 83.5 KB
/
utils.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 torch
import smplx
import os
from datetime import datetime
import yaml
import re
import numpy as np
import open3d as o3d
import tempfile
import gzip
from glob import glob
import pickle
import json
from typing import List
import random
import trimesh
import torch.nn.functional as F
##############################################################################################################
# MEASUREMENT UTILS
##############################################################################################################
CAESAR_LANDMARK_MAPPING = {
'10th Rib Midspine': '10th Rib Midspine',
'AUX LAND': 'AUX LAND',
'Butt Block': 'Butt Block',
'Cervical': 'Cervicale', # FIXED
'Cervicale': 'Cervicale',
'Crotch': 'Crotch',
'Lt. 10th Rib': 'Lt. 10th Rib',
'Lt. ASIS': 'Lt. ASIS',
'Lt. Acromio': 'Lt. Acromion', # FIXED
'Lt. Acromion': 'Lt. Acromion',
'Lt. Axilla, An': 'Lt. Axilla, Ant.', # FIXED
'Lt. Axilla, Ant': 'Lt. Axilla, Ant.', # FIXED
'Lt. Axilla, Post': 'Lt. Axilla, Post.', # FIXED
'Lt. Axilla, Post.': 'Lt. Axilla, Post.',
'Lt. Calcaneous, Post.': 'Lt. Calcaneous, Post.',
'Lt. Clavicale': 'Lt. Clavicale',
'Lt. Dactylion': 'Lt. Dactylion',
'Lt. Digit II': 'Lt. Digit II',
'Lt. Femoral Lateral Epicn': 'Lt. Femoral Lateral Epicn',
'Lt. Femoral Lateral Epicn ': 'Lt. Femoral Lateral Epicn', # FIXED
'Lt. Femoral Medial Epicn': 'Lt. Femoral Medial Epicn',
'Lt. Gonion': 'Lt. Gonion',
'Lt. Humeral Lateral Epicn': 'Lt. Humeral Lateral Epicn',
'Lt. Humeral Medial Epicn': 'Lt. Humeral Medial Epicn',
'Lt. Iliocristale': 'Lt. Iliocristale',
'Lt. Infraorbitale': 'Lt. Infraorbitale',
'Lt. Knee Crease': 'Lt. Knee Crease',
'Lt. Lateral Malleolus': 'Lt. Lateral Malleolus',
'Lt. Medial Malleolu': 'Lt. Medial Malleolus', # FIXED
'Lt. Medial Malleolus': 'Lt. Medial Malleolus',
'Lt. Metacarpal-Phal. II': 'Lt. Metacarpal Phal. II', # FIXED
'Lt. Metacarpal-Phal. V': 'Lt. Metacarpal Phal. V', # FIXED
'Lt. Metatarsal-Phal. I': 'Lt. Metatarsal Phal. I', # FIXED
'Lt. Metatarsal-Phal. V': 'Lt. Metatarsal Phal. V', # FIXED
'Lt. Olecranon': 'Lt. Olecranon',
'Lt. PSIS': 'Lt. PSIS',
'Lt. Radial Styloid': 'Lt. Radial Styloid',
'Lt. Radiale': 'Lt. Radiale',
'Lt. Sphyrio': 'Lt. Sphyrion', # FIXED
'Lt. Sphyrion': 'Lt. Sphyrion',
'Lt. Thelion/Bustpoin': 'Lt. Thelion/Bustpoint', # FIXED
'Lt. Thelion/Bustpoint': 'Lt. Thelion/Bustpoint',
'Lt. Tragion': 'Lt. Tragion',
'Lt. Trochanterion': 'Lt. Trochanterion',
'Lt. Ulnar Styloid': 'Lt. Ulnar Styloid',
'Nuchale': 'Nuchale',
'Rt. 10th Rib': 'Rt. 10th Rib',
'Rt. ASIS': 'Rt. ASIS',
'Rt. Acromio': 'Rt. Acromion', # FIXED
'Rt. Acromion': 'Rt. Acromion',
'Rt. Axilla, An': 'Rt. Axilla, Ant.', # FIXED
'Rt. Axilla, Ant': 'Rt. Axilla, Ant.', # FIXED
'Rt. Axilla, Post': 'Rt. Axilla, Post.', # FIXED
'Rt. Axilla, Post.': 'Rt. Axilla, Post.',
'Rt. Calcaneous, Post.': 'Rt. Calcaneous, Post.',
'Rt. Clavicale': 'Rt. Clavicale',
'Rt. Dactylion': 'Rt. Dactylion',
'Rt. Digit II': 'Rt. Digit II',
'Rt. Femoral Lateral Epicn': 'Rt. Femoral Lateral Epicn',
'Rt. Femoral Lateral Epicn ': 'Rt. Femoral Lateral Epicn', # FIXED
'Rt. Femoral Medial Epic': 'Rt. Femoral Medial Epicn', # FIXED
'Rt. Femoral Medial Epicn': 'Rt. Femoral Medial Epicn',
'Rt. Gonion': 'Rt. Gonion',
'Rt. Humeral Lateral Epicn': 'Rt. Humeral Lateral Epicn',
'Rt. Humeral Medial Epicn': 'Rt. Humeral Medial Epicn',
'Rt. Iliocristale': 'Rt. Iliocristale',
'Rt. Infraorbitale': 'Rt. Infraorbitale',
'Rt. Knee Creas': 'Rt. Knee Crease', # FIXED
'Rt. Knee Crease': 'Rt. Knee Crease',
'Rt. Lateral Malleolus': 'Rt. Lateral Malleolus',
'Rt. Medial Malleolu': 'Rt. Medial Malleolus', # FIXED
'Rt. Medial Malleolus': 'Rt. Medial Malleolus',
'Rt. Metacarpal Phal. II': 'Rt. Metacarpal Phal. II',
'Rt. Metacarpal-Phal. V': 'Rt. Metacarpal Phal. V', # FIXED
'Rt. Metatarsal-Phal. I': 'Rt. Metatarsal Phal. I', # FIXED
'Rt. Metatarsal-Phal. V': 'Rt. Metatarsal Phal. V', # FIXED
'Rt. Olecranon': 'Rt. Olecranon',
'Rt. PSIS': 'Rt. PSIS',
'Rt. Radial Styloid': 'Rt. Radial Styloid',
'Rt. Radiale': 'Rt. Radiale',
'Rt. Sphyrio': 'Rt. Sphyrion', # FIXED
'Rt. Sphyrion': 'Rt. Sphyrion',
'Rt. Thelion/Bustpoin': 'Rt. Thelion/Bustpoint', # FIXED
'Rt. Thelion/Bustpoint': 'Rt. Thelion/Bustpoint',
'Rt. Tragion': 'Rt. Tragion',
'Rt. Trochanterion': 'Rt. Trochanterion',
'Rt. Ulnar Styloid': 'Rt. Ulnar Styloid',
'Sellion': 'Sellion',
'Substernale': 'Substernale',
'Supramenton': 'Supramenton',
'Suprasternale': 'Suprasternale',
'Waist, Preferred, Post.': 'Waist, Preferred, Post.'
}
SMPL_INDEX_LANDMARKS = {
'10th Rib Midspine': 3024,
# 'AUX LAND': 0, ## ??
# 'Butt Block': 0, ## ??
'Cervicale': 828,
'Crotch': 1210, ## ??
'Lt. 10th Rib': 1481,
'Lt. ASIS': 3157,
'Lt. Acromion': 636,
'Lt. Axilla, Ant.': 772,
'Lt. Axilla, Post.': 1431,
'Lt. Calcaneous, Post.': 3387,
'Lt. Clavicale': 700,
'Lt. Dactylion': 2446,
'Lt. Digit II': 3302,
'Lt. Femoral Lateral Epicn': 1053,
'Lt. Femoral Medial Epicn': 1059,
'Lt. Gonion': 147,
'Lt. Humeral Lateral Epicn': 1738,
'Lt. Humeral Medial Epicn': 1627,
'Lt. Iliocristale': 654,
'Lt. Infraorbitale': 357,
'Lt. Knee Crease': 1050,
'Lt. Lateral Malleolus': 3327,
'Lt. Medial Malleolus': 3432,
'Lt. Metacarpal Phal. II': 2135,
'Lt. Metacarpal Phal. V': 2628,
'Lt. Metatarsal Phal. I': 3232,
'Lt. Metatarsal Phal. V': 3283,
'Lt. Olecranon': 1643,
'Lt. PSIS': 3098,
'Lt. Radial Styloid': 2110,
'Lt. Radiale': 1701,
'Lt. Sphyrion': 3417,
'Lt. Thelion/Bustpoint': 670,
'Lt. Tragion': 448,
'Lt. Trochanterion': 1454,
'Lt. Ulnar Styloid': 2108,
'Nuchale': 445,
'Rt. 10th Rib': 4953,
'Rt. ASIS': 6573,
'Rt. Acromion': 4124,
'Rt. Axilla, Ant.': 4874,
'Rt. Axilla, Post.': 4906,
'Rt. Calcaneous, Post.': 6786,
'Rt. Clavicale': 4187,
'Rt. Dactylion': 5907,
'Rt. Digit II': 6702,
'Rt. Femoral Lateral Epicn': 4538,
'Rt. Femoral Medial Epicn': 4543,
'Rt. Gonion': 3659,
'Rt. Humeral Lateral Epicn': 5207,
'Rt. Humeral Medial Epicn': 5097,
'Rt. Iliocristale': 4424,
'Rt. Infraorbitale': 3847,
'Rt. Knee Crease': 4535,
'Rt. Lateral Malleolus': 6728,
'Rt. Medial Malleolus': 6832,
'Rt. Metacarpal Phal. II': 5595,
'Rt. Metacarpal Phal. V': 6089,
'Rt. Metatarsal Phal. I': 6634,
'Rt. Metatarsal Phal. V': 6684,
'Rt. Olecranon': 5112,
'Rt. PSIS': 6523,
'Rt. Radial Styloid': 5480,
'Rt. Radiale': 5170,
'Rt. Sphyrion': 6817,
'Rt. Thelion/Bustpoint': 4158,
'Rt. Tragion': 3941,
'Rt. Trochanterion': 4927,
'Rt. Ulnar Styloid': 5520,
'Sellion': 410,
'Substernale': 1330,
'Supramenton': 3051,
'Suprasternale': 3073,
'Waist, Preferred, Post.': 3159
}
# revised after comparing original and transferred landmarks
# analysed the closest SMPL indices of the fitted NRD body
# to every original landmark and manually corrected the mapping
# removing Rib landmarks cause they are predominantly missing
SMPL_INDEX_LANDAMRKS_REVISED = {
# '10th Rib Midspine': 3024,
'Cervicale': 829,
'Crotch': 1353,
# 'Lt. 10th Rib': 1481,
'Lt. ASIS': 3157,
'Lt. Acromion': 1862,
'Lt. Axilla, Ant.': 1871,
'Lt. Axilla, Post.': 2991,
'Lt. Calcaneous, Post.': 3387,
'Lt. Clavicale': 1300,
'Lt. Dactylion': 2446,
'Lt. Digit II': 3222,
'Lt. Femoral Lateral Epicn': 1008,
'Lt. Femoral Medial Epicn': 1016,
'Lt. Gonion': 148,
'Lt. Humeral Lateral Epicn': 1621,
'Lt. Humeral Medial Epicn': 1661,
'Lt. Iliocristale': 677,
'Lt. Infraorbitale': 341,
'Lt. Knee Crease': 1050,
'Lt. Lateral Malleolus': 3327,
'Lt. Medial Malleolus': 3432,
'Lt. Metacarpal Phal. II': 2258,
'Lt. Metacarpal Phal. V': 2082,
'Lt. Metatarsal Phal. I': 3294,
'Lt. Metatarsal Phal. V': 3348,
'Lt. Olecranon': 1736,
'Lt. PSIS': 3097,
'Lt. Radial Styloid': 2112,
'Lt. Radiale': 1700,
'Lt. Sphyrion': 3417,
'Lt. Thelion/Bustpoint': 598,
'Lt. Tragion': 448,
'Lt. Trochanterion': 808,
'Lt. Ulnar Styloid': 2108,
'Nuchale': 445,
# 'Rt. 10th Rib': 4953,
'Rt. ASIS': 6573,
'Rt. Acromion': 5342,
'Rt. Axilla, Ant.': 5332,
'Rt. Axilla, Post.': 6450,
'Rt. Calcaneous, Post.': 6786,
'Rt. Clavicale': 4782,
'Rt. Dactylion': 5907,
'Rt. Digit II': 6620,
'Rt. Femoral Lateral Epicn': 4493,
'Rt. Femoral Medial Epicn': 4500,
'Rt. Gonion': 3661,
'Rt. Humeral Lateral Epicn': 5090,
'Rt. Humeral Medial Epicn': 5131,
'Rt. Iliocristale': 4165,
'Rt. Infraorbitale': 3847,
'Rt. Knee Crease': 4535,
'Rt. Lateral Malleolus': 6728,
'Rt. Medial Malleolus': 6832,
'Rt. Metacarpal Phal. II': 5578,
'Rt. Metacarpal Phal. V': 5545,
'Rt. Metatarsal Phal. I': 6694,
'Rt. Metatarsal Phal. V': 6715,
'Rt. Olecranon': 5205,
'Rt. PSIS': 6521,
'Rt. Radial Styloid': 5534,
'Rt. Radiale': 5170,
'Rt. Sphyrion': 6817,
'Rt. Thelion/Bustpoint': 4086,
'Rt. Tragion': 3941,
'Rt. Trochanterion': 4310,
'Rt. Ulnar Styloid': 5520,
'Sellion': 410,
'Substernale': 3079,
'Supramenton': 3051,
'Suprasternale': 3171,
'Waist, Preferred, Post.': 3021}
SMPL_SIMPLE_LANDMARKS = {
"HEAD_TOP": 412,
"HEAD_LEFT_TEMPLE": 166,
"NECK_ADAM_APPLE": 3050,
"LEFT_HEEL": 3458,
"RIGHT_HEEL": 6858,
"LEFT_NIPPLE": 3042,
"RIGHT_NIPPLE": 6489,
"SHOULDER_TOP": 829,
"INSEAM_POINT": 3149,
"BELLY_BUTTON": 3501,
"BACK_BELLY_BUTTON": 3022,
"CROTCH": 1210,
"PUBIC_BONE": 3145,
"RIGHT_WRIST": 5559,
"LEFT_WRIST": 2241,
"RIGHT_BICEP": 4855,
"RIGHT_FOREARM": 5197,
"LEFT_SHOULDER": 3011,
"RIGHT_SHOULDER": 6470,
"LOW_LEFT_HIP": 3134,
"LEFT_THIGH": 947,
"LEFT_CALF": 1103,
"LEFT_ANKLE": 3325,
"LEFT_ELBOW": 1643,
"BUTTHOLE":3119,
# introduce CAESAR landmarks because
# i need to measure arms in parts
"Cervicale": 829,
'Rt. Acromion': 5342,
'Rt. Humeral Lateral Epicn': 5090,
'Rt. Ulnar Styloid': 5520,
}
SMPL_SIMPLE_LANDMARKS["HEELS"] = (SMPL_SIMPLE_LANDMARKS["LEFT_HEEL"],
SMPL_SIMPLE_LANDMARKS["RIGHT_HEEL"])
SMPL_SIMPLE_MEASUREMENTS = {
"waist circumference": {"measurement_type": "circumference",
"indices": [3500, 1336, 917, 916, 919, 918, 665, 662,
657, 654, 631, 632, 720, 799, 796, 890, 889, 3124, 3018,
3019, 3502, 6473, 6474, 6545, 4376, 4375, 4284, 4285, 4208,
4120, 4121, 4142, 4143, 4150, 4151, 4406, 4405,
4403, 4402, 4812, 3500]},
"chest circumference": {"measurement_type": "circumference",
"indices": [3076, 2870, 1254, 1255, 1349, 1351, 3033,
3030, 3037, 3034, 3039, 611, 2868, 2864, 2866,
1760, 1419, 741, 738, 759, 2957, 2907, 1435, 1436,
1437, 1252, 1235, 749, 752, 3015, 4238, 4237, 4718,
4735, 4736, 4909, 6366, 4249, 4250, 4225, 4130, 4131,
4895, 4683,4682,4099, 4898, 4894, 4156, 4159, 4086,
4089, 4174, 4172, 4179, 6332,3076]},
"hip circumference": {"measurement_type": "circumference",
"indices": [1806, 1805, 1804, 1803, 1802, 1801, 1800, 1798,
1797, 1796, 1794, 1791, 1788, 1787, 3101, 3114, 3121, 3098,
3099, 3159, 6522, 6523, 6542, 6537, 6525, 5252, 5251, 5255,
5256, 5258, 5260, 5261, 5264, 5263, 5266, 5265, 5268, 5267,
1806]},
"thigh left circumference": {"measurement_type": "circumference",
"indices": [877, 874, 873, 848, 849, 902, 851, 852, 897,
900, 933, 936, 1359, 963, 908, 911, 1366,877]},
"calf left circumference": {"measurement_type": "circumference",
"indices": [1154, 1372, 1074, 1077, 1470, 1094, 1095, 1473,
1465, 1466, 1108, 1111, 1530, 1089, 1086, 1154]},
"ankle left circumference": {"measurement_type": "circumference",
"indices": [3322, 3323, 3190, 3188, 3185, 3206, 3182,
3183, 3194, 3195, 3196, 3176, 3177, 3193, 3319, 3322]},
"wrist left circumference": {"measurement_type": "circumference",
"indices": [1922, 1970, 1969, 2244, 1945, 1943, 1979,
1938, 1935, 2286, 2243, 2242, 1930, 1927, 1926, 1924, 1922]},
"forearm left circumference": {"measurement_type": "circumference",
"indices": [1573, 1915, 1914, 1577, 1576, 1912, 1911,
1624, 1625, 1917, 1611, 1610, 1607, 1608, 1916, 1574, 1573]},
"bicep left circumference": {"measurement_type": "circumference",
"indices": [789, 1311, 1315, 1379, 1378, 1394, 1393,
1389, 1388, 1233, 1232, 1385, 1381, 1382, 1397, 1396, 628, 627,789]},
"neck circumference": {"measurement_type": "circumference",
"indices": [3068, 1331, 215, 216, 440, 441, 452, 218, 219,
222, 425, 426, 453, 829, 3944, 3921, 3920, 3734, 3731, 3730,
3943, 3935, 3934, 3728, 3729, 4807, 3068]},
"head circumference": {"measurement_type": "circumference",
"indices": [335, 259, 133, 0, 3, 135, 136, 160, 161, 166,
167, 269, 179, 182, 252, 253, 384, 3765, 3766, 3694, 3693,
3782, 3681, 3678, 3671, 3672, 3648, 3647, 3513, 3512, 3646,
3771, 335]},
"height": {"measurement_type": "length",
"landmark_names": ["HEAD_TOP", "HEELS"]},
"shoulder to crotch height": {"measurement_type": "length",
"landmark_names": ["SHOULDER_TOP", "INSEAM_POINT"]},
"arm right length": {"measurement_type": "length",
"landmark_names": ["RIGHT_SHOULDER", "RIGHT_WRIST"]},
"crotch height": {"measurement_type": "length",
"landmark_names": ["INSEAM_POINT", "HEELS"]},
"Hip circumference max height": {"measurement_type": "length",
"landmark_names": ["LOW_LEFT_HIP", "HEELS"]},
"arm length (shoulder to elbow)": {"measurement_type": "length",
"landmark_names": ["LEFT_SHOULDER", "LEFT_ELBOW"]},
"arm length (spine to wrist)": {"measurement_type": "length",
"landmark_names": ["SHOULDER_TOP", "RIGHT_WRIST"]}
}
# revised after visualizing point importance for measurements on SMPL
SMPL_SIMPLE_MEASUREMENTS_REVISED = {
"waist circumference": {"measurement_type": "circumference",
"indices": [3500, 1336, 917, 916, 919, 918, 665, 662,
657, 654, 631, 632, 720, 799, 796, 890, 889, 3124, 3018,
3019, 3502, 6473, 6474, 6545, 4376, 4375, 4284, 4285, 4208,
4120, 4121, 4142, 4143, 4150, 4151, 4406, 4405,
4403, 4402, 4812, 3500]},
"chest circumference": {"measurement_type": "circumference",
"indices": [6310,4380,4379,6367,4213,4250,
4225,4130,4131,4895,4683,4681,4676,4893,4157,
4158,4087,4088,4175,4179,6331,3077,2871,691,685,600,601,670,
671,1191,1190,1193,1194,1756,1423,645,642,736,764,723,2908,1253,892,
2850,2849,3025,3505,6475,6311,6310]
},
"hip circumference": {"measurement_type": "circumference",
"indices": [1807, 864, 863, 1205, 1204, 915, 1511, 1513, 932, 1454, 1446,
1447, 3084, 3136, 3137, 3138, 3116, 3117,3118, 3119, 6541,
6539, 6540, 6559, 6558, 6557, 6509, 4919, 4920, 4927, 4418, 4353,
4983, 4923, 4690, 4692, 4351, 4350, 1807]},
"thigh left circumference": {"measurement_type": "circumference",
"indices": [877, 874, 873, 848, 849, 902, 851, 852, 897,
900, 933, 936, 1359, 963, 908, 911, 1366,877]},
"calf left circumference": {"measurement_type": "circumference",
"indices": [1154, 1372, 1074, 1077, 1470, 1094, 1095, 1473,
1465, 1466, 1108, 1111, 1530, 1089, 1086, 1154]},
"ankle left circumference": {"measurement_type": "circumference",
"indices": [3325, 3326, 3208, 3207, 3204, 3205, 3202, 3203,
3200, 3201, 3210, 3198, 3199, 3209, 3324, 3325]},
"wrist left circumference": {"measurement_type": "circumference",
"indices": [1922, 1970, 1969, 2244, 1945, 1943, 1979,
1938, 1935, 2286, 2243, 2242, 1930, 1927, 1926, 1924, 1922]},
"forearm left circumference": {"measurement_type": "circumference",
"indices": [1573, 1915, 1914, 1577, 1576, 1912, 1911,
1624, 1625, 1917, 1611, 1610, 1607, 1608, 1916, 1574, 1573]},
"bicep left circumference": {"measurement_type": "circumference",
"indices": [789, 1311, 1315, 1379, 1378, 1394, 1393,
1389, 1388, 1233, 1232, 1385, 1381, 1382, 1397, 1396, 628, 627,789]},
"neck circumference": {"measurement_type": "circumference",
"indices": [829, 3944, 3921, 3920, 3734, 3731, 4761, 4309, 4072, 4781, 4187, 6333, 3078, 2872, 700, 1299, 584, 821,
1280, 219, 222, 425, 426, 453, 829]},
"head circumference": {"measurement_type": "circumference",
"indices": [335, 259, 133, 0, 3, 135, 136, 160, 161, 166,
167, 269, 179, 182, 252, 253, 384, 3765, 3766, 3694, 3693,
3782, 3681, 3678, 3671, 3672, 3648, 3647, 3513, 3512, 3646,
3771, 335]},
"height": {"measurement_type": "length",
"landmark_names": ["HEAD_TOP", "HEELS"]},
"shoulder to crotch height": {"measurement_type": "length",
"landmark_names": ["SHOULDER_TOP", "INSEAM_POINT"]},
"arm right length": {"measurement_type": "length",
"landmark_names": ["RIGHT_SHOULDER", "RIGHT_WRIST"]},
"crotch height": {"measurement_type": "length",
"landmark_names": ["INSEAM_POINT", "HEELS"]},
"Hip circumference max height": {"measurement_type": "length",
"landmark_names": ["BUTTHOLE", "HEELS"]},
"arm length (shoulder to elbow)": {"measurement_type": "length",
"landmark_names": ["LEFT_SHOULDER", "LEFT_ELBOW"]},
"arm length (spine to wrist)": {"measurement_type": "length",
"landmark_names": ["SHOULDER_TOP", "RIGHT_WRIST"]},
"leg length": {"measurement_type": "length",
"landmark_names": ["LOW_LEFT_HIP", "LEFT_HEEL"]},
}
# revised arm lenght to be able to measure it in parts
SMPL_SIMPLE_MEASUREMENTS_REVISED2 = {
"waist circumference": {"measurement_type": "circumference",
"indices": [3500, 1336, 917, 916, 919, 918, 665, 662,
657, 654, 631, 632, 720, 799, 796, 890, 889, 3124, 3018,
3019, 3502, 6473, 6474, 6545, 4376, 4375, 4284, 4285, 4208,
4120, 4121, 4142, 4143, 4150, 4151, 4406, 4405,
4403, 4402, 4812, 3500]},
"chest circumference": {"measurement_type": "circumference",
"indices": [6310,4380,4379,6367,4213,4250,
4225,4130,4131,4895,4683,4681,4676,4893,4157,
4158,4087,4088,4175,4179,6331,3077,2871,691,685,600,601,670,
671,1191,1190,1193,1194,1756,1423,645,642,736,764,723,2908,1253,892,
2850,2849,3025,3505,6475,6311,6310]
},
"hip circumference": {"measurement_type": "circumference",
"indices": [1807, 864, 863, 1205, 1204, 915, 1511, 1513, 932, 1454, 1446,
1447, 3084, 3136, 3137, 3138, 3116, 3117,3118, 3119, 6541,
6539, 6540, 6559, 6558, 6557, 6509, 4919, 4920, 4927, 4418, 4353,
4983, 4923, 4690, 4692, 4351, 4350, 1807]},
"thigh left circumference": {"measurement_type": "circumference",
"indices": [877, 874, 873, 848, 849, 902, 851, 852, 897,
900, 933, 936, 1359, 963, 908, 911, 1366,877]},
"calf left circumference": {"measurement_type": "circumference",
"indices": [1154, 1372, 1074, 1077, 1470, 1094, 1095, 1473,
1465, 1466, 1108, 1111, 1530, 1089, 1086, 1154]},
"ankle left circumference": {"measurement_type": "circumference",
"indices": [3325, 3326, 3208, 3207, 3204, 3205, 3202, 3203,
3200, 3201, 3210, 3198, 3199, 3209, 3324, 3325]},
"wrist left circumference": {"measurement_type": "circumference",
"indices": [1922, 1970, 1969, 2244, 1945, 1943, 1979,
1938, 1935, 2286, 2243, 2242, 1930, 1927, 1926, 1924, 1922]},
"forearm left circumference": {"measurement_type": "circumference",
"indices": [1573, 1915, 1914, 1577, 1576, 1912, 1911,
1624, 1625, 1917, 1611, 1610, 1607, 1608, 1916, 1574, 1573]},
"bicep left circumference": {"measurement_type": "circumference",
"indices": [789, 1311, 1315, 1379, 1378, 1394, 1393,
1389, 1388, 1233, 1232, 1385, 1381, 1382, 1397, 1396, 628, 627,789]},
"neck circumference": {"measurement_type": "circumference",
"indices": [829, 3944, 3921, 3920, 3734, 3731, 4761, 4309, 4072, 4781, 4187, 6333, 3078, 2872, 700, 1299, 584, 821,
1280, 219, 222, 425, 426, 453, 829]},
"head circumference": {"measurement_type": "circumference",
"indices": [335, 259, 133, 0, 3, 135, 136, 160, 161, 166,
167, 269, 179, 182, 252, 253, 384, 3765, 3766, 3694, 3693,
3782, 3681, 3678, 3671, 3672, 3648, 3647, 3513, 3512, 3646,
3771, 335]},
"height": {"measurement_type": "length",
"landmark_names": ["HEAD_TOP", "HEELS"]},
"shoulder to crotch height": {"measurement_type": "length",
"landmark_names": ["SHOULDER_TOP", "INSEAM_POINT"]},
"arm right length": {"measurement_type": "length",
"landmark_names": ["Rt. Acromion", "Rt. Humeral Lateral Epicn", "Rt. Ulnar Styloid"]},
"crotch height": {"measurement_type": "length",
"landmark_names": ["INSEAM_POINT", "HEELS"]},
"Hip circumference max height": {"measurement_type": "length",
"landmark_names": ["BUTTHOLE", "HEELS"]},
"arm length (shoulder to elbow)": {"measurement_type": "length",
"landmark_names": ["Rt. Acromion", "Rt. Humeral Lateral Epicn"]},
"arm length (spine to wrist)": {"measurement_type": "length",
"landmark_names": ["Cervicale", "Rt. Acromion",
"Rt. Humeral Lateral Epicn","Rt. Ulnar Styloid"]},
"leg length": {"measurement_type": "length",
"landmark_names": ["LOW_LEFT_HIP", "LEFT_HEEL"]},
}
SMPL_SIMPLE2CAESAR_MEASUREMENTS_MAP = {'ankle left circumference': 'Ankle Circumference (mm)',
'arm length (shoulder to elbow)': 'Arm Length (Shoulder to Elbow) (mm)',
'arm right length': 'Arm Length (Shoulder to Wrist) (mm)',
'arm length (spine to wrist)': 'Arm Length (Spine to Wrist) (mm)',
'chest circumference': 'Chest Circumference (mm)',
'crotch height': 'Crotch Height (mm)',
'head circumference': 'Head Circumference (mm)',
'Hip circumference max height': 'Hip Circ Max Height (mm)',
'hip circumference': 'Hip Circumference, Maximum (mm)',
'neck circumference': 'Neck Base Circumference (mm)',
'height': 'Stature (mm)'}
TSOLI_MALE_ERRORS_MM = dict(zip(["Ankle Circumference (mm)" ,
"Arm Length (Shoulder to Elbow) (mm)",
"Arm Length (Shoulder to Wrist) (mm)",
"Arm Length (Spine to Wrist) (mm)",
"Chest Circumference (mm)",
"Crotch Height (mm)",
"Head Circumference (mm)",
"Hip Circ Max Height (mm)",
"Hip Circumference, Maximum (mm)",
"Neck Base Circumference (mm)",
"Stature (mm)"],
[5.56, 13.32, 12.66, 10.40, 13.02, 8.36, 5.59, 19.05, 10.66, 13.47, 6.53]
))
TSOLI_FEMALE_ERRORS_MM = dict(zip(["Ankle Circumference (mm)" ,
"Arm Length (Shoulder to Elbow) (mm)",
"Arm Length (Shoulder to Wrist) (mm)",
"Arm Length (Spine to Wrist) (mm)",
"Chest Circumference (mm)",
"Crotch Height (mm)",
"Head Circumference (mm)",
"Hip Circ Max Height (mm)",
"Hip Circumference, Maximum (mm)",
"Neck Base Circumference (mm)",
"Stature (mm)"],
[6.19, 6.65, 10.05, 11.87, 12.73, 5.50, 5.91, 18.59, 12.35, 15.43, 7.51]
))
TSOLI_MALE_ERRORS_IN_CM = {m_name.replace("(mm)","(cm)"): (m_val / 10) for m_name, m_val in TSOLI_MALE_ERRORS_MM.items()}
TSOLI_FEMALE_ERRORS_IN_CM = {m_name.replace("(mm)","(cm)"): (m_val / 10) for m_name, m_val in TSOLI_FEMALE_ERRORS_MM.items()}
def get_average_landmark(vertices, landmark_indices, landmark_name):
lm_ind1 = landmark_indices[landmark_name][0]
lm_ind2 = landmark_indices[landmark_name][1]
return (vertices[lm_ind1,:] + vertices[lm_ind2,:]) / 2
def get_simple_measurements(vertices, landmark_indices, measurement_definitions, use_measurements):
estimated_measurements = torch.zeros(len(use_measurements))
for i, m_name in enumerate(use_measurements):
if m_name in measurement_definitions.keys():
meas_def = measurement_definitions[m_name]
if meas_def["measurement_type"] == "circumference":
looped_indices = meas_def["indices"]
verts1 = vertices[looped_indices[1:],:]
verts2 = vertices[looped_indices[:-1]]
estimated_measurements[i] = torch.sum(torch.sqrt(torch.sum((verts1-verts2)** 2,1)))
else:
landmark_names = meas_def["landmark_names"]
accumulated_measurement = 0
for j in range(len(landmark_names)-1):
if isinstance(landmark_indices[landmark_names[j]],tuple):
pt1 = get_average_landmark(vertices, landmark_indices, landmark_names[j])
else:
pt1 = vertices[landmark_indices[landmark_names[j]],:]
if isinstance(landmark_indices[landmark_names[j+1]],tuple):
pt2 = get_average_landmark(vertices, landmark_indices, landmark_names[j+1])
else:
pt2 = vertices[landmark_indices[landmark_names[j+1]],:]
accumulated_measurement += torch.norm(pt1.float()-pt2.float())
estimated_measurements[i] = accumulated_measurement
# if isinstance(landmark_indices[landmark_names[0]],tuple):
# pt1a = vertices[landmark_indices[landmark_names[0]][0],:]
# pt1b = vertices[landmark_indices[landmark_names[0]][1],:]
# pt1 = (pt1a+pt1b)/2
# else:
# pt1 = vertices[landmark_indices[landmark_names[0]],:]
# if isinstance(landmark_indices[landmark_names[1]],tuple):
# pt2a = vertices[landmark_indices[landmark_names[1]][0],:]
# pt2b = vertices[landmark_indices[landmark_names[1]][1],:]
# pt2 = (pt2a+pt2b)/2
# else:
# pt2 = vertices[landmark_indices[landmark_names[1]],:]
# estimated_measurements[i] = torch.norm(pt1.float()-pt2.float())
else:
raise ValueError(f"Measurement {m_name} not found in measurement_definitions")
return estimated_measurements * 100 # convert to cm
def get_normalizing_landmark(landmark_names: list):
"""
Find index of normalizing landmark
"""
if "Substernale" in landmark_names:
landmark_normalizing_name = "Substernale"
elif "Nose" in landmark_names:
landmark_normalizing_name = "Nose"
elif "BELLY_BUTTON" in landmark_names:
landmark_normalizing_name = "BELLY_BUTTON"
else:
landmark_normalizing_name = landmark_names[0] # assign random landmark
landmark_normalizing_ind = landmark_names.index(landmark_normalizing_name)
return landmark_normalizing_name, landmark_normalizing_ind
def process_caesar_landmarks(landmark_path: str, scale: float = 1000.0):
"""
Process landmarks from .lnd file - reading file from AUX to END flags.
:param landmark_path (str): path to landmark .lnd file
:param scale (float): scale of landmark coordinates
Return: list of landmark names and coordinates
:return landmark_dict (dict): dictionary with landmark names as keys and
landmark coordinates as values
landmark_coords are (np.array): (1,3) array
of landmark coordinates
"""
landmark_coords = []
landmark_names = []
with open(landmark_path, 'r') as file:
do_read = False
for line in file:
# start reading file when encounter AUX flag
if line == "AUX =\n":
do_read = True
# skip to the next line
continue
# stop reading file when encounter END flag
if line == "END =\n":
do_read = False
if do_read:
# EXAMPLE OF LINE IN LANDMARKS
# 1 0 1 43.22 19.77 -38.43 522.00 Sellion
# where the coords should be
# 0.01977, -0.03843, 0.522
# this means that the last three floats before
# the name of the landmark are the coords
# find landmark coordinates
landmark_coordinate = re.findall(r"[-+]?\d+\.*\d*", line)
# print(line)
# print(landmark_coordinate)
x = float(landmark_coordinate[-3]) / scale
y = float(landmark_coordinate[-2]) / scale
z = float(landmark_coordinate[-1]) / scale
# find landmark name
# (?: ......)+ repeats the pattern inside the parenthesis
# \d* says it can be 0 or more digits in the beginning
# [a-zA-Z]+ says it needs to be one or more characters
# [.,/]* says it can be 0 or more symbols
# \s* says it can be 0 ore more spaces
# NOTE: this regex misses the case for landmarks with names
# AUX LAND 79 -- it parses it as AUX LAND -- which is ok for our purposes
landmark_name = re.findall(r" (?:\d*[a-zA-Z]+[-.,/]*\s*)+", line)
landmark_name = landmark_name[0][1:-1]
landmark_name_standardized = CAESAR_LANDMARK_MAPPING[landmark_name]
# * zero or more of the preceding character.
# + one or more of the preceding character.
# ? zero or one of the preceding character.
landmark_coords.append([x,y,z])
landmark_names.append(landmark_name_standardized)
landmark_coords = np.array(landmark_coords)
return dict(zip(landmark_names, landmark_coords))
##############################################################################################################
# TRAINING UTILS
##############################################################################################################
# from here https://stackoverflow.com/questions/49433936/how-do-i-initialize-weights-in-pytorch
def weights_init_general_strategy(params,in_features, **kwargs):
y = 1.0/np.sqrt(in_features)
return torch.FloatTensor(params.data.shape).uniform_(-y,y)
def weights_init(network, strategy_name, strategy_params):
"""
Initialize weights of the network according to the given strategy
:param network: torch model to initialize weights
:param strategy_name (Str): name of the strategy to use
:param strategy_params (Dict): dictionary with parameters for the strategy
"""
if isinstance(strategy_name,type(None)):
return network
if strategy_name == "output_layer_bias_to_mean_measurement":
out_layer = getattr(network,"output_layer")
out_layer_weights = getattr(out_layer,"weight")
out_layer_bias = getattr(out_layer,"bias")
set_bias_to = torch.tensor(strategy_params["output_layer"]["bias"])
setattr(out_layer_bias,"data",set_bias_to)
set_weights_to = strategy_params["output_layer"]["weight"]
out_layer_weights.data.fill_(set_weights_to)
elif strategy_name == "initialize_to_learned_LR":
model_path = strategy_params["model_path"]
with open(model_path,"rb") as f:
model = pickle.load(f)
set_weights_to = torch.from_numpy(model.coef_).float() # dim 11 x 170 (nr input features)
set_bias_to = torch.from_numpy(model.intercept_).float() # dim 11
out_layer = getattr(network,"output_layer")
out_layer_weights = getattr(out_layer,"weight")
out_layer_bias = getattr(out_layer,"bias")
setattr(out_layer_weights,"data",set_weights_to)
setattr(out_layer_bias,"data",set_bias_to)
return network
def set_seed(sd):
torch.manual_seed(sd)
random.seed(sd)
np.random.seed(sd)
def normal_sample_shape(batch_size, mean_shape, std_vector):
"""
Gaussian sampling of shape parameter given deviations from the mean.
"""
shape = mean_shape + torch.randn(batch_size, mean_shape.shape[0], device=mean_shape.device)*std_vector
return shape # (bs, num_smpl_betas)
def create_body_model(body_model_path: str, body_model_type: str, gender: str ="neutral", num_betas: int =10):
'''
Create SMPL body model
:param: body_model_path (str): location to SMPL .pkl models
:param body_model_type (str): smpl, smplx
:param: gender (str): male, female or neutral
:param: num_betas (int): number of SMPL shape coefficients
requires the model with num_coefs in smpl_path
Return:
:param: SMPL body model
'''
body_model_path = os.path.join(body_model_path,
body_model_type,
f"{body_model_type.upper()}_{gender.upper()}.pkl")
return smplx.create(body_model_path,
# model_type=body_model_type.upper(),
# gender=gender.upper(),
num_betas=num_betas,
ext='pkl')
def create_results_directory(save_path: str = "/pose-independent-anthropometry/results",
continue_run: str = None):
"""
Save results in save_path as YYYY_MM_DD_HH_MM_SS folder.
If continue_run is folder of type YYYY_MM_DD_HH_MM_SS, then
save results in {save_path}/{continue_run} folder.
:param save_path: path to save results to
:param continue_run: string of type YYYY_MM_DD_HH_MM_SS
"""
if continue_run:
# check if formatting of continue_run folder looks like "%Y_%m_%d_%H_%M_%S"
# wil raise ValueError if not
try:
_ = datetime.strptime(continue_run.split("/")[-1],"%Y_%m_%d_%H_%M_%S")
except Exception as e:
raise ValueError("CONTINUE_RUN must be a folder of type YYYY_MM_DD_HH_MM_SS")
print(f"Continuing run from previous checkpoint")
save_path = os.path.join(save_path,continue_run)
else:
current_time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
save_path = os.path.join(save_path,current_time)
if not os.path.exists(save_path):
os.makedirs(save_path)
print(f"Saving results to {save_path}")
return save_path
def load_config(path="configs/config.yaml"):
with open(path,'r') as f:
cfg = yaml.safe_load(f)
return cfg
def parse_landmark_txt_coords_formatting(data: List[str]):
"""
Parse landamrk txt file where each line is formatted as:
x_coord y_coord z_coord landmark_name
:param data (List[str]) list of strings, each string
represents one line from the txt file
:return landmarks (dict) in formatting
{landmark_name: [x,y,z]}
"""
# get number of landmarks
N = len(data)
if data[-1] == "\n":
N -= 1
# define landmarks
landmarks = {}
for i in range(N):
splitted_line = data[i].split(" ")
x = float(splitted_line[0])
y = float(splitted_line[1])
z = float(splitted_line[2])
remaining_line = splitted_line[3:]
landmark_name = " ".join(remaining_line)
if landmark_name[-1:] == "\n":
landmark_name = landmark_name[:-1]
landmarks[landmark_name] = [x,y,z]
return landmarks
def parse_landmark_txt_index_formatting(data):
"""
Parse landamrk txt file with formatting
landmark_index landmark_name
:param data (List[str]) list of strings, each string
represents one line from the txt file
:return landmarks (dict) in formatting
{landmark_name: index}
"""
# get number of landmarks
N = len(data)
if data[-1] == "\n":
N -= 1
# define landmarks
landmark_indices = {}
for i in range(N):
splitted_line = data[i].split(" ")
ind = int(splitted_line[0])
remaining_line = splitted_line[1:]
landmark_name = " ".join(remaining_line)
if landmark_name[-1:] == "\n":
landmark_name = landmark_name[:-1]
landmark_indices[landmark_name] = ind
return landmark_indices
def load_landmarks(landmark_path: str,
landmark_subset: List[str] = None,
scan_vertices: np.ndarray = None,
landmarks_scale: float = 1000,
verbose: bool = True):
"""
Load landmarks from file and return the landmarks as
torch tensor.
Landmark file is defined in the following format:
.txt extension
Option1) x y z landmark_name
Option2) landmark_index landmark_name
.json extension
Option1) {landmark_name: [x,y,z]}
Option2) {landmark_name: index}
:param landmark_path: (str) of path to landmark file
:param landmark_subset: (list) list of strings of landmark
names to use
:param scan_vertices: (torch.tensor) dim (N,3) of the vertices
if landmarks defined as indices of the
vertices, returin landmarks as
scan_vertices[landmark_indices,:]
Return: landmarks: np.array of landmarks
with dim (K,3)
"""
# if empty landmark subset, return None
if landmark_subset == []:
return {}
ext = landmark_path.split(".")[-1]
supported_extensions = [".txt",".json",".lnd"]
formatting_type = "indices"
if ext == "txt":
# read txt file
with open(landmark_path, 'r') as file:
data = file.readlines()
# check formatting type
try:
_ = float(data[0].split(" ")[1])
formatting_type = "coords"
except Exception as e:
pass
# parse landmarks
if formatting_type == "coords":
landmarks = parse_landmark_txt_coords_formatting(data)
elif formatting_type == "indices":
if isinstance(scan_vertices,type(None)):
msg = "Scan vertices need to be provided for"
msg += "index type of landmark file formatting"
raise NameError(msg)
landmark_inds = parse_landmark_txt_index_formatting(data)
landmarks = {}
for lm_name, lm_ind in landmark_inds.items():
landmarks[lm_name] = scan_vertices[lm_ind,:]
elif ext == "json":
with open(landmark_path,"r") as f:
data = json.load(f)
# check formatting type
first_lm = list(data.keys())[0]
if isinstance(data[first_lm],list):
formatting_type = "coords"
if formatting_type == "coords":
landmarks = landmarks = {lm_name: np.array(lm_val) for lm_name,lm_val in data.items()}
elif formatting_type == "indices":
if isinstance(scan_vertices,type(None)):
msg = "Scan vertices need to be provided for"
msg += "index type of landmark file formatting"
raise NameError(msg)
landmarks = {}
for lm_name, lm_ind in data.items():
landmarks[lm_name] = scan_vertices[lm_ind,:]
elif ext == "lnd":
if verbose:
print("Be aware that the .lnd extension assumes you are using the caesar dataset.")
landmarks = process_caesar_landmarks(landmark_path,landmarks_scale)
else: