SMPL model visualizerΒΆ

Visualizer for SMPL human body models. Requires a .npz model file.

See here for download instructions:

https://github.com/vchoutas/smplx?tab=readme-ov-file#downloading-the-model

  1from __future__ import annotations
  2
  3import time
  4from dataclasses import dataclass
  5from pathlib import Path
  6
  7import numpy as np
  8import trimesh
  9import tyro
 10
 11import viser
 12import viser.transforms as tf
 13
 14
 15@dataclass(frozen=True)
 16class SmplOutputs:
 17    vertices: np.ndarray
 18    faces: np.ndarray
 19    T_world_joint: np.ndarray  # (num_joints, 4, 4)
 20    T_parent_joint: np.ndarray  # (num_joints, 4, 4)
 21
 22
 23class SmplHelper:
 24    """Helper for models in the SMPL family, implemented in numpy."""
 25
 26    def __init__(self, model_path: Path) -> None:
 27        assert model_path.suffix.lower() == ".npz", "Model should be an .npz file!"
 28        body_dict = dict(**np.load(model_path, allow_pickle=True))
 29
 30        self.J_regressor = body_dict["J_regressor"]
 31        self.weights = body_dict["weights"]
 32        self.v_template = body_dict["v_template"]
 33        self.posedirs = body_dict["posedirs"]
 34        self.shapedirs = body_dict["shapedirs"]
 35        self.faces = body_dict["f"]
 36
 37        self.num_joints: int = self.weights.shape[-1]
 38        self.num_betas: int = self.shapedirs.shape[-1]
 39        self.parent_idx: np.ndarray = body_dict["kintree_table"][0]
 40
 41    def get_outputs(self, betas: np.ndarray, joint_rotmats: np.ndarray) -> SmplOutputs:
 42        # Get shaped vertices + joint positions, when all local poses are identity.
 43        v_tpose = self.v_template + np.einsum("vxb,b->vx", self.shapedirs, betas)
 44        j_tpose = np.einsum("jv,vx->jx", self.J_regressor, v_tpose)
 45
 46        # Local SE(3) transforms.
 47        T_parent_joint = np.zeros((self.num_joints, 4, 4)) + np.eye(4)
 48        T_parent_joint[:, :3, :3] = joint_rotmats
 49        T_parent_joint[0, :3, 3] = j_tpose[0]
 50        T_parent_joint[1:, :3, 3] = j_tpose[1:] - j_tpose[self.parent_idx[1:]]
 51
 52        # Forward kinematics.
 53        T_world_joint = T_parent_joint.copy()
 54        for i in range(1, self.num_joints):
 55            T_world_joint[i] = T_world_joint[self.parent_idx[i]] @ T_parent_joint[i]
 56
 57        # Linear blend skinning.
 58        pose_delta = (joint_rotmats[1:, ...] - np.eye(3)).flatten()
 59        v_blend = v_tpose + np.einsum("byn,n->by", self.posedirs, pose_delta)
 60        v_delta = np.ones((v_blend.shape[0], self.num_joints, 4))
 61        v_delta[:, :, :3] = v_blend[:, None, :] - j_tpose[None, :, :]
 62        v_posed = np.einsum(
 63            "jxy,vj,vjy->vx", T_world_joint[:, :3, :], self.weights, v_delta
 64        )
 65        return SmplOutputs(v_posed, self.faces, T_world_joint, T_parent_joint)
 66
 67
 68def main(model_path: Path) -> None:
 69    server = viser.ViserServer()
 70    server.scene.set_up_direction("+y")
 71    server.scene.add_grid("/grid", position=(0.0, -1.3, 0.0), plane="xz")
 72
 73    # Main loop. We'll read pose/shape from the GUI elements, compute the mesh,
 74    # and then send the updated mesh in a loop.
 75    model = SmplHelper(model_path)
 76    gui_elements = make_gui_elements(
 77        server,
 78        num_betas=model.num_betas,
 79        num_joints=model.num_joints,
 80        parent_idx=model.parent_idx,
 81    )
 82    body_handle = server.scene.add_mesh_simple(
 83        "/human",
 84        model.v_template,
 85        model.faces,
 86        wireframe=gui_elements.gui_wireframe.value,
 87        color=gui_elements.gui_rgb.value,
 88    )
 89
 90    # Add a vertex selector to the mesh. This will allow us to click on
 91    # vertices to get indices.
 92    red_sphere = trimesh.creation.icosphere(radius=0.001, subdivisions=1)
 93    red_sphere.visual.vertex_colors = (255, 0, 0, 255)  # type: ignore
 94
 95    while True:
 96        # Do nothing if no change.
 97        time.sleep(0.02)
 98        if not gui_elements.changed:
 99            continue
