File size: 7,259 Bytes
86cd604
 
 
 
 
 
 
4ea1d6a
86cd604
 
 
 
 
 
 
 
 
 
 
 
4ea1d6a
86cd604
4ea1d6a
 
 
 
 
 
 
 
 
86cd604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea1d6a
86cd604
4ea1d6a
86cd604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea1d6a
 
 
 
 
 
86cd604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea1d6a
86cd604
 
4ea1d6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86cd604
 
 
 
 
4ea1d6a
86cd604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea1d6a
86cd604
 
 
 
4ea1d6a
86cd604
 
 
 
 
4ea1d6a
86cd604
 
4ea1d6a
 
86cd604
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import List, Dict
import numpy as np
import trimesh
import torch
import smplx
import os
import argparse
from pprint import pprint

from measurement_definitions import *
from utils import *
from visualize import Visualizer
from landmark_definitions import *
from joint_definitions import *


def set_shape(model, shape_coefs):
    shape_coefs = shape_coefs.to(torch.float32)
    return model(betas=shape_coefs, return_verts=True)


def create_model(model_type, model_root, gender, num_betas=10, num_thetas=24):
    return smplx.create(
        model_path=model_root,
        model_type=model_type,
        gender=gender,
        use_face_contour=False,
        num_betas=num_betas,
        ext='pkl'
    )


class Measurer():
    def __init__(self):
        self.verts = None
        self.faces = None
        self.joints = None
        self.gender = None
        self.measurements = {}
        self.height_normalized_measurements = {}
        self.labeled_measurements = {}
        self.height_normalized_labeled_measurements = {}
        self.labels2names = {}

    def from_verts(self):
        pass

    def from_body_model(self):
        pass

    def measure(self, measurement_names: List[str]):
        for m_name in measurement_names:
            if m_name not in self.all_possible_measurements:
                continue
            if m_name in self.measurements:
                continue
            if self.measurement_types[m_name] == MeasurementType().LENGTH:
                self.measurements[m_name] = self.measure_length(m_name)
            elif self.measurement_types[m_name] == MeasurementType().CIRCUMFERENCE:
                self.measurements[m_name] = self.measure_circumference(m_name)

    def measure_length(self, measurement_name: str):
        inds = self.length_definitions[measurement_name]
        points = [(self.verts[i] if not isinstance(i, tuple) else (self.verts[i[0]] + self.verts[i[1]]) / 2) for i in inds]
        return self._get_dist(np.vstack(points)[None, ...])

    @staticmethod
    def _get_dist(verts: np.ndarray) -> float:
        return np.sum(np.linalg.norm(verts[:, 1] - verts[:, 0], axis=1)) * 100

    def measure_circumference(self, measurement_name: str):
        definition = self.circumf_definitions[measurement_name]
        landmark_indices = [self.landmarks[name] for name in definition["LANDMARKS"]]
        n1, n2 = self.joint2ind[definition["JOINTS"][0]], self.joint2ind[definition["JOINTS"][1]]
        origin = np.mean(self.verts[landmark_indices, :], axis=0)
        normal = self.joints[n1, :] - self.joints[n2, :]
        mesh = trimesh.Trimesh(vertices=self.verts, faces=self.faces)
        segments, faces = trimesh.intersections.mesh_plane(
            mesh, plane_normal=normal, plane_origin=origin, return_faces=True)
        segments = filter_body_part_slices(
            segments, faces, measurement_name,
            self.circumf_2_bodypart, self.face_segmentation
        )
        return self._get_dist(convex_hull_from_3D_points(segments))

    def height_normalize_measurements(self, new_height: float):
        old_height = self.measurements.get("height")
        if not old_height:
            return
        for k, v in self.measurements.items():
            self.height_normalized_measurements[k] = (v / old_height) * new_height
        for k, v in self.labeled_measurements.items():
            self.height_normalized_labeled_measurements[k] = (v / old_height) * new_height

    def label_measurements(self, set_measurement_labels: Dict[str, str]):
        self.labeled_measurements = {}
        self.labels2names = {}
        for label, name in set_measurement_labels.items():
            if name not in self.all_possible_measurements:
                continue
            if name not in self.measurements:
                self.measure([name])
            self.labeled_measurements[label] = self.measurements[name]
            self.labels2names[label] = name

    def visualize(self, measurement_names=[], landmark_names=[], title="Measurement Visualization", **kwargs):
        measurement_names = measurement_names or self.all_possible_measurements
        landmark_names = landmark_names or list(self.landmarks.keys())
        vizz = Visualizer(
            verts=self.verts,
            faces=self.faces,
            joints=self.joints,
            landmarks=self.landmarks,
            measurements=self.measurements,
            measurement_types=self.measurement_types,
            length_definitions=self.length_definitions,
            circumf_definitions=self.circumf_definitions,
            joint2ind=self.joint2ind,
            circumf_2_bodypart=self.circumf_2_bodypart,
            face_segmentation=self.face_segmentation,
            title=title,
            **kwargs
        )
        vizz.visualize(measurement_names=measurement_names, landmark_names=landmark_names)


class MeasureSMPL(Measurer):
    def __init__(self):
        super().__init__()
        self.model_type = "smpl"
        self.body_model_root = "."  # Flat structure: model files in root
        self.faces = smplx.SMPL("SMPL_MALE.pkl", ext="pkl").faces
        self.face_segmentation = load_face_segmentation("smpl_body_parts_2_faces.json")
        self.landmarks = SMPL_LANDMARK_INDICES
        self.measurement_types = MEASUREMENT_TYPES
        self.length_definitions = SMPLMeasurementDefinitions().LENGTHS
        self.circumf_definitions = SMPLMeasurementDefinitions().CIRCUMFERENCES
        self.circumf_2_bodypart = SMPLMeasurementDefinitions().CIRCUMFERENCE_TO_BODYPARTS
        self.all_possible_measurements = SMPLMeasurementDefinitions().possible_measurements
        self.joint2ind = SMPL_JOINT2IND
        self.num_joints = SMPL_NUM_JOINTS
        self.num_points = 6890

    def from_verts(self, verts: torch.tensor):
        verts = verts.squeeze()
        assert verts.shape == torch.Size([self.num_points, 3])
        regressor = get_joint_regressor(self.model_type, ".", gender="MALE", num_thetas=self.num_joints)
        self.joints = torch.matmul(regressor, verts).numpy()
        self.verts = verts.numpy()

    def from_body_model(self, gender: str, shape: torch.tensor):
        model = create_model(self.model_type, ".", gender, num_betas=10, num_thetas=self.num_joints)
        output = set_shape(model, shape)
        self.verts = output.vertices.detach().cpu().numpy().squeeze()
        self.joints = output.joints.squeeze().detach().cpu().numpy()
        self.gender = gender


class MeasureBody():
    def __new__(cls, model_type):
        return MeasureSMPL() if model_type.lower() == 'smpl' else MeasureSMPLX()  # fallback


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--measure_neutral_smpl_with_mean_shape', action='store_true')
    args = parser.parse_args()
    if args.measure_neutral_smpl_with_mean_shape:
        measurer = MeasureBody("smpl")
        betas = torch.zeros((1, 10), dtype=torch.float32)
        measurer.from_body_model(gender="MALE", shape=betas)
        measurer.measure(measurer.all_possible_measurements)
        pprint(measurer.measurements)
        measurer.label_measurements(STANDARD_LABELS)
        pprint(measurer.labeled_measurements)
        measurer.visualize()