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
  6from typing import List, Tuple
  7
  8import numpy as np
  9import numpy as onp
 10import tyro
 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(**onp.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.gui.configure_theme(control_layout="collapsible")
 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    smpl_outputs = model.get_outputs(
 83        betas=np.array([x.value for x in gui_elements.gui_betas]),
 84        joint_rotmats=onp.zeros((model.num_joints, 3, 3)) + onp.eye(3),
 85    )
 86
 87    bone_wxyzs = np.array(
 88        [tf.SO3.from_matrix(R).wxyz for R in smpl_outputs.T_world_joint[:, :3, :3]]
 89    )
 90    bone_positions = smpl_outputs.T_world_joint[:, :3, 3]
 91
 92    skinned_handle = server.scene.add_mesh_skinned(
 93        "/human",
 94        smpl_outputs.vertices,
 95        smpl_outputs.faces,
 96        bone_wxyzs=bone_wxyzs,
 97        bone_positions=bone_positions,
 98        skin_weights=model._weights,
 99        wireframe=gui_elements.gui_wireframe.value,
100        color=gui_elements.gui_rgb.value,
101    )
102
103    while True:
104        # Do nothing if no change.
105        time.sleep(0.02)
106        if not gui_elements.changed:
107            continue
108
109        gui_elements.changed = False
110
111        # Compute SMPL outputs.
112        smpl_outputs = model.get_outputs(
113            betas=np.array([x.value for x in gui_elements.gui_betas]),
114            joint_rotmats=np.stack(
115                [
116                    tf.SO3.exp(np.array(x.value)).as_matrix()
117                    for x in gui_elements.gui_joints
118                ],
119                axis=0,
120            ),
121        )
122
123        # Match transform control gizmos to joint positions.
124        for i, control in enumerate(gui_elements.transform_controls):
125            control.position = smpl_outputs.T_parent_joint[i, :3, 3]
126            print(control.position)
127
128            skinned_handle.bones[i].wxyz = tf.SO3.from_matrix(
129                smpl_outputs.T_world_joint[i, :3, :3]
130            ).wxyz
131            skinned_handle.bones[i].position = smpl_outputs.T_world_joint[i, :3, 3]
132
133
134@dataclass
135class GuiElements:
136    """Structure containing handles for reading from GUI elements."""
137
138    gui_rgb: viser.GuiInputHandle[Tuple[int, int, int]]
139    gui_wireframe: viser.GuiInputHandle[bool]
140    gui_betas: List[viser.GuiInputHandle[float]]
141    gui_joints: List[viser.GuiInputHandle[Tuple[float, float, float]]]
142    transform_controls: List[viser.TransformControlsHandle]
143
144    changed: bool
145    """This flag will be flipped to True whenever the mesh needs to be re-generated."""
146
147
148def make_gui_elements(
149    server: viser.ViserServer,
150    num_betas: int,
151    num_joints: int,
152    parent_idx: np.ndarray,
153) -> GuiElements:
154    """Make GUI elements for interacting with the model."""
155
156    tab_group = server.gui.add_tab_group()
157
158    def set_changed(_) -> None:
159        out.changed = True  # out is define later!
160
161    # GUI elements: mesh settings + visibility.
162    with tab_group.add_tab("View", viser.Icon.VIEWFINDER):
163        gui_rgb = server.gui.add_rgb("Color", initial_value=(90, 200, 255))
164        gui_wireframe = server.gui.add_checkbox("Wireframe", initial_value=False)
165        gui_show_controls = server.gui.add_checkbox("Handles", initial_value=True)
166
167        gui_rgb.on_update(set_changed)
168        gui_wireframe.on_update(set_changed)
169
170        @gui_show_controls.on_update
171        def _(_):
172            for control in transform_controls:
173                control.visible = gui_show_controls.value
174
175    # GUI elements: shape parameters.
176    with tab_group.add_tab("Shape", viser.Icon.BOX):
177        gui_reset_shape = server.gui.add_button("Reset Shape")
178        gui_random_shape = server.gui.add_button("Random Shape")
179
180        @gui_reset_shape.on_click
181        def _(_):
182            for beta in gui_betas:
183                beta.value = 0.0
184
185        @gui_random_shape.on_click
186        def _(_):
187            for beta in gui_betas:
188                beta.value = onp.random.normal(loc=0.0, scale=1.0)
189
190        gui_betas = []
191        for i in range(num_betas):
192            beta = server.gui.add_slider(
193                f"beta{i}", min=-5.0, max=5.0, step=0.01, initial_value=0.0
194            )
195            gui_betas.append(beta)
196            beta.on_update(set_changed)
197
198    # GUI elements: joint angles.
199    with tab_group.add_tab("Joints", viser.Icon.ANGLE):
200        gui_reset_joints = server.gui.add_button("Reset Joints")
201        gui_random_joints = server.gui.add_button("Random Joints")
202
203        @gui_reset_joints.on_click
204        def _(_):
205            for joint in gui_joints:
206                joint.value = (0.0, 0.0, 0.0)
207
208        @gui_random_joints.on_click
209        def _(_):
210            for joint in gui_joints:
211                # It's hard to uniformly sample orientations directly in so(3), so we
212                # first sample on S^3 and then convert.
213                quat = onp.random.normal(loc=0.0, scale=1.0, size=(4,))
214                quat /= onp.linalg.norm(quat)
215                joint.value = tf.SO3(wxyz=quat).log()
216
217        gui_joints: List[viser.GuiInputHandle[Tuple[float, float, float]]] = []
218        for i in range(num_joints):
219            gui_joint = server.gui.add_vector3(
220                label=f"Joint {i}",
221                initial_value=(0.0, 0.0, 0.0),
222                step=0.05,
223            )
224            gui_joints.append(gui_joint)
225
226            def set_callback_in_closure(i: int) -> None:
227                @gui_joint.on_update
228                def _(_):
229                    transform_controls[i].wxyz = tf.SO3.exp(
230                        np.array(gui_joints[i].value)
231                    ).wxyz
232                    out.changed = True
233
234            set_callback_in_closure(i)
235
236    # Transform control gizmos on joints.
237    transform_controls: List[viser.TransformControlsHandle] = []
238    prefixed_joint_names = []  # Joint names, but prefixed with parents.
239    for i in range(num_joints):
240        prefixed_joint_name = f"joint_{i}"
241        if i > 0:
242            prefixed_joint_name = (
243                prefixed_joint_names[parent_idx[i]] + "/" + prefixed_joint_name
244            )
245        prefixed_joint_names.append(prefixed_joint_name)
246        controls = server.scene.add_transform_controls(
247            f"/smpl/{prefixed_joint_name}",
248            depth_test=False,
249            scale=0.2 * (0.75 ** prefixed_joint_name.count("/")),
250            disable_axes=True,
251            disable_sliders=True,
252            visible=gui_show_controls.value,
253        )
254        transform_controls.append(controls)
255
256        def set_callback_in_closure(i: int) -> None:
257            @controls.on_update
258            def _(_) -> None:
259                axisangle = tf.SO3(transform_controls[i].wxyz).log()
260                gui_joints[i].value = (axisangle[0], axisangle[1], axisangle[2])
261
262        set_callback_in_closure(i)
263
264    out = GuiElements(
265        gui_rgb,
266        gui_wireframe,
267        gui_betas,
268        gui_joints,
269        transform_controls=transform_controls,
270        changed=True,
271    )
272    return out
273
274
275if __name__ == "__main__":
276    tyro.cli(main, description=__doc__)