100
101        gui_elements.changed = False
102
103        # If anything has changed, re-compute SMPL outputs.
104        smpl_outputs = model.get_outputs(
105            betas=np.array([x.value for x in gui_elements.gui_betas]),
106            joint_rotmats=tf.SO3.exp(
107                # (num_joints, 3)
108                np.array([x.value for x in gui_elements.gui_joints])
109            ).as_matrix(),
110        )
111
112        # Update the mesh properties based on the SMPL model output + GUI
113        # elements.
114        body_handle.vertices = smpl_outputs.vertices
115        body_handle.wireframe = gui_elements.gui_wireframe.value
116        body_handle.color = gui_elements.gui_rgb.value
117
118        # Match transform control gizmos to joint positions.
119        for i, control in enumerate(gui_elements.transform_controls):
120            control.position = smpl_outputs.T_parent_joint[i, :3, 3]
121
122
123@dataclass
124class GuiElements:
125    """Structure containing handles for reading from GUI elements."""
126
127    gui_rgb: viser.GuiInputHandle[tuple[int, int, int]]
128    gui_wireframe: viser.GuiInputHandle[bool]
129    gui_betas: list[viser.GuiInputHandle[float]]
130    gui_joints: list[viser.GuiInputHandle[tuple[float, float, float]]]
131    transform_controls: list[viser.TransformControlsHandle]
132
133    changed: bool
134    """This flag will be flipped to True whenever the mesh needs to be re-generated."""
135
136
137def make_gui_elements(
138    server: viser.ViserServer,
139    num_betas: int,
140    num_joints: int,
141    parent_idx: np.ndarray,
142) -> GuiElements:
143    """Make GUI elements for interacting with the model."""
144
145    tab_group = server.gui.add_tab_group()
146
147    def set_changed(_) -> None:
148        out.changed = True  # out is define later!
149
150    # GUI elements: mesh settings + visibility.
151    with tab_group.add_tab("View", viser.Icon.VIEWFINDER):
152        gui_rgb = server.gui.add_rgb("Color", initial_value=(90, 200, 255))
153        gui_wireframe = server.gui.add_checkbox("Wireframe", initial_value=False)
154        gui_show_controls = server.gui.add_checkbox("Handles", initial_value=True)
155
156        gui_rgb.on_update(set_changed)
157        gui_wireframe.on_update(set_changed)
158
159        @gui_show_controls.on_update
160        def _(_):
161            for control in transform_controls:
162                control.visible = gui_show_controls.value
163
164    # GUI elements: shape parameters.
165    with tab_group.add_tab("Shape", viser.Icon.BOX):
166        gui_reset_shape = server.gui.add_button("Reset Shape")
167        gui_random_shape = server.gui.add_button("Random Shape")
168
169        @gui_reset_shape.on_click
170        def _(_):
171            for beta in gui_betas:
172                beta.value = 0.0
173
174        @gui_random_shape.on_click
175        def _(_):
176            for beta in gui_betas:
177                beta.value = np.random.normal(loc=0.0, scale=1.0)
178
179        gui_betas = []
180        for i in range(num_betas):
181            beta = server.gui.add_slider(
182                f"beta{i}", min=-5.0, max=5.0, step=0.01, initial_value=0.0
183            )
184            gui_betas.append(beta)
185            beta.on_update(set_changed)
186
187    # GUI elements: joint angles.
188    with tab_group.add_tab("Joints", viser.Icon.ANGLE):
189        gui_reset_joints = server.gui.add_button("Reset Joints")
190        gui_random_joints = server.gui.add_button("Random Joints")
191
192        @gui_reset_joints.on_click
193        def _(_):
194            for joint in gui_joints:
195                joint.value = (0.0, 0.0, 0.0)
196
197        @gui_random_joints.on_click
198        def _(_):
199            rng = np.random.default_rng()
200            for joint in gui_joints:
201                joint.value = tf.SO3.sample_uniform(rng).log()
202
203        gui_joints: list[viser.GuiInputHandle[tuple[float, float, float]]] = []
204        for i in range(num_joints):
205            gui_joint = server.gui.add_vector3(
206                label=f"Joint {i}",
207                initial_value=(0.0, 0.0, 0.0),
208                step=0.05,
209            )
210            gui_joints.append(gui_joint)
211
212            def set_callback_in_closure(i: int) -> None:
213                @gui_joint.on_update
214                def _(_):
215                    transform_controls[i].wxyz = tf.SO3.exp(
216                        np.array(gui_joints[i].value)
217                    ).wxyz
218                    out.changed = True
219
220            set_callback_in_closure(i)
221
222    # Transform control gizmos on joints.
223    transform_controls: list[viser.TransformControlsHandle] = []
224    prefixed_joint_names = []  # Joint names, but prefixed with parents.
225    for i in range(num_joints):
226        prefixed_joint_name = f"joint_{i}"
227        if i > 0:
228            prefixed_joint_name = (
229                prefixed_joint_names[parent_idx[i]] + "/" + prefixed_joint_name
230            )
231        prefixed_joint_names.append(prefixed_joint_name)
232        controls = server.scene.add_transform_controls(
233            f"/smpl/{prefixed_joint_name}",
234            depth_test=False,
235            scale=0.2 * (0.75 ** prefixed_joint_name.count("/")),
236            disable_axes=True,
237            disable_sliders=True,
238            visible=gui_show_controls.value,
239        )
240        transform_controls.append(controls)
241
242        def set_callback_in_closure(i: int) -> None:
243            @controls.on_update
244            def _(_) -> None:
245                axisangle = tf.SO3(transform_controls[i].wxyz).log()
246                gui_joints[i].value = (axisangle[0], axisangle[1], axisangle[2])
247
248        set_callback_in_closure(i)
249
250    out = GuiElements(
251        gui_rgb,
252        gui_wireframe,
253        gui_betas,
254        gui_joints,
255        transform_controls=transform_controls,
256        changed=True,
257    )
258    return out
259
260
261if __name__ == "__main__":
262    tyro.cli(main, description=__doc__)