Datasets:
Download generator/scripts/prepare_sequence_from_blender_addon.py from mage0001/H2SMV-FPV: direct link, hf CLI and curl.
- Browser
- Download file 34.5 kB
-
https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/prepare_sequence_from_blender_addon.py
- Command line
-
hf download hf://datasets/mage0001/H2SMV-FPV/generator/scripts/prepare_sequence_from_blender_addon.py
-
curl -L -o prepare_sequence_from_blender_addon.py https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/prepare_sequence_from_blender_addon.py
34.5 kB
| #!/usr/bin/env python3 | |
| """ | |
| Prepare one SMPL-X sequence using the local SMPL-X Blender add-on. | |
| This script is intended to run inside Blender: | |
| blender -b --python scripts/prepare_sequence_from_blender_addon.py -- ... | |
| It uses the add-on's bundled SMPL-X locked-head model to create a skinned mesh, | |
| applies one fixed body shape for the sequence, applies the input pose per frame, | |
| then exports evaluated vertices plus an approximate COCO-WholeBody 133 skeleton. | |
| Face keypoints are intentionally disabled for v1. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import importlib | |
| import json | |
| import math | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| from typing import Any | |
| import bpy | |
| import mathutils | |
| import numpy as np | |
| COCO_WHOLEBODY_FACE_SLICE = slice(23, 91) | |
| LEFT_HAND_SLICE = slice(91, 112) | |
| RIGHT_HAND_SLICE = slice(112, 133) | |
| SMPLX_VERTEX_IDS = { | |
| "nose": 9120, | |
| "reye": 9929, | |
| "leye": 9448, | |
| "rear": 616, | |
| "lear": 6, | |
| "rthumb": 8079, | |
| "rindex": 7669, | |
| "rmiddle": 7794, | |
| "rring": 7905, | |
| "rpinky": 8022, | |
| "lthumb": 5361, | |
| "lindex": 4933, | |
| "lmiddle": 5058, | |
| "lring": 5169, | |
| "lpinky": 5286, | |
| "LBigToe": 5770, | |
| "LSmallToe": 5780, | |
| "LHeel": 8846, | |
| "RBigToe": 8463, | |
| "RSmallToe": 8474, | |
| "RHeel": 8635, | |
| } | |
| DEFAULT_ADDON_DIR = Path(__file__).resolve().parents[1] / "addons" / "smplx_blender_addon" | |
| SMPLX_BONE_ORDER = ( | |
| "pelvis", "left_hip", "right_hip", "spine1", "left_knee", "right_knee", | |
| "spine2", "left_ankle", "right_ankle", "spine3", "left_foot", "right_foot", | |
| "neck", "left_collar", "right_collar", "head", "left_shoulder", | |
| "right_shoulder", "left_elbow", "right_elbow", "left_wrist", "right_wrist", | |
| "jaw", "left_eye_smplhf", "right_eye_smplhf", | |
| "left_index1", "left_index2", "left_index3", | |
| "left_middle1", "left_middle2", "left_middle3", | |
| "left_pinky1", "left_pinky2", "left_pinky3", | |
| "left_ring1", "left_ring2", "left_ring3", | |
| "left_thumb1", "left_thumb2", "left_thumb3", | |
| "right_index1", "right_index2", "right_index3", | |
| "right_middle1", "right_middle2", "right_middle3", | |
| "right_pinky1", "right_pinky2", "right_pinky3", | |
| "right_ring1", "right_ring2", "right_ring3", | |
| "right_thumb1", "right_thumb2", "right_thumb3", | |
| ) | |
| def parse_blender_args() -> argparse.Namespace: | |
| argv = sys.argv | |
| if "--" in argv: | |
| argv = argv[argv.index("--") + 1 :] | |
| else: | |
| argv = [] | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--npz", required=True, type=Path) | |
| parser.add_argument("--out-dir", required=True, type=Path) | |
| parser.add_argument("--addon-dir", default=DEFAULT_ADDON_DIR, type=Path) | |
| parser.add_argument("--gender", default="auto", choices=["auto", "neutral", "male", "female"]) | |
| parser.add_argument("--model-variant", default="locked_head", choices=["locked_head", "v1.1"]) | |
| parser.add_argument("--uv-version", default="UV_2023", choices=["UV_2023", "UV_2021"]) | |
| parser.add_argument("--pose-key", default=None) | |
| parser.add_argument("--betas-key", default=None) | |
| parser.add_argument("--transl-key", default=None) | |
| parser.add_argument("--expression-key", default=None) | |
| parser.add_argument("--framerate-key", default=None) | |
| parser.add_argument("--frames", default=None, help="Source frame spec start:end:stride. Default exports all frames.") | |
| parser.add_argument("--motion-slowdown", type=int, default=2, | |
| help="Integer temporal upsampling factor. 2 inserts one SLERP midpoint; 1 disables.") | |
| parser.add_argument("--max-output-frames", type=int, default=121, | |
| help="Maximum frames after interpolation. 0 keeps the full interpolated sequence.") | |
| parser.add_argument("--output-fps", type=int, default=16, | |
| help="Final renderer/video FPS, recorded in sequence metadata.") | |
| parser.add_argument("--random-betas", action="store_true") | |
| parser.add_argument("--ignore-input-betas", action="store_true") | |
| parser.add_argument("--beta-seed", type=int, default=42) | |
| parser.add_argument("--beta-std", type=float, default=1.0) | |
| parser.add_argument("--beta-clip", type=float, default=2.0) | |
| parser.add_argument("--num-betas", type=int, default=10) | |
| parser.add_argument("--disable-face", action="store_true", default=True) | |
| parser.add_argument("--enable-face", dest="disable_face", action="store_false") | |
| parser.add_argument("--anim-format", default="SMPL-X", choices=["SMPL-X", "AMASS"]) | |
| parser.add_argument("--ignore-global-orient", action="store_true") | |
| parser.add_argument("--zero-spine1", action="store_true") | |
| parser.add_argument("--center-xy", action="store_true", default=True) | |
| parser.add_argument("--no-center-xy", dest="center_xy", action="store_false") | |
| parser.add_argument("--ground-plane", action="store_true", default=True) | |
| parser.add_argument("--no-ground-plane", dest="ground_plane", action="store_false") | |
| return parser.parse_args(argv) | |
| def load_npz_array(npz: np.lib.npyio.NpzFile, key: str | None, fallback_keys: list[str]) -> np.ndarray | None: | |
| if key: | |
| if key not in npz: | |
| raise KeyError(f"Key '{key}' not found in npz. Available keys: {list(npz.keys())}") | |
| return np.asarray(npz[key]) | |
| for candidate in fallback_keys: | |
| if candidate in npz: | |
| return np.asarray(npz[candidate]) | |
| return None | |
| def normalize_pose_55(pose: np.ndarray) -> np.ndarray: | |
| pose = np.asarray(pose, dtype=np.float32) | |
| if pose.ndim == 3 and pose.shape[1:] == (55, 3): | |
| return pose | |
| if pose.ndim == 2 and pose.shape[1] == 165: | |
| return pose.reshape(pose.shape[0], 55, 3) | |
| if pose.ndim == 1 and pose.shape[0] == 165: | |
| return pose.reshape(1, 55, 3) | |
| raise ValueError(f"Pose must be [F,55,3], [F,165], or [165]. Got {pose.shape}.") | |
| def normalize_transl(transl: np.ndarray | None, num_frames: int) -> np.ndarray: | |
| if transl is None: | |
| return np.zeros((num_frames, 3), dtype=np.float32) | |
| transl = np.asarray(transl, dtype=np.float32) | |
| if transl.ndim == 1 and transl.shape[0] == 3: | |
| return np.broadcast_to(transl[None, :], (num_frames, 3)).copy() | |
| if transl.ndim == 2 and transl.shape == (num_frames, 3): | |
| return transl.copy() | |
| raise ValueError(f"transl must be [3] or [F,3]. Got {transl.shape}.") | |
| def normalize_expression(expression: np.ndarray | None, num_frames: int) -> np.ndarray | None: | |
| if expression is None: | |
| return None | |
| expression = np.asarray(expression, dtype=np.float32) | |
| if expression.ndim == 1: | |
| return np.broadcast_to(expression[None, :], (num_frames, expression.shape[0])).copy() | |
| if expression.ndim == 2 and expression.shape[0] == num_frames: | |
| return expression.copy() | |
| raise ValueError(f"expression must be [E] or [F,E]. Got {expression.shape}.") | |
| def parse_frame_spec(frame_spec: str | None, num_frames: int) -> list[int]: | |
| if frame_spec is None: | |
| return list(range(num_frames)) | |
| parts = frame_spec.split(":") | |
| if len(parts) not in (2, 3): | |
| raise ValueError("--frames must be start:end or start:end:stride") | |
| start = int(parts[0]) | |
| end = int(parts[1]) | |
| stride = int(parts[2]) if len(parts) == 3 else 1 | |
| if stride <= 0 or start < 0 or end > num_frames or start >= end: | |
| raise ValueError(f"Invalid frame range {frame_spec} for num_frames={num_frames}.") | |
| return list(range(start, end, stride)) | |
| def axis_angle_to_quaternion(axis_angle: np.ndarray) -> np.ndarray: | |
| """Convert [..., 3] rotation vectors to unit quaternions [w, x, y, z].""" | |
| axis_angle = np.asarray(axis_angle, dtype=np.float64) | |
| angle = np.linalg.norm(axis_angle, axis=-1, keepdims=True) | |
| half = 0.5 * angle | |
| scale = np.empty_like(angle) | |
| small = angle < 1e-8 | |
| scale[small] = 0.5 | |
| scale[~small] = np.sin(half[~small]) / angle[~small] | |
| quat = np.concatenate((np.cos(half), axis_angle * scale), axis=-1) | |
| quat /= np.maximum(np.linalg.norm(quat, axis=-1, keepdims=True), 1e-12) | |
| return quat | |
| def quaternion_to_axis_angle(quat: np.ndarray) -> np.ndarray: | |
| """Convert unit quaternions to the canonical shortest rotation vectors.""" | |
| quat = np.asarray(quat, dtype=np.float64) | |
| quat /= np.maximum(np.linalg.norm(quat, axis=-1, keepdims=True), 1e-12) | |
| # q and -q encode the same rotation. w >= 0 gives an angle in [0, pi]. | |
| quat = np.where((quat[..., :1] < 0.0), -quat, quat) | |
| xyz = quat[..., 1:] | |
| xyz_norm = np.linalg.norm(xyz, axis=-1, keepdims=True) | |
| angle = 2.0 * np.arctan2(xyz_norm, np.clip(quat[..., :1], -1.0, 1.0)) | |
| scale = np.empty_like(xyz_norm) | |
| small = xyz_norm < 1e-8 | |
| scale[small] = 2.0 | |
| scale[~small] = angle[~small] / xyz_norm[~small] | |
| return (xyz * scale).astype(np.float32) | |
| def quaternion_slerp(q0: np.ndarray, q1: np.ndarray, alpha: float) -> np.ndarray: | |
| """Vectorized shortest-path SLERP for matching arrays of quaternions.""" | |
| q0 = np.asarray(q0, dtype=np.float64) | |
| q1 = np.asarray(q1, dtype=np.float64) | |
| dot = np.sum(q0 * q1, axis=-1, keepdims=True) | |
| q1 = np.where(dot < 0.0, -q1, q1) | |
| dot = np.clip(np.abs(dot), 0.0, 1.0) | |
| near = dot > 0.9995 | |
| theta = np.arccos(dot) | |
| sin_theta = np.sin(theta) | |
| safe_sin = np.where(np.abs(sin_theta) < 1e-8, 1.0, sin_theta) | |
| s0 = np.sin((1.0 - alpha) * theta) / safe_sin | |
| s1 = np.sin(alpha * theta) / safe_sin | |
| spherical = s0 * q0 + s1 * q1 | |
| linear = (1.0 - alpha) * q0 + alpha * q1 | |
| out = np.where(near, linear, spherical) | |
| out /= np.maximum(np.linalg.norm(out, axis=-1, keepdims=True), 1e-12) | |
| return out | |
| def interpolate_motion( | |
| pose_55: np.ndarray, | |
| transl: np.ndarray, | |
| expression: np.ndarray | None, | |
| factor: int, | |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray]: | |
| """Upsample selected poses without duplicating shared segment endpoints.""" | |
| if factor < 1: | |
| raise ValueError("--motion-slowdown must be an integer >= 1") | |
| frame_count = pose_55.shape[0] | |
| if frame_count == 0: | |
| raise ValueError("Cannot interpolate an empty motion sequence") | |
| if factor == 1 or frame_count == 1: | |
| positions = np.arange(frame_count, dtype=np.float32) | |
| return pose_55.copy(), transl.copy(), None if expression is None else expression.copy(), positions | |
| pose_quat = axis_angle_to_quaternion(pose_55) | |
| out_count = (frame_count - 1) * factor + 1 | |
| out_pose = np.empty((out_count, 55, 3), dtype=np.float32) | |
| out_transl = np.empty((out_count, 3), dtype=np.float32) | |
| out_expression = None if expression is None else np.empty((out_count, expression.shape[1]), dtype=np.float32) | |
| positions = np.arange(out_count, dtype=np.float32) / float(factor) | |
| out_idx = 0 | |
| for source_idx in range(frame_count - 1): | |
| for substep in range(factor): | |
| alpha = substep / float(factor) | |
| if substep == 0: | |
| out_pose[out_idx] = pose_55[source_idx] | |
| else: | |
| out_pose[out_idx] = quaternion_to_axis_angle( | |
| quaternion_slerp(pose_quat[source_idx], pose_quat[source_idx + 1], alpha) | |
| ) | |
| out_transl[out_idx] = (1.0 - alpha) * transl[source_idx] + alpha * transl[source_idx + 1] | |
| if out_expression is not None: | |
| out_expression[out_idx] = ((1.0 - alpha) * expression[source_idx] | |
| + alpha * expression[source_idx + 1]) | |
| out_idx += 1 | |
| out_pose[-1] = pose_55[-1] | |
| out_transl[-1] = transl[-1] | |
| if out_expression is not None: | |
| out_expression[-1] = expression[-1] | |
| return out_pose, out_transl, out_expression, positions | |
| def jsonable(value: Any) -> Any: | |
| if isinstance(value, np.ndarray): | |
| return value.tolist() | |
| if isinstance(value, (np.integer, np.floating)): | |
| return value.item() | |
| if isinstance(value, Path): | |
| return str(value) | |
| return value | |
| def enable_addon(addon_dir: Path) -> None: | |
| addon_dir = addon_dir.resolve() | |
| if not addon_dir.exists(): | |
| raise FileNotFoundError(f"SMPL-X Blender addon not found: {addon_dir}") | |
| parent = addon_dir.parent | |
| if str(parent) not in sys.path: | |
| sys.path.insert(0, str(parent)) | |
| module = importlib.import_module(addon_dir.name) | |
| # Registering twice is harmless in the common background case after reload, | |
| # but Blender may raise if a class is already registered. | |
| try: | |
| module.register() | |
| except ValueError: | |
| pass | |
| def create_smplx_body(gender: str, model_variant: str, uv_version: str): | |
| wm_tool = bpy.context.window_manager.smplx_tool | |
| wm_tool.body_model = "smplx" | |
| wm_tool.smplx_gender = gender | |
| wm_tool.smplx_version = model_variant | |
| wm_tool.smplx_uv = uv_version | |
| wm_tool.smplx_handpose = "flat" | |
| result = bpy.ops.scene.smplx_add_gender() | |
| if "FINISHED" not in result: | |
| raise RuntimeError(f"bpy.ops.scene.smplx_add_gender failed: {result}") | |
| obj = bpy.context.view_layer.objects.active | |
| if obj is None or obj.type != "MESH": | |
| raise RuntimeError("SMPL-X addon did not leave an active mesh object.") | |
| armature = obj.parent | |
| if armature is None or armature.type != "ARMATURE": | |
| raise RuntimeError(f"SMPL-X mesh '{obj.name}' has no armature parent.") | |
| obj.name = "SMPLX_BODY_PREP" | |
| armature.name = "SMPLX_ARMATURE_PREP" | |
| return obj, armature | |
| def resolve_gender(data: np.lib.npyio.NpzFile, requested: str) -> str: | |
| if requested != "auto": | |
| return requested | |
| if "gender" not in data: | |
| return "neutral" | |
| gender = str(np.asarray(data["gender"]).item()).lower() | |
| if gender not in {"neutral", "male", "female"}: | |
| return "neutral" | |
| return gender | |
| def choose_betas( | |
| data: np.lib.npyio.NpzFile, | |
| betas_key: str | None, | |
| num_betas: int, | |
| random_betas: bool, | |
| ignore_input_betas: bool, | |
| beta_seed: int, | |
| beta_std: float, | |
| beta_clip: float, | |
| ) -> np.ndarray: | |
| if random_betas or ignore_input_betas: | |
| rng = np.random.default_rng(beta_seed) | |
| betas = rng.normal(0.0, beta_std, size=(num_betas,)).astype(np.float32) | |
| return np.clip(betas, -beta_clip, beta_clip).astype(np.float32) | |
| betas_raw = load_npz_array(data, betas_key, ["betas", "beta", "shape", "shapes"]) | |
| if betas_raw is None: | |
| return np.zeros((num_betas,), dtype=np.float32) | |
| betas_raw = np.asarray(betas_raw, dtype=np.float32) | |
| if betas_raw.ndim == 2: | |
| betas_raw = betas_raw[0] | |
| if betas_raw.ndim != 1: | |
| raise ValueError(f"betas must be [B] or [F,B]. Got {betas_raw.shape}.") | |
| out = np.zeros((num_betas,), dtype=np.float32) | |
| out[: min(num_betas, betas_raw.shape[0])] = betas_raw[:num_betas] | |
| return out | |
| def scalar_string(value: Any, default: str) -> str: | |
| if value is None: | |
| return default | |
| arr = np.asarray(value) | |
| try: | |
| item = arr.item() | |
| except ValueError: | |
| item = arr.reshape(-1)[0] | |
| if isinstance(item, bytes): | |
| return item.decode("utf-8") | |
| return str(item) | |
| def addon_ready_pose(pose_55: np.ndarray) -> np.ndarray: | |
| """SMPL-X add-on animation import expects poses as [F, 165], not [F, 55, 3].""" | |
| return np.asarray(pose_55, dtype=np.float32).reshape(pose_55.shape[0], 165) | |
| def write_addon_npz( | |
| source_data: np.lib.npyio.NpzFile, | |
| out_path: Path, | |
| pose_55: np.ndarray, | |
| transl: np.ndarray, | |
| expression: np.ndarray | None, | |
| betas: np.ndarray, | |
| gender: str, | |
| mocap_framerate: int, | |
| ) -> None: | |
| """Write a normalized SMPL-X npz for bpy.ops.object.smplx_add_animation.""" | |
| payload: dict[str, Any] = {} | |
| for key in source_data.files: | |
| value = source_data[key] | |
| if key in {"poses", "pose", "smplx_poses", "smplx_pose", "trans", "transl", "translation", "translations", "betas", "beta", "shape", "shapes", "gender", "expression", "expressions", "expr", "smplx_expr"}: | |
| continue | |
| payload[key] = value | |
| payload["poses"] = addon_ready_pose(pose_55) | |
| payload["trans"] = np.asarray(transl, dtype=np.float32) | |
| if expression is not None: | |
| payload["expression"] = np.asarray(expression, dtype=np.float32) | |
| payload["betas"] = np.asarray(betas, dtype=np.float32) | |
| payload["gender"] = np.asarray(gender) | |
| payload["mocap_framerate"] = np.asarray(int(mocap_framerate), dtype=np.int32) | |
| np.savez(out_path, **payload) | |
| def import_addon_animation( | |
| npz_path: Path, | |
| target_framerate: int, | |
| model_variant: str, | |
| uv_version: str, | |
| ) -> tuple[bpy.types.Object, bpy.types.Object]: | |
| wm_tool = bpy.context.window_manager.smplx_tool | |
| wm_tool.body_model = "smplx" | |
| wm_tool.smplx_version = model_variant | |
| wm_tool.smplx_uv = uv_version | |
| result = bpy.ops.object.smplx_add_animation( | |
| filepath=str(npz_path), | |
| anim_format="SMPL-X", | |
| keyframe_corrective_pose_weights=True, | |
| target_framerate=int(target_framerate), | |
| hand_reference="FLAT", | |
| ) | |
| if "FINISHED" not in result: | |
| raise RuntimeError(f"bpy.ops.object.smplx_add_animation failed: {result}") | |
| obj = bpy.context.view_layer.objects.active | |
| if obj is None or obj.type != "MESH": | |
| meshes = [candidate for candidate in bpy.context.scene.objects if candidate.type == "MESH" and candidate.get("body_model") == "smplx"] | |
| if not meshes: | |
| raise RuntimeError("SMPL-X addon animation import did not create an active SMPL-X mesh.") | |
| obj = meshes[-1] | |
| armature = obj.parent | |
| if armature is None or armature.type != "ARMATURE": | |
| raise RuntimeError(f"Imported SMPL-X mesh '{obj.name}' has no armature parent.") | |
| obj.name = "SMPLX_BODY_PREP" | |
| armature.name = "SMPLX_ARMATURE_PREP" | |
| return obj, armature | |
| def set_sequence_betas(obj: bpy.types.Object, betas: np.ndarray) -> None: | |
| key_blocks = obj.data.shape_keys.key_blocks | |
| for key_block in key_blocks: | |
| if key_block.name.startswith("Shape"): | |
| key_block.value = 0.0 | |
| for index, beta in enumerate(betas): | |
| name = f"Shape{index:03d}" | |
| if name not in key_blocks: | |
| raise KeyError(f"Missing SMPL-X shape key: {name}") | |
| key_block = key_blocks[name] | |
| value = float(beta) | |
| if value < key_block.slider_min: | |
| key_block.slider_min = value | |
| if value > key_block.slider_max: | |
| key_block.slider_max = value | |
| key_block.value = value | |
| bpy.context.view_layer.objects.active = obj | |
| bpy.ops.object.smplx_update_joint_locations("EXEC_DEFAULT") | |
| def set_expression(obj: bpy.types.Object, expr: np.ndarray | None) -> None: | |
| key_blocks = obj.data.shape_keys.key_blocks | |
| for key_block in key_blocks: | |
| if key_block.name.startswith("Exp"): | |
| key_block.value = 0.0 | |
| if expr is None: | |
| return | |
| for index, value in enumerate(np.asarray(expr).reshape(-1)): | |
| name = f"Exp{index:03d}" | |
| if name not in key_blocks: | |
| break | |
| key_block = key_blocks[name] | |
| value = float(value) | |
| if value < key_block.slider_min: | |
| key_block.slider_min = value | |
| if value > key_block.slider_max: | |
| key_block.slider_max = value | |
| key_block.value = value | |
| def set_pose_frame( | |
| obj: bpy.types.Object, | |
| armature: bpy.types.Object, | |
| pose_55: np.ndarray, | |
| transl: np.ndarray, | |
| expression: np.ndarray | None, | |
| set_pose_from_rodrigues, | |
| anim_format: str, | |
| ) -> None: | |
| bpy.context.view_layer.objects.active = obj | |
| set_expression(obj, expression) | |
| for bone_index, bone_name in enumerate(SMPLX_BONE_ORDER): | |
| bone = armature.pose.bones[bone_name] | |
| if bone.rotation_mode != "QUATERNION": | |
| bone.rotation_mode = "QUATERNION" | |
| if bone_name == "pelvis": | |
| bone.location = mathutils.Vector((float(transl[0]), float(transl[1]), float(transl[2]))) | |
| set_pose_from_rodrigues(armature, bone_name, pose_55[bone_index]) | |
| if anim_format == "AMASS": | |
| root = armature.pose.bones["root"] | |
| if root.rotation_mode != "QUATERNION": | |
| root.rotation_mode = "QUATERNION" | |
| root.rotation_quaternion = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(-90.0)) | |
| bpy.ops.object.smplx_set_poseshapes("EXEC_DEFAULT") | |
| bpy.context.view_layer.update() | |
| def evaluated_vertices(obj: bpy.types.Object) -> np.ndarray: | |
| depsgraph = bpy.context.evaluated_depsgraph_get() | |
| obj_eval = obj.evaluated_get(depsgraph) | |
| mesh = obj_eval.to_mesh() | |
| try: | |
| vertices = np.empty((len(mesh.vertices), 3), dtype=np.float32) | |
| mesh.vertices.foreach_get("co", vertices.reshape(-1)) | |
| return vertices | |
| finally: | |
| obj_eval.to_mesh_clear() | |
| def mesh_faces(obj: bpy.types.Object) -> np.ndarray: | |
| faces: list[list[int]] = [] | |
| for poly in obj.data.polygons: | |
| if len(poly.vertices) == 3: | |
| faces.append([int(v) for v in poly.vertices]) | |
| elif len(poly.vertices) == 4: | |
| v = [int(x) for x in poly.vertices] | |
| faces.append([v[0], v[1], v[2]]) | |
| faces.append([v[0], v[2], v[3]]) | |
| else: | |
| verts = [int(x) for x in poly.vertices] | |
| for i in range(1, len(verts) - 1): | |
| faces.append([verts[0], verts[i], verts[i + 1]]) | |
| return np.asarray(faces, dtype=np.int32) | |
| def to_obj_local(obj: bpy.types.Object, armature: bpy.types.Object, point_armature_local: mathutils.Vector) -> np.ndarray: | |
| world = armature.matrix_world @ point_armature_local | |
| local = obj.matrix_world.inverted() @ world | |
| return np.asarray((local.x, local.y, local.z), dtype=np.float32) | |
| def bone_head(obj: bpy.types.Object, armature: bpy.types.Object, name: str) -> np.ndarray | None: | |
| bone = armature.pose.bones.get(name) | |
| if bone is None: | |
| return None | |
| return to_obj_local(obj, armature, bone.head) | |
| def bone_tail(obj: bpy.types.Object, armature: bpy.types.Object, name: str) -> np.ndarray | None: | |
| bone = armature.pose.bones.get(name) | |
| if bone is None: | |
| return None | |
| return to_obj_local(obj, armature, bone.tail) | |
| def set_point(out: np.ndarray, mask: np.ndarray, idx: int, value: np.ndarray | None) -> None: | |
| if value is None: | |
| return | |
| out[idx] = value | |
| mask[idx] = 1 | |
| def vertex_point(vertices: np.ndarray, vertex_id: int) -> np.ndarray | None: | |
| if vertex_id < 0 or vertex_id >= vertices.shape[0]: | |
| return None | |
| return np.asarray(vertices[vertex_id], dtype=np.float32) | |
| def interp(a: np.ndarray | None, b: np.ndarray | None, t: float) -> np.ndarray | None: | |
| if a is None or b is None: | |
| return None | |
| return (1.0 - t) * a + t * b | |
| def add_offset(point: np.ndarray | None, offset: tuple[float, float, float]) -> np.ndarray | None: | |
| if point is None: | |
| return None | |
| return point + np.asarray(offset, dtype=np.float32) | |
| def finger_points( | |
| obj: bpy.types.Object, | |
| armature: bpy.types.Object, | |
| vertices: np.ndarray, | |
| side: str, | |
| finger: str, | |
| ) -> list[np.ndarray | None]: | |
| b1 = f"{side}_{finger}1" | |
| b2 = f"{side}_{finger}2" | |
| b3 = f"{side}_{finger}3" | |
| prefix = "l" if side == "left" else "r" | |
| return [ | |
| bone_head(obj, armature, b1), | |
| bone_head(obj, armature, b2), | |
| bone_head(obj, armature, b3), | |
| vertex_point(vertices, SMPLX_VERTEX_IDS[prefix + finger]), | |
| ] | |
| def fill_hand( | |
| out: np.ndarray, | |
| mask: np.ndarray, | |
| obj: bpy.types.Object, | |
| armature: bpy.types.Object, | |
| vertices: np.ndarray, | |
| side: str, | |
| start: int, | |
| ) -> None: | |
| wrist = bone_head(obj, armature, f"{side}_wrist") | |
| set_point(out, mask, start, wrist) | |
| offset = 1 | |
| # COCO hand order: thumb, index, middle, ring, pinky. | |
| for finger in ("thumb", "index", "middle", "ring", "pinky"): | |
| for point in finger_points(obj, armature, vertices, side, finger): | |
| set_point(out, mask, start + offset, point) | |
| offset += 1 | |
| def coco133_from_frame( | |
| obj: bpy.types.Object, | |
| armature: bpy.types.Object, | |
| vertices: np.ndarray, | |
| disable_face: bool, | |
| ) -> tuple[np.ndarray, np.ndarray]: | |
| out = np.zeros((133, 3), dtype=np.float32) | |
| mask = np.zeros((133,), dtype=np.uint8) | |
| pelvis = bone_head(obj, armature, "pelvis") | |
| neck = bone_head(obj, armature, "neck") | |
| head = bone_head(obj, armature, "head") | |
| l_sh = bone_head(obj, armature, "left_shoulder") | |
| r_sh = bone_head(obj, armature, "right_shoulder") | |
| l_hip = bone_head(obj, armature, "left_hip") | |
| r_hip = bone_head(obj, armature, "right_hip") | |
| l_ankle = bone_head(obj, armature, "left_ankle") | |
| r_ankle = bone_head(obj, armature, "right_ankle") | |
| l_foot = bone_head(obj, armature, "left_foot") | |
| r_foot = bone_head(obj, armature, "right_foot") | |
| eye_dx = 0.035 | |
| ear_dx = 0.075 | |
| set_point(out, mask, 0, vertex_point(vertices, SMPLX_VERTEX_IDS["nose"])) | |
| set_point(out, mask, 1, vertex_point(vertices, SMPLX_VERTEX_IDS["leye"])) | |
| set_point(out, mask, 2, vertex_point(vertices, SMPLX_VERTEX_IDS["reye"])) | |
| set_point(out, mask, 3, vertex_point(vertices, SMPLX_VERTEX_IDS["lear"])) | |
| set_point(out, mask, 4, vertex_point(vertices, SMPLX_VERTEX_IDS["rear"])) | |
| set_point(out, mask, 5, l_sh) | |
| set_point(out, mask, 6, r_sh) | |
| set_point(out, mask, 7, bone_head(obj, armature, "left_elbow")) | |
| set_point(out, mask, 8, bone_head(obj, armature, "right_elbow")) | |
| set_point(out, mask, 9, bone_head(obj, armature, "left_wrist")) | |
| set_point(out, mask, 10, bone_head(obj, armature, "right_wrist")) | |
| set_point(out, mask, 11, l_hip) | |
| set_point(out, mask, 12, r_hip) | |
| set_point(out, mask, 13, bone_head(obj, armature, "left_knee")) | |
| set_point(out, mask, 14, bone_head(obj, armature, "right_knee")) | |
| set_point(out, mask, 15, l_ankle) | |
| set_point(out, mask, 16, r_ankle) | |
| set_point(out, mask, 17, vertex_point(vertices, SMPLX_VERTEX_IDS["LBigToe"])) | |
| set_point(out, mask, 18, vertex_point(vertices, SMPLX_VERTEX_IDS["LSmallToe"])) | |
| set_point(out, mask, 19, vertex_point(vertices, SMPLX_VERTEX_IDS["LHeel"])) | |
| set_point(out, mask, 20, vertex_point(vertices, SMPLX_VERTEX_IDS["RBigToe"])) | |
| set_point(out, mask, 21, vertex_point(vertices, SMPLX_VERTEX_IDS["RSmallToe"])) | |
| set_point(out, mask, 22, vertex_point(vertices, SMPLX_VERTEX_IDS["RHeel"])) | |
| fill_hand(out, mask, obj, armature, vertices, "left", LEFT_HAND_SLICE.start) | |
| fill_hand(out, mask, obj, armature, vertices, "right", RIGHT_HAND_SLICE.start) | |
| if disable_face: | |
| out[COCO_WHOLEBODY_FACE_SLICE, :] = 0.0 | |
| mask[COCO_WHOLEBODY_FACE_SLICE] = 0 | |
| return out, mask | |
| def prepare_sequence(args: argparse.Namespace) -> None: | |
| args.out_dir.mkdir(parents=True, exist_ok=True) | |
| data = np.load(args.npz, allow_pickle=True) | |
| pose_raw = load_npz_array(data, args.pose_key, ["poses", "pose", "smplx_poses", "smplx_pose"]) | |
| if pose_raw is None: | |
| raise KeyError(f"Could not find pose key. Available keys: {list(data.keys())}") | |
| pose_55 = normalize_pose_55(pose_raw) | |
| if args.ignore_global_orient: | |
| pose_55 = pose_55.copy() | |
| pose_55[:, 0, :] = 0.0 | |
| if args.zero_spine1: | |
| pose_55 = pose_55.copy() | |
| pose_55[:, 3, :] = 0.0 | |
| num_source_frames = pose_55.shape[0] | |
| selected_source_indices = parse_frame_spec(args.frames, num_source_frames) | |
| transl = normalize_transl(load_npz_array(data, args.transl_key, ["trans", "transl", "translation", "translations"]), num_source_frames) | |
| expression = normalize_expression( | |
| load_npz_array(data, args.expression_key, ["smplx_expr", "expression", "expressions", "expr"]), | |
| num_source_frames, | |
| ) | |
| pose_55 = pose_55[selected_source_indices] | |
| transl = transl[selected_source_indices] | |
| if expression is not None: | |
| expression = expression[selected_source_indices] | |
| num_selected_source_frames = pose_55.shape[0] | |
| pose_55, transl, expression, selected_positions = interpolate_motion( | |
| pose_55=pose_55, | |
| transl=transl, | |
| expression=expression, | |
| factor=args.motion_slowdown, | |
| ) | |
| # Convert local selected-frame positions back to coordinates in the original NPZ. | |
| source_indices_np = np.asarray(selected_source_indices, dtype=np.float32) | |
| lo = np.floor(selected_positions).astype(np.int64) | |
| hi = np.minimum(lo + 1, len(selected_source_indices) - 1) | |
| alpha = selected_positions - lo.astype(np.float32) | |
| original_frame_positions = ((1.0 - alpha) * source_indices_np[lo] + alpha * source_indices_np[hi]) | |
| if args.max_output_frames < 0: | |
| raise ValueError("--max-output-frames must be >= 0") | |
| num_interpolated_frames_before_limit = pose_55.shape[0] | |
| if args.max_output_frames: | |
| limit = min(args.max_output_frames, pose_55.shape[0]) | |
| pose_55 = pose_55[:limit] | |
| transl = transl[:limit] | |
| original_frame_positions = original_frame_positions[:limit] | |
| if expression is not None: | |
| expression = expression[:limit] | |
| output_frame_indices = list(range(pose_55.shape[0])) | |
| gender = resolve_gender(data, args.gender) | |
| betas = choose_betas( | |
| data=data, | |
| betas_key=args.betas_key, | |
| num_betas=args.num_betas, | |
| random_betas=args.random_betas, | |
| ignore_input_betas=args.ignore_input_betas, | |
| beta_seed=args.beta_seed, | |
| beta_std=args.beta_std, | |
| beta_clip=args.beta_clip, | |
| ) | |
| framerate = load_npz_array(data, args.framerate_key, ["mocap_framerate", "mocap_frame_rate"]) | |
| if framerate is None: | |
| mocap_framerate = 30 | |
| else: | |
| mocap_framerate = int(np.asarray(framerate).reshape(-1)[0]) | |
| addon_npz_path = args.out_dir / "_addon_import_sequence.npz" | |
| write_addon_npz( | |
| source_data=data, | |
| out_path=addon_npz_path, | |
| pose_55=pose_55, | |
| transl=transl, | |
| expression=expression, | |
| betas=betas, | |
| gender=gender, | |
| mocap_framerate=mocap_framerate, | |
| ) | |
| obj, armature = import_addon_animation( | |
| addon_npz_path, | |
| target_framerate=mocap_framerate, | |
| model_variant=args.model_variant, | |
| uv_version=args.uv_version, | |
| ) | |
| faces = mesh_faces(obj) | |
| vertices_all: list[np.ndarray] = [] | |
| coco_all: list[np.ndarray] = [] | |
| mask_all: list[np.ndarray] = [] | |
| for out_frame_idx in output_frame_indices: | |
| print( | |
| f"[prepare] frame {out_frame_idx + 1}/{len(output_frame_indices)} " | |
| f"source_position={original_frame_positions[out_frame_idx]:.4f}" | |
| ) | |
| bpy.context.scene.frame_set(out_frame_idx + 1) | |
| set_expression(obj, None if expression is None else expression[out_frame_idx]) | |
| bpy.context.view_layer.update() | |
| frame_vertices = evaluated_vertices(obj) | |
| vertices_all.append(frame_vertices) | |
| coco, mask = coco133_from_frame(obj, armature, frame_vertices, disable_face=args.disable_face) | |
| coco_all.append(coco) | |
| mask_all.append(mask) | |
| vertices_np = np.stack(vertices_all, axis=0).astype(np.float32) | |
| coco_np = np.stack(coco_all, axis=0).astype(np.float32) | |
| mask_np = np.stack(mask_all, axis=0).astype(np.uint8) | |
| normalization_offset = np.zeros((3,), dtype=np.float32) | |
| if args.center_xy: | |
| xy_min = vertices_np[:, :, :2].reshape(-1, 2).min(axis=0) | |
| xy_max = vertices_np[:, :, :2].reshape(-1, 2).max(axis=0) | |
| normalization_offset[:2] = (xy_min + xy_max) * 0.5 | |
| if args.ground_plane: | |
| normalization_offset[2] = vertices_np[:, :, 2].min() | |
| vertices_np = vertices_np - normalization_offset[None, None, :] | |
| coco_np = coco_np - normalization_offset[None, None, :] | |
| coco_np[:, COCO_WHOLEBODY_FACE_SLICE, :] = 0.0 | |
| np.save(args.out_dir / "vertices.npy", vertices_np) | |
| np.save(args.out_dir / "faces.npy", faces) | |
| np.save(args.out_dir / "coco133_3d.npy", coco_np) | |
| np.save(args.out_dir / "coco133_mask.npy", mask_np) | |
| meta = { | |
| "source_npz": str(args.npz), | |
| "num_source_frames": int(num_source_frames), | |
| "num_selected_source_frames": int(num_selected_source_frames), | |
| "num_interpolated_frames_before_limit": int(num_interpolated_frames_before_limit), | |
| "num_frames": int(vertices_np.shape[0]), | |
| "source_frame_indices": selected_source_indices, | |
| "output_source_frame_positions": original_frame_positions, | |
| "motion_slowdown": int(args.motion_slowdown), | |
| "max_output_frames": int(args.max_output_frames), | |
| "output_fps": int(args.output_fps), | |
| "num_vertices": int(vertices_np.shape[1]), | |
| "num_faces": int(faces.shape[0]), | |
| "keypoint_format": "coco_wholebody_133", | |
| "coco_source": "smplx_blender_addon_armature_plus_official_smplx_vertex_ids_v2", | |
| "smplx_vertex_ids_source": "vchoutas/smplx vertex_ids.py", | |
| "smplx_vertex_ids": SMPLX_VERTEX_IDS, | |
| "face_disabled": bool(args.disable_face), | |
| "pose_shape": list(pose_55.shape), | |
| "transl_shape": list(transl.shape), | |
| "expression_shape": list(expression.shape) if expression is not None else None, | |
| "gender": gender, | |
| "betas": betas, | |
| "betas_source": "random" if (args.random_betas or args.ignore_input_betas) else "input_or_zero", | |
| "beta_seed": args.beta_seed, | |
| "beta_std": args.beta_std, | |
| "beta_clip": args.beta_clip, | |
| "addon_dir": str(args.addon_dir), | |
| "model_variant": args.model_variant, | |
| "uv_version": args.uv_version, | |
| "anim_format": "SMPL-X", | |
| "ignore_global_orient": bool(args.ignore_global_orient), | |
| "zero_spine1": bool(args.zero_spine1), | |
| "addon_import_npz": str(addon_npz_path), | |
| "addon_import_operator": "bpy.ops.object.smplx_add_animation", | |
| "keyframe_corrective_pose_weights": True, | |
| "normalization": { | |
| "center_xy": bool(args.center_xy), | |
| "ground_plane": bool(args.ground_plane), | |
| "offset_subtracted": normalization_offset, | |
| }, | |
| "mocap_framerate": mocap_framerate, | |
| "notes": "Selected source poses are temporally interpolated before the official SMPL-X Blender addon import; renderer and COCO consume the resulting capped sequence without further interpolation.", | |
| } | |
| with open(args.out_dir / "meta.json", "w", encoding="utf-8") as f: | |
| json.dump(meta, f, indent=2, default=jsonable) | |
| print(f"[OK] Saved Blender-addon sequence cache to {args.out_dir}") | |
| def main() -> None: | |
| args = parse_blender_args() | |
| enable_addon(args.addon_dir) | |
| prepare_sequence(args) | |
| if __name__ == "__main__": | |
| main() | |