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