| """ |
| Unified motion visualization: npz → stick figure video/gif. |
| |
| Supports all datasets (human + animal, any joint count). |
| Outputs: MP4 video or GIF for human/VLM review. |
| |
| Usage: |
| # Render single motion |
| python scripts/render_motion.py --input data/processed/humanml3d/motions/000001.npz --output results/videos/ |
| |
| # Batch render dataset |
| python scripts/render_motion.py --dataset humanml3d --num 20 --output results/videos/humanml3d/ |
| |
| # Render with text overlay |
| python scripts/render_motion.py --input ... --output ... --show_text --show_skeleton_info |
| """ |
|
|
| import sys |
| import os |
| import argparse |
| from pathlib import Path |
| import numpy as np |
| import matplotlib |
| matplotlib.use('Agg') |
| import matplotlib.pyplot as plt |
| from mpl_toolkits.mplot3d import Axes3D |
| from matplotlib.animation import FuncAnimation, PillowWriter |
| import matplotlib.patches as mpatches |
|
|
| project_root = Path(__file__).parent.parent |
| sys.path.insert(0, str(project_root)) |
|
|
| from src.data.skeleton_graph import SkeletonGraph |
|
|
| SIDE_COLORS = {'left': '#e74c3c', 'right': '#3498db', 'center': '#555555'} |
|
|
|
|
| def load_motion_and_skeleton(npz_path: Path, dataset_path: Path = None): |
| """Load motion data and its skeleton.""" |
| d = dict(np.load(npz_path, allow_pickle=True)) |
| T = int(d['num_frames']) |
|
|
| |
| skel_data = None |
| if dataset_path: |
| |
| species = str(d.get('species', '')) |
| if species: |
| sp_path = dataset_path / 'skeletons' / f'{species}.npz' |
| if sp_path.exists(): |
| skel_data = dict(np.load(sp_path, allow_pickle=True)) |
| if skel_data is None: |
| main_skel = dataset_path / 'skeleton.npz' |
| if main_skel.exists(): |
| skel_data = dict(np.load(main_skel, allow_pickle=True)) |
|
|
| if skel_data is None: |
| |
| parent = npz_path.parent.parent |
| main_skel = parent / 'skeleton.npz' |
| if main_skel.exists(): |
| skel_data = dict(np.load(main_skel, allow_pickle=True)) |
|
|
| skeleton = SkeletonGraph.from_dict(skel_data) if skel_data else None |
| canon = [str(n) for n in skel_data.get('canonical_names', [])] if skel_data else [] |
|
|
| return d, T, skeleton, canon |
|
|
|
|
| def render_motion_to_gif( |
| npz_path: Path, |
| output_path: Path, |
| dataset_path: Path = None, |
| fps: int = 20, |
| show_text: bool = True, |
| show_skeleton_info: bool = True, |
| figsize: tuple = (10, 8), |
| frame_skip: int = 1, |
| view_angles: tuple = (25, -60), |
| ): |
| """Render a single motion npz to an animated GIF.""" |
| d, T, skeleton, canon = load_motion_and_skeleton(npz_path, dataset_path) |
|
|
| joint_positions = d['joint_positions'][:T] |
| J = joint_positions.shape[1] |
| parents = skeleton.parent_indices if skeleton else [-1] + [0] * (J - 1) |
| side_tags = skeleton.side_tags if skeleton else ['center'] * J |
|
|
| |
| frames = range(0, T, frame_skip) |
| n_frames = len(list(frames)) |
|
|
| |
| all_pos = joint_positions.reshape(-1, 3) |
| center = all_pos.mean(axis=0) |
| span = max(all_pos.max(axis=0) - all_pos.min(axis=0)) / 2 + 0.1 |
|
|
| |
| texts = str(d.get('texts', '')) |
| first_text = texts.split('|||')[0] if texts else '' |
| species = str(d.get('species', '')) |
| skeleton_id = str(d.get('skeleton_id', '')) |
| motion_id = npz_path.stem |
|
|
| |
| fig = plt.figure(figsize=figsize) |
| ax = fig.add_subplot(111, projection='3d') |
|
|
| def update(frame_idx): |
| ax.clear() |
| fi = list(frames)[frame_idx] |
| pos = joint_positions[fi] |
|
|
| |
| for j in range(J): |
| p = parents[j] |
| if p >= 0 and p < J: |
| ax.plot3D( |
| [pos[j, 0], pos[p, 0]], |
| [pos[j, 2], pos[p, 2]], |
| [pos[j, 1], pos[p, 1]], |
| color='#bdc3c7', linewidth=2, zorder=1, |
| ) |
|
|
| |
| for j in range(J): |
| color = SIDE_COLORS.get(side_tags[j] if j < len(side_tags) else 'center', '#555') |
| ax.scatter3D( |
| [pos[j, 0]], [pos[j, 2]], [pos[j, 1]], |
| color=color, s=25, zorder=3, edgecolors='black', linewidths=0.3, |
| ) |
|
|
| |
| ground_y = joint_positions[:, :, 1].min() - 0.02 |
| gx = np.array([center[0] - span, center[0] + span]) |
| gz = np.array([center[2] - span, center[2] + span]) |
| gx, gz = np.meshgrid(gx, gz) |
| gy = np.full_like(gx, ground_y) |
| ax.plot_surface(gx, gz, gy, alpha=0.1, color='green') |
|
|
| |
| traj = joint_positions[:fi+1, 0, :] |
| if len(traj) > 1: |
| ax.plot3D(traj[:, 0], traj[:, 2], np.full(len(traj), ground_y), |
| color='blue', alpha=0.3, linewidth=1) |
|
|
| |
| ax.set_xlim(center[0] - span, center[0] + span) |
| ax.set_ylim(center[2] - span, center[2] + span) |
| ax.set_zlim(center[1] - span, center[1] + span) |
| ax.set_xlabel('X') |
| ax.set_ylabel('Z') |
| ax.set_zlabel('Y') |
| ax.view_init(elev=view_angles[0], azim=view_angles[1]) |
|
|
| |
| title_parts = [] |
| if show_skeleton_info: |
| info = f'{skeleton_id}' |
| if species: |
| info = f'{species}' |
| title_parts.append(f'{info} ({J}j)') |
| title_parts.append(f'frame {fi}/{T}') |
| if show_text and first_text: |
| |
| txt = first_text[:60] + ('...' if len(first_text) > 60 else '') |
| title_parts.append(f'"{txt}"') |
| ax.set_title('\n'.join(title_parts), fontsize=9) |
|
|
| anim = FuncAnimation(fig, update, frames=n_frames, interval=1000 // (fps // frame_skip)) |
|
|
| |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| suffix = output_path.suffix.lower() |
| if suffix == '.gif': |
| anim.save(str(output_path), writer=PillowWriter(fps=fps // frame_skip)) |
| elif suffix == '.mp4': |
| try: |
| anim.save(str(output_path), writer='ffmpeg', fps=fps // frame_skip) |
| except Exception: |
| |
| gif_path = output_path.with_suffix('.gif') |
| anim.save(str(gif_path), writer=PillowWriter(fps=fps // frame_skip)) |
| output_path = gif_path |
| else: |
| anim.save(str(output_path), writer=PillowWriter(fps=fps // frame_skip)) |
|
|
| plt.close(fig) |
| return output_path |
|
|
|
|
| def render_multi_view( |
| npz_path: Path, |
| output_path: Path, |
| dataset_path: Path = None, |
| n_frames: int = 8, |
| ): |
| """Render a multi-frame overview image (static, for quick review).""" |
| d, T, skeleton, canon = load_motion_and_skeleton(npz_path, dataset_path) |
|
|
| joint_positions = d['joint_positions'][:T] |
| J = joint_positions.shape[1] |
| parents = skeleton.parent_indices if skeleton else [-1] + [0] * (J - 1) |
| side_tags = skeleton.side_tags if skeleton else ['center'] * J |
|
|
| frame_indices = np.linspace(0, T - 1, n_frames, dtype=int) |
| colors = plt.cm.viridis(np.linspace(0, 1, n_frames)) |
|
|
| texts = str(d.get('texts', '')) |
| first_text = texts.split('|||')[0][:80] if texts else '' |
| species = str(d.get('species', '')) |
| skeleton_id = str(d.get('skeleton_id', '')) |
|
|
| fig = plt.figure(figsize=(16, 6)) |
|
|
| |
| ax1 = fig.add_subplot(121, projection='3d') |
| for idx, fi in enumerate(frame_indices): |
| pos = joint_positions[fi] |
| alpha = 0.3 + 0.7 * (idx / max(n_frames - 1, 1)) |
| for j in range(J): |
| p = parents[j] |
| if p >= 0 and p < J: |
| ax1.plot3D([pos[j, 0], pos[p, 0]], [pos[j, 2], pos[p, 2]], |
| [pos[j, 1], pos[p, 1]], color=colors[idx], alpha=alpha, linewidth=1.5) |
|
|
| all_pos = joint_positions.reshape(-1, 3) |
| mid = all_pos.mean(axis=0) |
| sp = max(all_pos.max(axis=0) - all_pos.min(axis=0)) / 2 + 0.1 |
| ax1.set_xlim(mid[0]-sp, mid[0]+sp); ax1.set_ylim(mid[2]-sp, mid[2]+sp); ax1.set_zlim(mid[1]-sp, mid[1]+sp) |
| ax1.set_title(f'{species or skeleton_id} ({J}j, {T} frames)\n{first_text}', fontsize=9) |
| ax1.view_init(25, -60) |
|
|
| |
| ax2 = fig.add_subplot(222) |
| root = d['root_position'][:T] |
| ax2.plot(root[:, 0], root[:, 2], 'b-', linewidth=1) |
| ax2.plot(root[0, 0], root[0, 2], 'go', ms=6, label='start') |
| ax2.plot(root[-1, 0], root[-1, 2], 'ro', ms=6, label='end') |
| ax2.set_title('Root trajectory (top)', fontsize=8) |
| ax2.set_aspect('equal') |
| ax2.legend(fontsize=7) |
| ax2.grid(True, alpha=0.3) |
|
|
| ax3 = fig.add_subplot(224) |
| vel = d['velocities'][:T] |
| mean_vel = np.linalg.norm(vel, axis=-1).mean(axis=1) |
| ax3.plot(mean_vel, 'b-', alpha=0.7, linewidth=1) |
| fc = d['foot_contact'][:T] |
| if fc.shape[1] >= 4: |
| ax3.fill_between(range(T), 0, fc[:, :2].max(axis=1) * mean_vel.max() * 0.3, |
| alpha=0.2, color='red', label='L foot') |
| ax3.fill_between(range(T), 0, fc[:, 2:].max(axis=1) * mean_vel.max() * 0.3, |
| alpha=0.2, color='green', label='R foot') |
| ax3.set_title('Velocity + foot contact', fontsize=8) |
| ax3.legend(fontsize=7) |
| ax3.grid(True, alpha=0.3) |
|
|
| plt.tight_layout() |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| plt.savefig(output_path, dpi=120, bbox_inches='tight') |
| plt.close() |
| return output_path |
|
|
|
|
| def batch_render( |
| dataset_id: str, |
| output_dir: Path, |
| num: int = 20, |
| mode: str = 'overview', |
| frame_skip: int = 2, |
| ): |
| """Batch render samples from a dataset.""" |
| base = project_root / 'data' / 'processed' / dataset_id |
| mdir = base / 'motions' |
| files = sorted(os.listdir(mdir)) |
|
|
| |
| indices = np.linspace(0, len(files) - 1, min(num, len(files)), dtype=int) |
| selected = [files[i] for i in indices] |
|
|
| output_dir.mkdir(parents=True, exist_ok=True) |
| rendered = 0 |
|
|
| for f in selected: |
| npz_path = mdir / f |
| name = f.replace('.npz', '') |
|
|
| if mode in ('overview', 'both'): |
| out = output_dir / f'{name}_overview.png' |
| render_multi_view(npz_path, out, base) |
| rendered += 1 |
|
|
| if mode in ('gif', 'both'): |
| out = output_dir / f'{name}.gif' |
| render_motion_to_gif(npz_path, out, base, frame_skip=frame_skip) |
| rendered += 1 |
|
|
| return rendered |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Render motion visualizations') |
| parser.add_argument('--input', type=str, help='Single npz file to render') |
| parser.add_argument('--dataset', type=str, help='Dataset ID for batch render') |
| parser.add_argument('--output', type=str, default='results/videos/', help='Output directory') |
| parser.add_argument('--num', type=int, default=20, help='Number of samples for batch') |
| parser.add_argument('--mode', choices=['overview', 'gif', 'both'], default='both') |
| parser.add_argument('--frame_skip', type=int, default=2, help='Frame skip for GIF (1=all frames)') |
| parser.add_argument('--show_text', action='store_true', default=True) |
| parser.add_argument('--show_skeleton_info', action='store_true', default=True) |
| args = parser.parse_args() |
|
|
| output = Path(args.output) |
|
|
| if args.input: |
| npz_path = Path(args.input) |
| ds_path = npz_path.parent.parent |
| print(f'Rendering: {npz_path.name}') |
|
|
| if args.mode in ('overview', 'both'): |
| out = output / f'{npz_path.stem}_overview.png' |
| render_multi_view(npz_path, out, ds_path) |
| print(f' Overview: {out}') |
|
|
| if args.mode in ('gif', 'both'): |
| out = output / f'{npz_path.stem}.gif' |
| render_motion_to_gif(npz_path, out, ds_path, frame_skip=args.frame_skip) |
| print(f' GIF: {out}') |
|
|
| elif args.dataset: |
| print(f'Batch rendering: {args.dataset} ({args.num} samples, mode={args.mode})') |
| n = batch_render(args.dataset, output / args.dataset, args.num, args.mode, args.frame_skip) |
| print(f' Rendered: {n} files → {output / args.dataset}') |
|
|
| else: |
| |
| for ds in ['humanml3d', 'lafan1', '100style', 'bandai_namco', 'cmu_mocap', 'mixamo', 'truebones_zoo']: |
| ds_path = project_root / 'data' / 'processed' / ds |
| if not ds_path.exists(): |
| continue |
| print(f'Rendering {ds}...') |
| n = batch_render(ds, output / ds, min(args.num, 10), args.mode, args.frame_skip) |
| print(f' {n} files') |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|