carsten12 commited on
Commit
c306ff4
·
verified ·
1 Parent(s): 5143ae5

Delete measure.py

Browse files
Files changed (1) hide show
  1. measure.py +0 -502
measure.py DELETED
@@ -1,502 +0,0 @@
1
-
2
- from typing import List, Dict
3
- import numpy as np
4
- import trimesh
5
- import torch
6
- import smplx
7
- from pprint import pprint
8
- import os
9
- import argparse
10
-
11
- from measurement_definitions import *
12
- from utils import *
13
- from visualize import Visualizer
14
- from landmark_definitions import *
15
- from joint_definitions import *
16
-
17
-
18
-
19
- def set_shape(model, shape_coefs):
20
- '''
21
- Set shape of body model.
22
- :param model: smplx body model
23
- :param shape_coefs: torch.tensor dim (10,)
24
-
25
- Return
26
- shaped smplx body model
27
- '''
28
- shape_coefs = shape_coefs.to(torch.float32)
29
- return model(betas=shape_coefs, return_verts=True)
30
-
31
- def create_model(model_type, model_root, gender, num_betas=10, num_thetas=24):
32
- '''
33
- Create SMPL/SMPLX/etc. body model
34
- :param model_type: str of model type: smpl, smplx, etc.
35
- :param model_root: str of location where there are smpl/smplx/etc. folders with .pkl models
36
- (clumsy definition in smplx package)
37
- :param gender: str of gender: MALE or FEMALE or NEUTRAL
38
- :param num_betas: int of number of shape coefficients
39
- requires the model with num_coefs in model_root
40
- :param num_thetas: int of number of pose coefficients
41
-
42
- Return:
43
- :param smplx body model (SMPL, SMPLX, etc.)
44
- '''
45
-
46
- #body_pose = torch.zeros((1, (num_thetas-1) * 3))
47
-
48
- return smplx.create(model_path=model_root,
49
- model_type=model_type,
50
- gender=gender,
51
- use_face_contour=False,
52
- num_betas=num_betas,
53
- #body_pose=body_pose,
54
- ext='pkl')
55
-
56
-
57
-
58
- class Measurer():
59
- '''
60
- Measure a parametric body model defined either.
61
- Parent class for Measure{SMPL,SMPLX,..}.
62
-
63
- All the measurements are expressed in cm.
64
- '''
65
-
66
- def __init__(self):
67
- self.verts = None
68
- self.faces = None
69
- self.joints = None
70
- self.gender = None
71
-
72
- self.measurements = {}
73
- self.height_normalized_measurements = {}
74
- self.labeled_measurements = {}
75
- self.height_normalized_labeled_measurements = {}
76
- self.labels2names = {}
77
-
78
- def from_verts(self):
79
- pass
80
-
81
- def from_body_model(self):
82
- pass
83
-
84
- def measure(self,
85
- measurement_names: List[str]
86
- ):
87
- '''
88
- Measure the given measurement names from measurement_names list
89
- :param measurement_names - list of strings of defined measurements
90
- to measure from MeasurementDefinitions class
91
- '''
92
-
93
- for m_name in measurement_names:
94
- if m_name not in self.all_possible_measurements:
95
- print(f"Measurement {m_name} not defined.")
96
- pass
97
-
98
- if m_name in self.measurements:
99
- pass
100
-
101
- if self.measurement_types[m_name] == MeasurementType().LENGTH:
102
-
103
- value = self.measure_length(m_name)
104
- self.measurements[m_name] = value
105
-
106
- elif self.measurement_types[m_name] == MeasurementType().CIRCUMFERENCE:
107
-
108
- value = self.measure_circumference(m_name)
109
- self.measurements[m_name] = value
110
-
111
- else:
112
- print(f"Measurement {m_name} not defined")
113
-
114
- def measure_length(self, measurement_name: str):
115
- '''
116
- Measure distance between 2 landmarks
117
- :param measurement_name: str - defined in MeasurementDefinitions
118
-
119
- Returns
120
- :float of measurement in cm
121
- '''
122
-
123
- measurement_landmarks_inds = self.length_definitions[measurement_name]
124
-
125
- landmark_points = []
126
- for i in range(2):
127
- if isinstance(measurement_landmarks_inds[i],tuple):
128
- # if touple of indices for landmark, take their average
129
- lm = (self.verts[measurement_landmarks_inds[i][0]] +
130
- self.verts[measurement_landmarks_inds[i][1]]) / 2
131
- else:
132
- lm = self.verts[measurement_landmarks_inds[i]]
133
-
134
- landmark_points.append(lm)
135
-
136
- landmark_points = np.vstack(landmark_points)[None,...]
137
-
138
- return self._get_dist(landmark_points)
139
-
140
- @staticmethod
141
- def _get_dist(verts: np.ndarray) -> float:
142
- '''
143
- The Euclidean distance between vertices.
144
- The distance is found as the sum of each pair i
145
- of 3D vertices (i,0,:) and (i,1,:)
146
- :param verts: np.ndarray (N,2,3) - vertices used
147
- to find distances
148
-
149
- Returns:
150
- :param dist: float, sumed distances between vertices
151
- '''
152
-
153
- verts_distances = np.linalg.norm(verts[:, 1] - verts[:, 0],axis=1)
154
- distance = np.sum(verts_distances)
155
- distance_cm = distance * 100 # convert to cm
156
- return distance_cm
157
-
158
- def measure_circumference(self,
159
- measurement_name: str,
160
- ):
161
- '''
162
- Measure circumferences. Circumferences are defined with
163
- landmarks and joints - the measurement is found by cutting the
164
- SMPL model with the plane defined by a point (landmark point) and
165
- normal (vector connecting the two joints).
166
- :param measurement_name: str - measurement name
167
-
168
- Return
169
- float of measurement value in cm
170
- '''
171
-
172
- measurement_definition = self.circumf_definitions[measurement_name]
173
- circumf_landmarks = measurement_definition["LANDMARKS"]
174
- circumf_landmark_indices = [self.landmarks[l_name] for l_name in circumf_landmarks]
175
- circumf_n1, circumf_n2 = self.circumf_definitions[measurement_name]["JOINTS"]
176
- circumf_n1, circumf_n2 = self.joint2ind[circumf_n1], self.joint2ind[circumf_n2]
177
-
178
- plane_origin = np.mean(self.verts[circumf_landmark_indices,:],axis=0)
179
- plane_normal = self.joints[circumf_n1,:] - self.joints[circumf_n2,:]
180
-
181
- mesh = trimesh.Trimesh(vertices=self.verts, faces=self.faces)
182
-
183
- # new version
184
- slice_segments, sliced_faces = trimesh.intersections.mesh_plane(mesh,
185
- plane_normal=plane_normal,
186
- plane_origin=plane_origin,
187
- return_faces=True) # (N, 2, 3), (N,)
188
-
189
- slice_segments = filter_body_part_slices(slice_segments,
190
- sliced_faces,
191
- measurement_name,
192
- self.circumf_2_bodypart,
193
- self.face_segmentation)
194
-
195
- slice_segments_hull = convex_hull_from_3D_points(slice_segments)
196
-
197
- return self._get_dist(slice_segments_hull)
198
-
199
- def height_normalize_measurements(self, new_height: float):
200
- '''
201
- Scale all measurements so that the height measurement gets
202
- the value of new_height:
203
- new_measurement = (old_measurement / old_height) * new_height
204
- NOTE the measurements and body model remain unchanged, a new
205
- dictionary height_normalized_measurements is created.
206
-
207
- Input:
208
- :param new_height: float, the newly defined height.
209
-
210
- Return:
211
- self.height_normalized_measurements: dict of
212
- {measurement:value} pairs with
213
- height measurement = new_height, and other measurements
214
- scaled accordingly
215
- '''
216
- if self.measurements != {}:
217
- old_height = self.measurements["height"]
218
- for m_name, m_value in self.measurements.items():
219
- norm_value = (m_value / old_height) * new_height
220
- self.height_normalized_measurements[m_name] = norm_value
221
-
222
- if self.labeled_measurements != {}:
223
- for m_name, m_value in self.labeled_measurements.items():
224
- norm_value = (m_value / old_height) * new_height
225
- self.height_normalized_labeled_measurements[m_name] = norm_value
226
-
227
- def label_measurements(self,set_measurement_labels: Dict[str, str]):
228
- '''
229
- Create labeled_measurements dictionary with "label: x cm" structure
230
- for each given measurement.
231
- NOTE: This overwrites any prior labeling!
232
-
233
- :param set_measurement_labels: dict of labels and measurement names
234
- (example. {"A": "head_circumference"})
235
- '''
236
-
237
- if self.labeled_measurements != {}:
238
- print("Overwriting old labels")
239
-
240
- self.labeled_measurements = {}
241
- self.labels2names = {}
242
-
243
- for set_label, set_name in set_measurement_labels.items():
244
-
245
- if set_name not in self.all_possible_measurements:
246
- print(f"Measurement {set_name} not defined.")
247
- pass
248
-
249
- if set_name not in self.measurements.keys():
250
- self.measure([set_name])
251
-
252
- self.labeled_measurements[set_label] = self.measurements[set_name]
253
- self.labels2names[set_label] = set_name
254
-
255
- def visualize(self,
256
- measurement_names: List[str] = [],
257
- landmark_names: List[str] = [],
258
- title="Measurement visualization",
259
- visualize_body: bool = True,
260
- visualize_landmarks: bool = True,
261
- visualize_joints: bool = True,
262
- visualize_measurements: bool=True):
263
-
264
- # TODO: create default model if not defined
265
- # if self.verts is None:
266
- # print("Model has not been defined. \
267
- # Visualizing on default male model")
268
- # model = create_model(self.smpl_path, "MALE", num_coefs=10)
269
- # shape = torch.zeros((1, 10), dtype=torch.float32)
270
- # model_output = set_shape(model, shape)
271
-
272
- # verts = model_output.vertices.detach().cpu().numpy().squeeze()
273
- # faces = model.faces.squeeze()
274
- # else:
275
- # verts = self.verts
276
- # faces = self.faces
277
-
278
- if measurement_names == []:
279
- measurement_names = self.all_possible_measurements
280
-
281
- if landmark_names == []:
282
- landmark_names = list(self.landmarks.keys())
283
-
284
- vizz = Visualizer(verts=self.verts,
285
- faces=self.faces,
286
- joints=self.joints,
287
- landmarks=self.landmarks,
288
- measurements=self.measurements,
289
- measurement_types=self.measurement_types,
290
- length_definitions=self.length_definitions,
291
- circumf_definitions=self.circumf_definitions,
292
- joint2ind=self.joint2ind,
293
- circumf_2_bodypart=self.circumf_2_bodypart,
294
- face_segmentation=self.face_segmentation,
295
- visualize_body=visualize_body,
296
- visualize_landmarks=visualize_landmarks,
297
- visualize_joints=visualize_joints,
298
- visualize_measurements=visualize_measurements,
299
- title=title
300
- )
301
-
302
- vizz.visualize(measurement_names=measurement_names,
303
- landmark_names=landmark_names,
304
- title=title)
305
-
306
-
307
- class MeasureSMPL(Measurer):
308
- '''
309
- Measure the SMPL model defined either by the shape parameters or
310
- by its 6890 vertices.
311
-
312
- All the measurements are expressed in cm.
313
- '''
314
-
315
- def __init__(self):
316
-
317
- super().__init__()
318
-
319
- self.model_type = "smpl"
320
- self.body_model_root = "data"
321
- self.body_model_path = os.path.join(self.body_model_root,
322
- self.model_type)
323
-
324
- self.faces = smplx.SMPL(self.body_model_path, ext="pkl").faces
325
- face_segmentation_path = os.path.join(self.body_model_path,
326
- f"{self.model_type}_body_parts_2_faces.json")
327
- self.face_segmentation = load_face_segmentation(face_segmentation_path)
328
-
329
- self.landmarks = SMPL_LANDMARK_INDICES
330
- self.measurement_types = MEASUREMENT_TYPES
331
- self.length_definitions = SMPLMeasurementDefinitions().LENGTHS
332
- self.circumf_definitions = SMPLMeasurementDefinitions().CIRCUMFERENCES
333
- self.circumf_2_bodypart = SMPLMeasurementDefinitions().CIRCUMFERENCE_TO_BODYPARTS
334
- self.all_possible_measurements = SMPLMeasurementDefinitions().possible_measurements
335
-
336
- self.joint2ind = SMPL_JOINT2IND
337
- self.num_joints = SMPL_NUM_JOINTS
338
-
339
- self.num_points = 6890
340
-
341
- def from_verts(self,
342
- verts: torch.tensor):
343
- '''
344
- Construct body model from only vertices.
345
- :param verts: torch.tensor (6890,3) of SMPL vertices
346
- '''
347
-
348
- verts = verts.squeeze()
349
- error_msg = f"verts need to be of dimension ({self.num_points},3)"
350
- assert verts.shape == torch.Size([self.num_points,3]), error_msg
351
-
352
- joint_regressor = get_joint_regressor(self.model_type,
353
- self.body_model_root,
354
- gender="NEUTRAL",
355
- num_thetas=self.num_joints)
356
- joints = torch.matmul(joint_regressor, verts)
357
- self.joints = joints.numpy()
358
- self.verts = verts.numpy()
359
-
360
- def from_body_model(self,
361
- gender: str,
362
- shape: torch.tensor):
363
- '''
364
- Construct body model from given gender and shape params
365
- of SMPl model.
366
- :param gender: str, MALE or FEMALE or NEUTRAL
367
- :param shape: torch.tensor, (1,10) beta parameters
368
- for SMPL model
369
- '''
370
-
371
- model = create_model(model_type=self.model_type,
372
- model_root=self.body_model_root,
373
- gender=gender,
374
- num_betas=10,
375
- num_thetas=self.num_joints)
376
- model_output = set_shape(model, shape)
377
-
378
- self.verts = model_output.vertices.detach().cpu().numpy().squeeze()
379
- self.joints = model_output.joints.squeeze().detach().cpu().numpy()
380
- self.gender = gender
381
-
382
-
383
- class MeasureSMPLX(Measurer):
384
- '''
385
- Measure the SMPLX model defined either by the shape parameters or
386
- by its 10475 vertices.
387
-
388
- All the measurements are expressed in cm.
389
- '''
390
-
391
- def __init__(self):
392
-
393
- super().__init__()
394
-
395
- self.model_type = "smplx"
396
- self.body_model_root = "data"
397
- self.body_model_path = os.path.join(self.body_model_root,
398
- self.model_type)
399
-
400
- self.faces = smplx.SMPLX(self.body_model_path, ext="pkl").faces
401
- face_segmentation_path = os.path.join(self.body_model_path,
402
- f"{self.model_type}_body_parts_2_faces.json")
403
- self.face_segmentation = load_face_segmentation(face_segmentation_path)
404
-
405
- self.landmarks = SMPLX_LANDMARK_INDICES
406
- self.measurement_types = MEASUREMENT_TYPES
407
- self.length_definitions = SMPLXMeasurementDefinitions().LENGTHS
408
- self.circumf_definitions = SMPLXMeasurementDefinitions().CIRCUMFERENCES
409
- self.circumf_2_bodypart = SMPLXMeasurementDefinitions().CIRCUMFERENCE_TO_BODYPARTS
410
- self.all_possible_measurements = SMPLXMeasurementDefinitions().possible_measurements
411
-
412
- self.joint2ind = SMPLX_JOINT2IND
413
- self.num_joints = SMPLX_NUM_JOINTS
414
-
415
- self.num_points = 10475
416
-
417
- def from_verts(self,
418
- verts: torch.tensor):
419
- '''
420
- Construct body model from only vertices.
421
- :param verts: torch.tensor (10475,3) of SMPLX vertices
422
- '''
423
-
424
- verts = verts.squeeze()
425
- error_msg = f"verts need to be of dimension ({self.num_points},3)"
426
- assert verts.shape == torch.Size([self.num_points,3]), error_msg
427
-
428
- joint_regressor = get_joint_regressor(self.model_type,
429
- self.body_model_root,
430
- gender="NEUTRAL",
431
- num_thetas=self.num_joints)
432
- joints = torch.matmul(joint_regressor, verts)
433
- self.joints = joints.numpy()
434
- self.verts = verts.numpy()
435
-
436
- def from_body_model(self,
437
- gender: str,
438
- shape: torch.tensor):
439
- '''
440
- Construct body model from given gender and shape params
441
- of SMPl model.
442
- :param gender: str, MALE or FEMALE or NEUTRAL
443
- :param shape: torch.tensor, (1,10) beta parameters
444
- for SMPL model
445
- '''
446
-
447
- model = create_model(model_type=self.model_type,
448
- model_root=self.body_model_root,
449
- gender=gender,
450
- num_betas=10,
451
- num_thetas=self.num_joints)
452
- model_output = set_shape(model, shape)
453
-
454
- self.verts = model_output.vertices.detach().cpu().numpy().squeeze()
455
- self.joints = model_output.joints.squeeze().detach().cpu().numpy()
456
- self.gender = gender
457
-
458
-
459
- class MeasureBody():
460
- def __new__(cls, model_type):
461
- model_type = model_type.lower()
462
- if model_type == 'smpl':
463
- return MeasureSMPL()
464
- elif model_type == 'smplx':
465
- return MeasureSMPLX()
466
- else:
467
- raise NotImplementedError("Model type not defined")
468
-
469
-
470
-
471
- if __name__ == "__main__":
472
-
473
- parser = argparse.ArgumentParser(description='Measure body models.')
474
- parser.add_argument('--measure_neutral_smpl_with_mean_shape', action='store_true',
475
- help="Measure a mean shape smpl model.")
476
- parser.add_argument('--measure_neutral_smplx_with_mean_shape', action='store_true',
477
- help="Measure a mean shape smplx model.")
478
- args = parser.parse_args()
479
-
480
- model_types_to_measure = []
481
- if args.measure_neutral_smpl_with_mean_shape:
482
- model_types_to_measure.append("smpl")
483
- elif args.measure_neutral_smplx_with_mean_shape:
484
- model_types_to_measure.append("smplx")
485
-
486
- for model_type in model_types_to_measure:
487
- print(f"Measuring {model_type} body model")
488
- measurer = MeasureBody(model_type)
489
-
490
- betas = torch.zeros((1, 10), dtype=torch.float32)
491
- measurer.from_body_model(gender="NEUTRAL", shape=betas)
492
-
493
- measurement_names = measurer.all_possible_measurements
494
- measurer.measure(measurement_names)
495
- print("Measurements")
496
- pprint(measurer.measurements)
497
-
498
- measurer.label_measurements(STANDARD_LABELS)
499
- print("Labeled measurements")
500
- pprint(measurer.labeled_measurements)
501
-
502
- measurer.visualize()