-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
executable file
·1677 lines (1391 loc) · 76.8 KB
/
dataset.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 numpy as np
import torch
from torch.utils.data import Dataset
import random
import os
import pandas as pd
from glob import glob
import gzip
import tempfile
import open3d as o3d
from typing import List
import argparse
from sklearn.cluster import MiniBatchKMeans
import pickle
from copy import deepcopy
from tqdm import tqdm
import h5py
import sys
from utils import (create_body_model,
SMPL_SIMPLE_LANDMARKS,
SMPL_SIMPLE_MEASUREMENTS,
SMPL_SIMPLE_MEASUREMENTS_REVISED,
get_normalizing_landmark,
process_caesar_landmarks,
pelvis_normalization,
unpose_caesar,
repose_caesar,
load_scan,
get_moyo_poses,
load_landmarks)
import utils
from losses import MaxMixturePrior
class DYNA(Dataset):
'''
DYNA dataset
y-axis is height
orig scale is meters --> convert to cm
measurements are in cm
'''
def __init__(self,
dataset_path: str = "/data/DYNA",
subject_id: str = "50009",
subject_action: str = "jumping_jacks",
use_landmarks: str = "SMPL_INDEX_LANDAMRKS_REVISED",
measurement_type: str = None,
pelvis_normalization: bool = False,
**kwargs):
"""
:param dataset_path: (str) path to DYNA dataset
:param subject_id: (str) subject id
:param subject_action: (str) action performed by subject
:param use_landmarks: (str) landmarks defined on the SMPL model from utils.py
:param measurement_type: (str) type of measurements to load
-> npy measurement file per subject
with potentially multiple measurements
not necessary for evaluation on DYNA
:param pelvis_normalization: (bool) whether to normalize landmarks to pelvis
"""
self.subject_id = subject_id
# pelvis normalization
self.pelvis_normalization = pelvis_normalization
landmarks_dict = getattr(utils, use_landmarks.upper(), None)
self.landmark_names = list(landmarks_dict.keys())
self.rt_psis_ind = self.landmark_names.index("Rt. PSIS")
self.lt_psis_ind = self.landmark_names.index("Lt. PSIS")
self.rt_asis_ind = self.landmark_names.index("Rt. ASIS")
self.lt_asis_ind = self.landmark_names.index("Lt. ASIS")
self.nuchale_ind = self.landmark_names.index("Nuchale")
genders = {'50002': 'male',
'50007': 'male',
'50009': 'male',
'50026': 'male',
'50027': 'male',
'50004': 'female',
'50020': 'female',
'50021': 'female',
'50022': 'female',
'50025': 'female'}
self.subject_gender = genders[subject_id]
data_all_subjects = h5py.File(os.path.join(dataset_path,
f"dyna_{self.subject_gender.lower()}.h5"), 'r')
seq_name = f"{subject_id}_{subject_action}"
self.subject_sequence_data = data_all_subjects[seq_name][()].transpose(2,0,1)
self.scan_faces = data_all_subjects["faces"][()]
if not isinstance(measurement_type, type(None)):
measurements_dir_path = os.path.join(dataset_path, "measurements")
self.subject_measurements = np.load(os.path.join(measurements_dir_path,
f"{subject_id}.npz"))[measurement_type]
self.subject_measurements = torch.from_numpy(self.subject_measurements)
else:
self.subject_measurements = None
landmark_dict = getattr(utils, use_landmarks.upper(), None)
landmark_names = list(landmark_dict.keys())
self.landmark_indices = list(landmark_dict.values())
self.SCALE_TO_CM = 100
def __getitem__(self, index):
"""
:return (dict): dictionary with keys:
"name": name of scan
"vertices": (N,3) np.array
"faces": (N,3) np.array or None if no faces
"landmarks": dict with landmark names as keys and landmark coords as values
landmark coords are (1,3) np.array or None if no landmarks
"""
# load scan
scan_vertices = self.subject_sequence_data[index]
scan_vertices = torch.from_numpy(scan_vertices)
# load landmarks
landmarks = scan_vertices[self.landmark_indices,:]
# load measurements
measurements = self.subject_measurements
# pelvis normalization
if self.pelvis_normalization:
landmarks, centroid, R2y, R2z = pelvis_normalization(landmarks,
self.rt_psis_ind,
self.lt_psis_ind,
self.rt_asis_ind,
self.lt_asis_ind,
self.nuchale_ind,
return_transformations=True)
scan_vertices = scan_vertices - centroid
scan_vertices = torch.matmul(scan_vertices, R2y.T) # K x 3
scan_vertices = torch.matmul(scan_vertices, R2z.T)
return_dict = {"name": f"{self.subject_id}_t{index}",
"vertices": scan_vertices * self.SCALE_TO_CM,
"faces": self.scan_faces,
"landmarks": landmarks * self.SCALE_TO_CM,
"measurements": measurements,
"gender": self.subject_gender
}
return return_dict
def __len__(self):
return self.subject_sequence_data.shape[0]
class FourDHumanOutfit(Dataset):
'''
4DHumanOutfit dataset - loading only tight clothing type.
'''
def __init__(self,
dataset_path: str,
parameters_path: str,
sequence_list: List[str] = None,
clothing_type: str = "tig",
pelvis_normalization: bool = False,
use_landmarks: str = "SMPL_INDEX_LANDAMRKS_REVISED",
transferred_landmarks_name: str = "simple",
body_models_path: str = "data/body_models",
**kwargs):
"""
:param dataset_path: (str) path to 4DHumanOutfit scans
:param parameters_path: (str) path to the directory where the already
fitted SMPL parameters are stored
:param sequence_list: (List[str]) list of sequences to load.
If "All", all sequences are loaded
:param clothing_type: (str) type of clothing to load
:param pelvis_normalization: (bool) whether to normalize landmarks to pelvis
:param use_landmarks: (str) landmarks defined on the SMPL model from utils.py
:param transferred_landmarks_name: (str) name of the transferred landmarks
provided by the dataset
-> simple, nn or nn_threshold
:param body_models_path: (str) path to the SMPL body models
"""
all_male_subjects = ["ben","bob","jon","leo","mat","pat","ray","ted","tom"]
all_female_subjects = ["ada","bea","deb","gia","joy","kim","mia","sue","zoe"]
all_subjects_names = all_male_subjects + all_female_subjects
# create gender mapper
all_genders = ["male"] * len(all_male_subjects) + ["female"] * len(all_female_subjects)
self.gender_mapper = dict(zip(all_subjects_names,all_genders))
self.load_scans = True if not isinstance(dataset_path, type(None)) else False
if not isinstance(sequence_list, type(None)):
use_subjects = [seq.split("-")[0] for seq in sequence_list]
else:
use_subjects = all_subjects_names
self.scan_paths = []
self.subject_names = []
self.action_names = []
self.sequence_names = []
self.poses = []
self.shapes = []
self.trans = []
self.genders = []
self.landmarks = []
for subj_name in all_subjects_names:
if subj_name in use_subjects:
all_subj_action_paths = glob(os.path.join(parameters_path,subj_name,f"{subj_name}-{clothing_type}-*"))
for subj_action_path in all_subj_action_paths:
action_name = os.path.basename(subj_action_path).split("-")[-1]
sequence_name = f"{subj_name}-{clothing_type}-{action_name}"
if not isinstance(sequence_list, type(None)):
if sequence_name not in sequence_list:
continue
all_seq_poses = torch.load(os.path.join(subj_action_path,"poses.pt"),
map_location=torch.device("cpu")).detach().cpu()
all_seq_shapes = torch.load(os.path.join(subj_action_path,"betas.pt"),
map_location=torch.device("cpu")).detach().cpu()
all_seq_trans = torch.load(os.path.join(subj_action_path,"trans.pt"),
map_location=torch.device("cpu")).detach().cpu()
all_seq_gender = self.gender_mapper[subj_name]
all_seq_landmarks_paths = torch.load(os.path.join(subj_action_path,f"landmarks_{transferred_landmarks_name}.pt"),
map_location=torch.device("cpu"))
N_frames = all_seq_poses.shape[0]
if self.load_scans:
all_seq_scan_paths = sorted(glob(os.path.join(dataset_path,subj_name,sequence_name,"*/*.obj")))
else:
all_seq_scan_paths = [f"{i}.obj" for i in range(N_frames)] # NOTE: just placeholders
for frame_ind in range(N_frames):
self.scan_paths.append(all_seq_scan_paths[frame_ind])
self.subject_names.append(subj_name)
self.action_names.append(action_name)
self.sequence_names.append(sequence_name)
self.poses.append(all_seq_poses[frame_ind])#.unsqueeze(0).detach().cpu())
self.shapes.append(all_seq_shapes[frame_ind])#.unsqueeze(0).detach().cpu())
self.trans.append(all_seq_trans[frame_ind])#.unsqueeze(0).detach().cpu())
self.genders.append(all_seq_gender)
self.landmarks.append(all_seq_landmarks_paths[frame_ind])#.unsqueeze(0).detach().cpu())
self.dataset_size = len(self.poses)
# pelvis normalization
self.pelvis_normalization = pelvis_normalization
landmarks_dict = getattr(utils, use_landmarks.upper(), None)
self.landmark_names = list(landmarks_dict.keys())
self.rt_psis_ind = self.landmark_names.index("Rt. PSIS")
self.lt_psis_ind = self.landmark_names.index("Lt. PSIS")
self.rt_asis_ind = self.landmark_names.index("Rt. ASIS")
self.lt_asis_ind = self.landmark_names.index("Lt. ASIS")
self.nuchale_ind = self.landmark_names.index("Nuchale")
# create body models
self.bms = {
"MALE": create_body_model(body_models_path,
"smpl",
"MALE",
8),
"FEMALE": create_body_model(body_models_path,
"smpl",
"FEMALE",
8),
"NEUTRAL": create_body_model(body_models_path,
"smpl",
"NEUTRAL",
8),
}
def __getitem__(self, index):
"""
:return (dict): dictionary with keys:
"""
# load scan
scan_path = self.scan_paths[index]
sequence_name = self.sequence_names[index] #scan_path.split("/")[-2]
scan_name = os.path.basename(scan_path).split(".obj")[0]
if self.load_scans:
scan = o3d.io.read_triangle_mesh(scan_path)
scan_vertices = torch.from_numpy(np.asarray(scan.vertices))
scan_faces = torch.from_numpy(np.asarray(scan.triangles))
scan_faces = scan_faces if scan_faces.shape[0] > 0 else None
else:
scan_vertices = None
scan_faces = None
scan_landmarks = self.landmarks[index]
scan_gender = self.genders[index].upper()
# create fitting
fit_pose = self.poses[index].unsqueeze(0)
fit_shape = self.shapes[index].unsqueeze(0)
fit_trans = self.trans[index].unsqueeze(0)
fit = self.bms[scan_gender](body_pose=fit_pose[:,3:],
betas=fit_shape,
global_orient=fit_pose[:,:3],
transl=fit_trans,
pose2rot=True).vertices[0].detach().cpu()
# fit = fit + fit_trans
# normalize
if self.pelvis_normalization:
scan_landmarks, centroid, R2y, R2z = pelvis_normalization(scan_landmarks,
self.rt_psis_ind,
self.lt_psis_ind,
self.rt_asis_ind,
self.lt_asis_ind,
self.nuchale_ind,
return_transformations=True)
if self.load_scans:
scan_vertices = scan_vertices - centroid
scan_vertices = torch.matmul(scan_vertices.float(), R2y.T) # K x 3
scan_vertices = torch.matmul(scan_vertices, R2z.T)
fit = fit - centroid
fit = torch.matmul(fit.float(), R2y.T) # K x 3
fit = torch.matmul(fit, R2z.T)
return {"name": f"{sequence_name}-{scan_name}",
"sequence_name": sequence_name,
"vertices": scan_vertices,
"faces": scan_faces,
"landmarks": scan_landmarks,
"pose": self.poses[index],
"shape": self.shapes[index],
"trans": self.trans[index],
"gender": self.genders[index],
"fit":fit}
def __len__(self):
return self.dataset_size
class NPZDataset(Dataset):
def __init__(self,
dataset_path: str,
what_to_return: List[str] =["landmarks","measurements"],
**kwargs
):
"""
Dataset defined with a .npz file or folder with .npz files
The .npz files are data points of subjects with landmarks and measurements
:param dataset_path: (str) path to the .npz file or folder with .npz files
:param what_to_return: (List[str]) list of keys to return from the .npz
"""
if dataset_path.endswith(".npz"):
self.data_orig = np.load(dataset_path)
self.data = {name: (torch.from_numpy(self.data_orig[name])
if self.data_orig[name].dtype.type not in [np.str_] else self.data_orig[name])
for name in self.data_orig.keys()
}
# if path is a flder with .npz files
else:
all_files = sorted(glob(os.path.join(dataset_path,"*.npz")))
first_example = np.load(all_files[0])
self.data = {name : [] for name in first_example.keys()}
# self.possible_returns = list(first_example.keys())
for fl in all_files:
d = np.load(fl)
for name in d.keys():
self.data[name].append(d[name])
for name in self.data.keys():
if np.array(self.data[name]).dtype.type not in [np.str_]:
if name not in ["indices_verts","indices_lm"]:
self.data[name] = torch.from_numpy(np.array(self.data[name]))
else:
self.data[name] = np.array(self.data[name])
else:
self.data[name] = self.data[name]
self.possible_returns = list(self.data.keys())
self.what_to_return = what_to_return
if "use_measurements" in kwargs:
self.use_measurements = kwargs["use_measurements"]
def __len__(self):
if "landmarks" in self.data:
return self.data["landmarks"].shape[0]
elif "markers" in self.data:
return self.data["markers"].shape[0]
def __getitem__(self, index):
return {name: self.data[name][index]
for name in self.what_to_return
if name in self.possible_returns}
class NPZDatasetTrainRobustness(Dataset):
def __init__(self,
dataset_path: str,
what_to_return: List[str] =["landmarks","measurements"],
pelvis_normalization: bool = True,
augmentation_landmark_2_origin_prob: float = 0,
use_landmarks: str = "SMPL_INDEX_LANDAMRKS_REVISED",
use_preprocessed_partial_landmarks: bool = False,
**kwargs
):
"""
Extension of the NPZ dataset that allows for augmentation of the landmarks
:param dataset_path: (str) path to the .npz file or folder with .npz files
:param what_to_return: (List[str]) list of keys to return from the .npz
:param pelvis_normalization: (bool) whether to normalize landmarks to pelvis
:param augmentation_landmark_2_origin_prob: (float) probability of moving a random landmark to the origin
:param use_landmarks: (str) landmarks defined on the SMPL model from utils.py
:param use_preprocessed_partial_landmarks: (bool) whether to use preprocessed partial landmarks instead of
randomly moving landmarks to the origin
"""
if dataset_path.endswith(".npz"):
self.data = np.load(dataset_path)
self.data = {name: (torch.from_numpy(self.data[name])
if self.data[name].dtype.type not in [np.str_] else self.data[name])
for name in self.data.keys()}
else:
all_files = sorted(glob(os.path.join(dataset_path,"*.npz")))
first_example = np.load(all_files[0])
self.data = {name : [] for name in first_example.keys()}
self.data["names"] = []
for fl in all_files:
self.data["names"].append(fl.split("/")[-1].split(".npz")[0])
d = np.load(fl)
for name in d.keys():
self.data[name].append(d[name])
for name in self.data.keys():
if np.array(self.data[name]).dtype.type not in [np.str_]:
if name not in ["indices_verts","indices_lm", "names"]:
self.data[name] = torch.from_numpy(np.array(self.data[name]))
else:
self.data[name] = np.array(self.data[name])
else:
self.data[name] = self.data[name]
self.possible_returns = list(self.data.keys())
self.what_to_return = what_to_return
# augmentation to partial landmarks
self.augmentation_landmark_2_origin_prob = augmentation_landmark_2_origin_prob
self.use_preprocessed_partial_landmarks = use_preprocessed_partial_landmarks
self.save_augmentation = False
if "save_path" in kwargs:
self.save_augmentation = True
self.augmentation_tracker_path = os.path.join(kwargs["save_path"],
"augmentation_tracker.txt")
# pelvis normalization
self.pelvis_normalization = pelvis_normalization
landmarks_dict = getattr(utils, use_landmarks.upper(), None)
self.landmark_names = list(landmarks_dict.keys())
self.rt_psis_ind = self.landmark_names.index("Rt. PSIS")
self.lt_psis_ind = self.landmark_names.index("Lt. PSIS")
self.rt_asis_ind = self.landmark_names.index("Rt. ASIS")
self.lt_asis_ind = self.landmark_names.index("Lt. ASIS")
self.nuchale_ind = self.landmark_names.index("Nuchale")
if "use_measurements" in kwargs:
self.use_measurements = kwargs["use_measurements"]
def __len__(self):
return self.data["landmarks"].shape[0]
def __getitem__(self, index):
current_data = {name: self.data[name][index]
for name in self.what_to_return
if name in self.possible_returns}
lm = current_data["landmarks"].clone()
# move random LM to origin
if self.augmentation_landmark_2_origin_prob > 0:
if np.random.choice([0,1],p=[0.5,0.5]):
augment_lms = np.random.choice([0,1],
size=lm.shape[0],
p=[1-self.augmentation_landmark_2_origin_prob,
self.augmentation_landmark_2_origin_prob])
# NOTE: HARDCODED WAY FOR NEVER REMOVING NORMALIZATION LANDMARKS
augment_lms[[self.rt_psis_ind,
self.lt_psis_ind,
self.rt_asis_ind,
self.lt_asis_ind,
self.nuchale_ind]] = 0
N_lm_to_origin = np.sum(augment_lms)
# self.augmentation_tracker.append(N_lm_to_origin)
if self.save_augmentation:
with open(self.augmentation_tracker_path, "a") as f:
f.write(f"{N_lm_to_origin}\n")
augment_lms = torch.from_numpy(augment_lms) == 1
lm[augment_lms] = torch.zeros((N_lm_to_origin,3),
dtype=lm.dtype)
if self.use_preprocessed_partial_landmarks:
if np.random.choice([0,1],p=[0.5,0.5]):
# NOTE: Hardcoded to always use pelvis landmarks
current_data["indices_lm"][self.rt_psis_ind] = 1
current_data["indices_lm"][self.lt_psis_ind] = 1
current_data["indices_lm"][self.rt_asis_ind] = 1
current_data["indices_lm"][self.lt_asis_ind] = 1
current_data["indices_lm"][self.nuchale_ind] = 1
partial_inds = current_data["indices_lm"]
lm = lm[partial_inds]
# normalize
if self.pelvis_normalization:
lm, centroid, R2y, R2z = pelvis_normalization(lm,
self.rt_psis_ind,
self.lt_psis_ind,
self.rt_asis_ind,
self.lt_asis_ind,
self.nuchale_ind,
return_transformations=True)
current_data["landmarks"] = lm
current_data["name"] = self.data["names"][index]
return current_data
class CAESAR(Dataset):
'''
CAESAR dataset
z-ax is the height
returning vertices and landmarks in m and measurements in mm!
'''
def __init__(self, cfg: dict):
"""
cfg: config dictionary with
:param data_dir (str): path to caesar dataset
:param load_countries (str or list): countries to load. If "All", all countries are loaded
:param use_landmarks (str or list): landmarks to use. If "All", all landmarks are loaded,
if list of landmark names, only those are loaded
:param load_measurements (bool): whether to load measurements or not
"""
data_dir = cfg["data_dir"]
load_countries = cfg["load_countries"]
self.landmark_subset = cfg.get("use_landmarks",None)
self.load_measurements = cfg.get("load_measurements",None)
self.load_only_standing_pose = cfg.get("load_only_standing_pose",False)
self.load_only_sitting_pose = cfg.get("load_only_sitting_pose",False)
# set loading countries
all_countries = ["Italy","The Netherlands","North America"]
if load_countries == "All":
load_countries = all_countries
for country in load_countries:
if country not in all_countries:
msg = f"Country {country} not found. Available countries are: {all_countries}"
raise ValueError(msg)
# set paths
scans_and_landmark_dir = os.path.join(data_dir, "Data AE2000")
scans_and_landmark_paths = {
"Italy": os.path.join(scans_and_landmark_dir, "Italy","PLY and LND Italy"),
"The Netherlands": os.path.join(scans_and_landmark_dir, "The Netherlands","PLY and LND TN"),
"North America": os.path.join(scans_and_landmark_dir, "North America","PLY and LND NA")
}
self.scans_and_landmark_paths = scans_and_landmark_paths
if self.load_measurements:
measurements_path = os.path.join(data_dir,
"processed_data",
"measurements.csv")
self.measurements = pd.read_csv(measurements_path)
measurements_extr_seat_path = os.path.join(data_dir,
"processed_data",
"measurements_extracted_seated.csv")
self.meas_extr_seated = pd.read_csv(measurements_extr_seat_path)
measurements_extr_stand_path = os.path.join(data_dir,
"processed_data",
"measurements_extracted_standing.csv")
self.meas_extr_stand = pd.read_csv(measurements_extr_stand_path)
demographics_path = os.path.join(data_dir,
"processed_data",
"demographics.csv")
self.demographics = pd.read_csv(demographics_path)
self.scan_paths = []
self.landmark_paths = []
self.countries = []
for country, path in scans_and_landmark_paths.items():
for scan_path in glob(f"{path}/*.ply.gz"):
scan_pose = scan_path.split("/")[-1].split(".ply.gz")[0][-1]
if self.load_only_standing_pose:
if scan_pose != "a":
continue
if self.load_only_sitting_pose:
if scan_pose != "b":
continue
# set scan path
self.scan_paths.append(scan_path)
# set landmark path
landmark_path = scan_path.replace(".ply.gz", ".lnd")
if os.path.exists(landmark_path):
self.landmark_paths.append(landmark_path)
else:
self.landmark_paths.append(None)
# set country
self.countries.append(country)
self.dataset_size = len(self.scan_paths)
self.LANDMARK_SCALE = 1000 # landmark coordinates are in mm, we want them in m
self.country_scales = {"Italy": 1, "The Netherlands": 1000, "North America": 1} # scale to convert from mm to m
def __getitem__(self, index):
"""
:return (dict): dictionary with keys:
"name": name of scan
"vertices": (N,3) np.array
"faces": (N,3) np.array or None if no faces
"landmarks": dict with landmark names as keys and landmark coords as values
landmark coords are (1,3) np.array or None if no landmarks
"country": string
"""
# load country
scan_country = self.countries[index]
scan_scale = self.country_scales[scan_country]
# load scan
scan_path = self.scan_paths[index]
scan_name = os.path.basename(scan_path).split(".ply.gz")[0]
scan_number = int(scan_name[-5:-1])
with gzip.open(scan_path, 'rb') as gz_file:
try:
ply_content = gz_file.read()
except Exception as _:
return {"name": scan_name,
"vertices": None,
"faces": None,
"landmarks": None,
"country": None,
}
# TRIMESH APPROACH THAT WORKS
# ply_fileobj = io.BytesIO(ply_content)
# scan = trimesh.load_mesh(file_obj=ply_fileobj, file_type='ply')
# scan_vertices = scan.vertices
# scan_faces = scan.faces
# OPEN3D APPROACH
# complicated way to save ply to disk and load again -.-
temp_ply_path = tempfile.mktemp(suffix=".ply")
with open(temp_ply_path, 'wb') as temp_ply_file:
temp_ply_file.write(ply_content)
scan = o3d.io.read_triangle_mesh(temp_ply_path)
# scan_center = scan.get_center()
scan_vertices = np.asarray(scan.vertices) / scan_scale
scan_faces = np.asarray(scan.triangles)
scan_faces = scan_faces if scan_faces.shape[0] > 0 else None
os.remove(temp_ply_path)
# load landmarks
landmark_path = self.landmark_paths[index]
if landmark_path is not None:
landmarks = process_caesar_landmarks(landmark_path,
self.LANDMARK_SCALE)
if isinstance(self.landmark_subset, list):
landmarks = {lm_name: landmarks[lm_name]
for lm_name in self.landmark_subset
if lm_name in landmarks.keys()}
else:
landmarks = None
# load measurements
if self.load_measurements:
measurements = self.measurements.loc[
(self.measurements["Country"] == scan_country) &
(self.measurements["Subject Number"] == scan_number)
].to_dict("records")
measurements = None if measurements == [] else measurements[0]
measurements_seat = self.meas_extr_seated.loc[
(self.meas_extr_seated["Country"] == scan_country) &
(self.meas_extr_seated["Subject Number"] == scan_number)
].to_dict("records")
measurements_seat = None if measurements_seat == [] else measurements_seat[0]
measurements_stand = self.meas_extr_stand.loc[
(self.meas_extr_stand["Country"] == scan_country) &
(self.meas_extr_stand["Subject Number"] == scan_number)
].to_dict("records")
measurements_stand = None if measurements_stand == [] else measurements_stand[0]
demographics = self.demographics.loc[
(self.demographics["Country"] == scan_country) &
(self.demographics["Subject Number"] == scan_number)
].to_dict("records")
demographics = None if demographics == [] else demographics[0]
else:
measurements = None
measurements_seat = None
measurements_stand = None
demographics = None
return {"name": scan_name,
"vertices": scan_vertices,
"faces": scan_faces,
"landmarks": landmarks,
"country": self.countries[index],
"measurements": measurements,
"measurements_seat": measurements_seat,
"measurements_stand": measurements_stand,
"demographics": demographics
}
def __len__(self):
return self.dataset_size
class OnTheFlyCAESAR(Dataset):
'''
reposed CAESAR dataset
y-ax is the height
vertices, landmarks, markers and measurements are returned in cm
The idea is that for each pose from a SMPL pose dataset
choose a random CAESAR subject and repose them into that pose
with a certain probability.
'''
def __init__(self,
caesar_dir,
fitted_bm_dir=None,
fitted_nrd_dir=None,
poses_path=None,
n_poses=None,
dont_pose=False,
iterate_over_poses=True,
load_countries="All",
pose_params_from='all',
body_model_name="smpl",
body_models_path="data/body_models",
body_model_num_shape_param=10,
use_measurements=None,
use_subjects=None,
iterate_over_subjects=False,
use_landmarks="SMPL_INDEX_LANDMARKS",
landmark_normalization="pelvis",
what_to_return=["landmarks","measurements"],
augmentation_landmark_jitter_std=0,
augmentation_landmark_2_origin_prob=0,
augmentation_unpose_prob=0,
augmentation_repose_prob=0,
preprocessed_path=None,
subsample_verts=None,
use_moyo_poses=False,
moyo_poses_path=None,
single_fixed_pose_ind=None,
fix_dataset=None,
remove_monster_poses_threshold=None,
pose_prior_path="data/prior",
mocap_marker_path="/data/wear3d_preprocessed/mocap/simple+nn/standard/from_2023_10_18_23_32_22",
use_transferred_lm_path=None,
unposing_landmarks_choice="nn_to_verts", # "nn_to_smpl"
**kwargs
):
"""
:param caesar_dir: (str) path to caesar dataset
:param fitted_bm_dir: (str) path to SMPL param fits to CAESAR dataset
:param fitted_nrd_dir: (str) path to SMPL vertex fits to CAESAR dataset
:param poses_path: (str) SMPL poses dataset to use
:param n_poses: (int) number of poses to use from the poses dataset
:param dont_pose: (bool) whether to use the poses or not
:param iterate_over_poses: (bool) whether to iterate over poses or subjects
-> if iterating over subjects the poses can be omitted or used
:param load_countries: (str or list) countries to load from CAESAR. If "All", all countries are loaded
:param pose_params_from: (str) which pose parameters to use from the SMPL poses dataset
:param body_model_name: (str) name of the body model to use (smpl only)
:param body_models_path: (str) path to the body models
:param body_model_num_shape_param: (int) number of shape parameters of the body model
:param use_measurements: (List[str]) measurements to load
:param use_subjects: (str or List[str]) subjects to use from the CAESAR dataset
-> path to a .txt file with subjects to use
or list of subjects
:param use_landmarks: (str) landmarks defined on the SMPL model from utils.py
:param landmark_normalization: (str) normalization method for landmarks
:param what_to_return: (List[str]) what to return from the dataset
:param augmentation_landmark_jitter_std: (float) std of the landmark jitter
:param augmentation_landmark_2_origin_prob: (float) probability of moving a random landmark to the origin
:param augmentation_unpose_prob: (float) probability of unposing the subject
:param augmentation_repose_prob: (float) probability of reposing the subject
:param preprocessed_path: (str) path to preprocessed data used for unposing and reposing (not necessary)
:param subsample_verts: (int) number of vertices to subsample to
:param use_moyo_poses: (bool) whether to use MOYO poses
:param moyo_poses_path: (str) path to MOYO poses
:param single_fixed_pose_ind: (int) index if you want to use a single pose for the whole dataset
:param fix_dataset: (str) fix a set of subjects to use from the start instead of randomly sampling in each iteration
:param remove_monster_poses_threshold: (int) threshold for removing poses that are not plausible
:param pose_prior_path: (str) path to the pose prior from SMPLify
:param mocap_marker_path: (str) path to the mocap markers for the CAESAR dataset
:param use_transferred_lm_path: (str) path to the transferred landmarks
:param unposing_landmarks_choice: (str) choice of how to unpose the landmarks
-> currently only "nn_to_verts"
"""
self.caesar_dir = caesar_dir
self.fitted_bm_dir = fitted_bm_dir
self.fitted_nrd_dir = fitted_nrd_dir
self.poses_path = poses_path
self.n_poses = n_poses
self.dont_pose = dont_pose
self.load_countries = load_countries
self.pose_params_from = pose_params_from
self.body_model_name = body_model_name
self.body_models_path = body_models_path
self.body_model_num_shape_param = body_model_num_shape_param
self.use_measurements = use_measurements
self.use_subjects = use_subjects
self.use_landmarks = use_landmarks
self.landmark_normalization = landmark_normalization
self.what_to_return = what_to_return
self.augmentation_landmark_jitter_std = augmentation_landmark_jitter_std
self.augmentation_landmark_2_origin_prob = augmentation_landmark_2_origin_prob
self.augmentation_unpose_prob = augmentation_unpose_prob
self.augmentation_dont_unpose_prob = 1 - augmentation_unpose_prob
self.augmentation_repose_prob = augmentation_repose_prob
self.augmentation_dont_repose_prob = 1 - augmentation_repose_prob
self.preprocessed_path = preprocessed_path
self.use_preprocessed_data = True if not isinstance(preprocessed_path, type(None)) else False
# NOTE: if subsampling verts, the faces wont correspond anymore!
self.subsample_verts = 1 if isinstance(subsample_verts, type(None)) else subsample_verts
self.use_moyo_poses = use_moyo_poses
self.moyo_poses_path = moyo_poses_path
self.remove_monster_poses_threshold = remove_monster_poses_threshold
self.pose_prior_path = pose_prior_path
self.use_transferred_lm_path = use_transferred_lm_path
self.unposing_lm_choice = unposing_landmarks_choice
self.iterate_over_subjects = iterate_over_subjects
self.single_fixed_pose_ind = single_fixed_pose_ind
self.iterate_over_poses = iterate_over_poses
self.fix_dataset = fix_dataset
if self.iterate_over_subjects and self.iterate_over_poses:
raise ValueError("Cannot iterate over subjects AND over poses \
- choose one bruv")
# set CAESAR subjects to use
if isinstance(self.use_subjects,str):
with open(self.use_subjects, "r") as f:
self.subjects_subset = f.read().splitlines()
elif isinstance(self.use_subjects,list):
self.subjects_subset = self.use_subjects
else:
self.subjects_subset = None
# set CAESAR countries to load
all_countries = ["Italy","The Netherlands","North America"]
if load_countries == "All":
load_countries = all_countries
assert all([(country in all_countries) for country in load_countries]), \
f"Available countries are: {all_countries}"
# set paths
scans_and_landmark_dir = os.path.join(caesar_dir, "Data AE2000")
scans_and_landmark_paths = {
"Italy": os.path.join(scans_and_landmark_dir, "Italy","PLY and LND Italy"),
"The Netherlands": os.path.join(scans_and_landmark_dir, "The Netherlands","PLY and LND TN"),
"North America": os.path.join(scans_and_landmark_dir, "North America","PLY and LND NA")
}
scans_and_landmark_paths = {country:path for country, path in scans_and_landmark_paths.items() if country in load_countries}
self.scans_and_landmark_paths = scans_and_landmark_paths
# load measurements
if "measurements" in self.what_to_return:
assert self.use_measurements is not None, "use_measurements must be set if measurements are returned"
measurements_path = os.path.join(caesar_dir,
"processed_data",
"measurements.csv")
self.measurements = pd.read_csv(measurements_path)
measurements_extr_seat_path = os.path.join(caesar_dir,
"processed_data",
"measurements_extracted_seated.csv")
self.meas_extr_seated = pd.read_csv(measurements_extr_seat_path)
measurements_extr_stand_path = os.path.join(caesar_dir,
"processed_data",
"measurements_extracted_standing.csv")
self.meas_extr_stand = pd.read_csv(measurements_extr_stand_path)
demographics_path = os.path.join(caesar_dir,
"processed_data",
"demographics.csv")
self.demographics = pd.read_csv(demographics_path)
# gather paths for each subject
self.scan_paths = []
self.fitted_bm_paths = []
self.fitted_nrd_paths = []
self.landmark_paths = []
self.countries = []
self.scan_marker_paths = []
for country, path in scans_and_landmark_paths.items():
for scan_path in glob(f"{path}/*.ply.gz"):
scan_name_with_extension = scan_path.split("/")[-1]
# scan_pose = scan_name_with_extension.split(".ply.gz")[0][-1]
scan_name = scan_name_with_extension.split(".ply.gz")[0]
if not isinstance(self.subjects_subset,type(None)):
if scan_name not in self.subjects_subset:
continue
# set fitted bm path
if self.dont_pose:
pass
else:
bm_path = os.path.join(self.fitted_bm_dir, f"{scan_name}.npz")
if not os.path.exists(bm_path):
continue
nrd_path = os.path.join(self.fitted_nrd_dir, f"{scan_name}.npz")
if not os.path.exists(nrd_path):
continue
self.fitted_bm_paths.append(bm_path)
self.fitted_nrd_paths.append(nrd_path)
# set scan path
self.scan_paths.append(scan_path)
# set landmark path
if isinstance(self.use_transferred_lm_path,type(None)):
landmark_path = scan_path.replace(".ply.gz", ".lnd")
else:
landmark_path = os.path.join(use_transferred_lm_path, f"{scan_name}_landmarks.json")
if os.path.exists(landmark_path):
self.landmark_paths.append(landmark_path)
else:
self.landmark_paths.append(None)
# set country
self.countries.append(country)
# markers
if not isinstance(mocap_marker_path, type(None)):
marker_path = os.path.join(mocap_marker_path, f"{scan_name}_markers.npy")
self.scan_marker_paths.append(marker_path)
# set scaling
self.N_scans = len(self.scan_paths)
# scale everyhing to m - unpose and unscale works on m (divide by this scale)
self.LANDMARK_SCALE_M = 1000 # landmark coordinates from mm to m
self.country_scales_m = {"Italy": 1, "The Netherlands": 1000, "North America": 1} # scale to convert from mm to m
# after unposing and scaling, scale everyhing to cm (multiply with this scale)
self.LANDMARK_SCALE_CM = 100 # landmark coordinates from m to cm
self.SCAN_SCALE_CM = 100 # scan vertices from m to cm