#!/usr/bin/env python3 """ Lightweight AnchorWorld human-pose and scene-pose visualizer. Dependencies: numpy, torch, smplx, ffmpeg The human is rendered as a 22-joint SMPL-X skeleton. Scene poses are rendered as camera frustums in the same coordinate system. No GVHMR, PyTorch3D, OpenCV, or custom renderer is required. """ import argparse import math import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple import numpy as np SMPL22_PARENTS = [ -1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19, ] LEFT_JOINTS = {1, 4, 7, 10, 13, 16, 18, 20} RIGHT_JOINTS = {2, 5, 8, 11, 14, 17, 19, 21} CAMERA_COLORS = [ (245, 90, 85), (80, 200, 120), (90, 150, 245), (235, 180, 70), (190, 105, 235), (70, 205, 215), ] def import_torch(): try: import torch except ImportError as exc: raise RuntimeError( "PyTorch is required. Install dependencies with: " "pip install -r requirements-visualization.txt" ) from exc return torch def load_file(path: Path) -> Any: if not path.is_file(): raise FileNotFoundError(f"File not found: {path}") if path.suffix.lower() in {".pt", ".pth"}: torch = import_torch() try: return torch.load(path, map_location="cpu", weights_only=False) except TypeError: return torch.load(path, map_location="cpu") if path.suffix.lower() == ".npy": return np.load(path, allow_pickle=False) raise ValueError(f"Unsupported file format: {path.suffix}. Use .pt or .npy.") def to_numpy(value: Any) -> np.ndarray: if isinstance(value, np.ndarray): return value if hasattr(value, "detach"): return value.detach().cpu().numpy() return np.asarray(value) def expand_frames(tensor, frame_count: int, name: str): if tensor.shape[0] == frame_count: return tensor if tensor.shape[0] == 1: return tensor.expand(frame_count, *tensor.shape[1:]) raise ValueError( f"{name} has {tensor.shape[0]} frames; expected 1 or {frame_count}." ) def resolve_smplx_root(model_dir: Path) -> Path: """Accept either the model root or the root/smplx directory.""" direct_model = model_dir / "SMPLX_NEUTRAL.npz" nested_model = model_dir / "smplx" / "SMPLX_NEUTRAL.npz" if nested_model.is_file(): return model_dir if direct_model.is_file() and model_dir.name.lower() == "smplx": return model_dir.parent raise FileNotFoundError( "SMPLX_NEUTRAL.npz was not found. Expected either:\n" f" {nested_model}\n" f"or:\n {direct_model}" ) def joints_from_smplx(params: Dict[str, Any], model_dir: Path) -> np.ndarray: torch = import_torch() try: import smplx except ImportError as exc: raise RuntimeError("Install SMPL-X with: pip install smplx") from exc if "global_orient" not in params or "body_pose" not in params: raise KeyError("SMPL-X parameters must contain global_orient and body_pose.") global_orient = torch.as_tensor(params["global_orient"]).float() body_pose = torch.as_tensor(params["body_pose"]).float() if global_orient.ndim == 1: global_orient = global_orient.unsqueeze(0) if body_pose.ndim == 1: body_pose = body_pose.unsqueeze(0) frame_count = max(global_orient.shape[0], body_pose.shape[0]) global_orient = expand_frames(global_orient, frame_count, "global_orient") body_pose = expand_frames(body_pose, frame_count, "body_pose") matrix_pose = ( global_orient.shape[-2:] == (3, 3) and body_pose.shape[-2:] == (3, 3) ) if matrix_pose: if global_orient.ndim == 3: global_orient = global_orient.unsqueeze(1) if body_pose.ndim != 4: raise ValueError("Matrix body_pose must have shape [F, J, 3, 3].") pose2rot = False else: if global_orient.ndim == 3 and global_orient.shape[1:] == (1, 3): global_orient = global_orient[:, 0] if body_pose.ndim == 3 and body_pose.shape[-1] == 3: body_pose = body_pose.reshape(frame_count, -1) if global_orient.shape[-1] != 3 or body_pose.ndim != 2: raise ValueError("Invalid axis-angle SMPL-X parameter shape.") pose2rot = True transl = torch.as_tensor( params.get("transl", torch.zeros(frame_count, 3)) ).float() if transl.ndim == 1: transl = transl.unsqueeze(0) transl = expand_frames(transl, frame_count, "transl") betas = torch.as_tensor( params.get("betas", torch.zeros(frame_count, 10)) ).float() if betas.ndim == 1: betas = betas.unsqueeze(0) if betas.ndim > 2: betas = betas.reshape(betas.shape[0], -1) betas = expand_frames(betas, frame_count, "betas") model_root = resolve_smplx_root(model_dir) model = smplx.create( str(model_root), model_type="smplx", gender="neutral", ext="npz", use_pca=False, num_betas=betas.shape[-1], batch_size=frame_count, ) with torch.no_grad(): output = model( global_orient=global_orient, body_pose=body_pose, betas=betas, transl=transl, pose2rot=pose2rot, return_verts=False, ) return output.joints[:, :22].cpu().numpy().astype(np.float32) def load_human_joints(path: Path, model_dir: Optional[Path]) -> np.ndarray: data = load_file(path) if not isinstance(data, dict): joints = to_numpy(data) else: joints = None for key in ("joints_global", "global_joints", "joints", "pred_joints"): if key in data: joints = to_numpy(data[key]) break if joints is None: if model_dir is None: raise ValueError( "--smplx-model-dir is required for SMPL-X parameter files." ) params = data.get("smpl_params_global", data) if not isinstance(params, dict): raise ValueError("Could not find smpl_params_global.") joints = joints_from_smplx(params, model_dir) if joints.ndim != 3 or joints.shape[-1] != 3: raise ValueError("Human joints must have shape [frames, joints, 3].") if joints.shape[1] < 22: raise ValueError("At least 22 SMPL joints are required.") return joints[:, :22].astype(np.float32) def extract_scene_array(data: Any) -> np.ndarray: if not isinstance(data, dict): return to_numpy(data) for key in ( "scene_pose", "scene_poses", "camera_pose", "camera_poses", "extrinsics", "poses", "c2w", "c2ws", ): if key in data: return to_numpy(data[key]) arrays = [ value for value in data.values() if isinstance(value, np.ndarray) or hasattr(value, "shape") ] if len(arrays) == 1: return to_numpy(arrays[0]) raise ValueError("Could not identify the scene-pose array.") def normalize_scene_shape(array: np.ndarray) -> np.ndarray: """ Return camera poses in [views, frames, 3, 4]. Supported inputs: [3,4], [4,4], [12] [F,3,4], [V,3,4], [F,12] [V,F,3,4], [V,F,4,4], [V,F,12] """ poses = np.asarray(array, dtype=np.float32) if poses.shape[-2:] == (4, 4): poses = poses[..., :3, :4] elif poses.shape[-1:] == (12,): poses = poses.reshape(*poses.shape[:-1], 3, 4) if poses.shape[-2:] != (3, 4): raise ValueError(f"Unsupported scene-pose shape: {poses.shape}") if poses.ndim == 2: return poses[None, None] if poses.ndim == 3: # Up to 16 matrices are treated as static multi-view cameras. return poses[:, None] if poses.shape[0] <= 16 else poses[None] if poses.ndim == 4: # AnchorWorld multi-view files are stored view-first: [V, F, 3, 4]. return poses raise ValueError(f"Unsupported scene-pose shape: {poses.shape}") def w2c_to_c2w(poses: np.ndarray) -> np.ndarray: rotation = poses[..., :3] translation = poses[..., 3] rotation_inv = np.swapaxes(rotation, -1, -2) translation_inv = -np.einsum( "...ij,...j->...i", rotation_inv, translation ) return np.concatenate( [rotation_inv, translation_inv[..., None]], axis=-1 ) def load_scene_poses(path: Path, convention: str) -> np.ndarray: poses = normalize_scene_shape(extract_scene_array(load_file(path))) if convention == "w2c": poses = w2c_to_c2w(poses) return poses.astype(np.float32) def scale_camera_distance( poses: np.ndarray, human_center: np.ndarray, distance_scale: float, ) -> np.ndarray: """ Move camera centers toward or away from the human without changing rotation. scale=1.0: original camera positions scale=0.5: half the original distance to the human center scale=0.0: camera centers at the human center scale>1.0: cameras move farther away """ scaled = poses.copy() camera_centers = scaled[..., :3, 3] scaled[..., :3, 3] = ( human_center + distance_scale * (camera_centers - human_center) ) return scaled def unit(vector: np.ndarray) -> np.ndarray: norm = float(np.linalg.norm(vector)) if norm < 1e-8: raise ValueError("Cannot normalize a zero vector.") return vector / norm def view_basis(azimuth_degrees: float, elevation_degrees: float): azimuth = math.radians(azimuth_degrees) elevation = math.radians(elevation_degrees) eye_direction = np.array( [ math.cos(elevation) * math.sin(azimuth), math.sin(elevation), math.cos(elevation) * math.cos(azimuth), ], dtype=np.float32, ) forward = unit(-eye_direction) world_up = np.array([0.0, 1.0, 0.0], dtype=np.float32) right = unit(np.cross(forward, world_up)) up = unit(np.cross(right, forward)) return right, up def project( points: np.ndarray, center: np.ndarray, right: np.ndarray, up: np.ndarray, scale: float, width: int, height: int, ) -> np.ndarray: relative = points - center pixels = np.empty((len(points), 2), dtype=np.float32) pixels[:, 0] = width * 0.5 + (relative @ right) * scale pixels[:, 1] = height * 0.52 - (relative @ up) * scale return np.rint(pixels).astype(np.int32) def draw_disc( image: np.ndarray, center: Sequence[int], radius: int, color: Tuple[int, int, int], ) -> None: x, y = int(center[0]), int(center[1]) height, width = image.shape[:2] x0, x1 = max(0, x - radius), min(width, x + radius + 1) y0, y1 = max(0, y - radius), min(height, y + radius + 1) if x0 >= x1 or y0 >= y1: return yy, xx = np.ogrid[y0:y1, x0:x1] mask = (xx - x) ** 2 + (yy - y) ** 2 <= radius ** 2 image[y0:y1, x0:x1][mask] = color def draw_line( image: np.ndarray, start: Sequence[int], end: Sequence[int], color: Tuple[int, int, int], width: int, ) -> None: x0, y0 = int(start[0]), int(start[1]) x1, y1 = int(end[0]), int(end[1]) steps = max(abs(x1 - x0), abs(y1 - y0), 1) + 1 xs = np.rint(np.linspace(x0, x1, steps)).astype(np.int32) ys = np.rint(np.linspace(y0, y1, steps)).astype(np.int32) for x, y in zip(xs, ys): draw_disc(image, (x, y), max(0, width // 2), color) def camera_frustum(depth: float, aspect: float = 16.0 / 9.0) -> np.ndarray: half_height = depth * 0.22 half_width = half_height * aspect return np.array( [ [0.0, 0.0, 0.0], [-half_width, -half_height, depth], [half_width, -half_height, depth], [half_width, half_height, depth], [-half_width, half_height, depth], ], dtype=np.float32, ) def transform(points: np.ndarray, c2w: np.ndarray) -> np.ndarray: return points @ c2w[:, :3].T + c2w[:, 3] def scene_frame_index(human_index: int, human_frames: int, scene_frames: int) -> int: if human_frames <= 1 or scene_frames <= 1: return 0 return int(round(human_index / (human_frames - 1) * (scene_frames - 1))) def ground_grid( center: np.ndarray, ground_y: float, extent: float, ) -> List[Tuple[np.ndarray, np.ndarray]]: lines = [] for offset in np.linspace(-extent, extent, 11): lines.append(( np.array([center[0] - extent, ground_y, center[2] + offset]), np.array([center[0] + extent, ground_y, center[2] + offset]), )) lines.append(( np.array([center[0] + offset, ground_y, center[2] - extent]), np.array([center[0] + offset, ground_y, center[2] + extent]), )) return lines def render_frame( joints: np.ndarray, scene_poses: np.ndarray, center: np.ndarray, right: np.ndarray, up: np.ndarray, image_scale: float, width: int, height: int, grid: List[Tuple[np.ndarray, np.ndarray]], frustum: np.ndarray, ) -> np.ndarray: image = np.full((height, width, 3), (18, 20, 26), dtype=np.uint8) for start, end in grid: pixels = project( np.stack([start, end]), center, right, up, image_scale, width, height, ) draw_line(image, pixels[0], pixels[1], (50, 55, 65), 1) edges = [ (0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4), (4, 1), ] for view_index, pose in enumerate(scene_poses): color = CAMERA_COLORS[view_index % len(CAMERA_COLORS)] pixels = project( transform(frustum, pose), center, right, up, image_scale, width, height, ) for start, end in edges: draw_line(image, pixels[start], pixels[end], color, 3) draw_line(image, pixels[3], pixels[4], (80, 245, 110), 4) draw_disc(image, pixels[0], 5, color) joint_pixels = project( joints, center, right, up, image_scale, width, height ) for joint_index, parent_index in enumerate(SMPL22_PARENTS): if parent_index < 0: continue if joint_index in LEFT_JOINTS: color = (75, 205, 245) elif joint_index in RIGHT_JOINTS: color = (245, 155, 70) else: color = (230, 235, 245) draw_line( image, joint_pixels[parent_index], joint_pixels[joint_index], color, 5, ) for joint_index, pixel in enumerate(joint_pixels): if joint_index in LEFT_JOINTS: color = (75, 205, 245) elif joint_index in RIGHT_JOINTS: color = (245, 155, 70) else: color = (240, 240, 245) draw_disc(image, pixel, 5, color) return image class VideoWriter: def __init__(self, output: Path, width: int, height: int, fps: float): ffmpeg = shutil.which("ffmpeg") if ffmpeg is None: raise RuntimeError("ffmpeg is required but was not found.") output.parent.mkdir(parents=True, exist_ok=True) command = [ ffmpeg, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", str(output), ] self.process = subprocess.Popen( command, stdin=subprocess.PIPE, stderr=subprocess.PIPE ) def write(self, frame: np.ndarray) -> None: if self.process.stdin is None: raise RuntimeError("ffmpeg input pipe is unavailable.") self.process.stdin.write(np.ascontiguousarray(frame).tobytes()) def close(self) -> None: if self.process.stdin is not None: self.process.stdin.close() stderr = self.process.stderr.read() if self.process.stderr else b"" self.process.wait() if self.process.returncode: raise RuntimeError(stderr.decode("utf-8", errors="replace")) def visualize(args: argparse.Namespace) -> None: if args.width % 2 or args.height % 2: raise ValueError("--width and --height must be even.") if args.stride < 1: raise ValueError("--stride must be at least 1.") if args.camera_distance_scale < 0: raise ValueError("--camera-distance-scale cannot be negative.") human_path = Path(args.human_pose).expanduser().resolve() scene_path = Path(args.scene_pose).expanduser().resolve() output_path = Path(args.output).expanduser().resolve() model_dir = ( Path(args.smplx_model_dir).expanduser().resolve() if args.smplx_model_dir else None ) print(f"Loading human pose: {human_path}") joints = load_human_joints(human_path, model_dir) print(f"Loading scene pose: {scene_path}") scene_poses = load_scene_poses(scene_path, args.scene_convention) frame_indices = list(range(0, len(joints), args.stride)) if args.max_frames is not None: frame_indices = frame_indices[:args.max_frames] if not frame_indices: raise ValueError("No frames selected.") selected_joints = joints[frame_indices] human_center = ( selected_joints.reshape(-1, 3).min(axis=0) + selected_joints.reshape(-1, 3).max(axis=0) ) * 0.5 scene_poses = scale_camera_distance( scene_poses, human_center, args.camera_distance_scale ) camera_centers = scene_poses[..., :3, 3].reshape(-1, 3) bounds = np.concatenate( [selected_joints.reshape(-1, 3), camera_centers], axis=0 ) view_center = (bounds.min(axis=0) + bounds.max(axis=0)) * 0.5 radius = max( float(np.linalg.norm(bounds - view_center, axis=1).max()), 1.0, ) image_scale = 0.43 * min(args.width, args.height) / radius * args.zoom human_size = float(np.max( selected_joints.reshape(-1, 3).max(axis=0) - selected_joints.reshape(-1, 3).min(axis=0) )) frustum = camera_frustum(max(0.15, human_size * args.frustum_scale)) right, up = view_basis(args.azimuth, args.elevation) grid = ground_grid( view_center, float(selected_joints[..., 1].min()), radius, ) print( f"Rendering {len(frame_indices)} frames, " f"{scene_poses.shape[0]} scene views, " f"camera distance scale={args.camera_distance_scale}" ) writer = VideoWriter(output_path, args.width, args.height, args.fps) try: for output_index, human_index in enumerate(frame_indices): current_scene_poses = [] for view_index in range(scene_poses.shape[0]): scene_index = scene_frame_index( human_index, len(joints), scene_poses.shape[1] ) current_scene_poses.append(scene_poses[view_index, scene_index]) frame = render_frame( joints[human_index], np.stack(current_scene_poses), view_center, right, up, image_scale, args.width, args.height, grid, frustum, ) writer.write(frame) if output_index == 0 or (output_index + 1) % 10 == 0: print(f" rendered {output_index + 1}/{len(frame_indices)}") finally: writer.close() print(f"Saved: {output_path}") def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Visualize AnchorWorld human pose and scene cameras." ) parser.add_argument("--human-pose", required=True) parser.add_argument("--scene-pose", required=True) parser.add_argument("--smplx-model-dir") parser.add_argument("--output", default="pose_scene_preview.mp4") parser.add_argument( "--scene-convention", choices=("c2w", "w2c"), default="c2w", ) parser.add_argument( "--camera-distance-scale", type=float, default=1.0, help=( "Scale camera distance around the human center. " "1.0 keeps original positions; 0.5 halves the distance." ), ) parser.add_argument("--fps", type=float, default=15.0) parser.add_argument("--width", type=int, default=960) parser.add_argument("--height", type=int, default=720) parser.add_argument("--stride", type=int, default=1) parser.add_argument("--max-frames", type=int) parser.add_argument("--azimuth", type=float, default=-55.0) parser.add_argument("--elevation", type=float, default=25.0) parser.add_argument("--zoom", type=float, default=1.0) parser.add_argument("--frustum-scale", type=float, default=0.35) return parser def main() -> int: parser = build_parser() try: visualize(parser.parse_args()) except (KeyError, RuntimeError, ValueError, FileNotFoundError) as exc: parser.error(str(exc)) return 0 if __name__ == "__main__": sys.exit(main())