| """ |
| render_smal_multiview.py — combine pose + shape + texture into multi-view SMAL dog renders. |
| |
| Inputs (the released library): |
| --pose_npz library/poses/poses.npz : pose_6d (N, 34, 6) |
| --shape_npz library/shapes/shapes.npz : beta (S,30), betas_limbs (S,9), pose_6d (S,34,6), |
| logscale_part_list (9,) |
| --texture_dir library/textures/ : texture_*.png (2048^2) + uv_atlas_0.pth |
| [+ uv_atlas_1.pth] + uv_atlas_index.npy |
| --bite_root BITE checkout (code + SMAL weights), see scripts/setup.sh |
| |
| For each pose, each of the 60 views independently samples a random shape and texture (matching the |
| released dataset's generation). The shape-specific ear pose (shape pose_6d, joints 32/33) is blended |
| into the motion pose; cameras orbit the subject (4 azimuth x 5 elevation x 3 roll = 60 views). |
| |
| Outputs per pose: pose_{idx:06d}/{rgb,seg,npz,...}/{view}.{png,npz}. With --shard (default on, |
| single process) the per-pose dirs are packed into stored tar shards. |
| |
| Requires a one-time setup of the SMAL/BITE dependency: bash scripts/setup.sh |
| """ |
| import os |
| import sys |
|
|
| |
| def _early_arg(flag): |
| for i, a in enumerate(sys.argv): |
| if a == flag and i + 1 < len(sys.argv): |
| return sys.argv[i + 1] |
| if a.startswith(flag + "="): |
| return a.split("=", 1)[1] |
| return None |
|
|
| _br = _early_arg("--bite_root") |
| if _br: |
| os.environ["BITE_ROOT"] = _br |
| os.environ.setdefault("PYOPENGL_PLATFORM", "egl") |
|
|
| import argparse |
| import random |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| import cv2 |
| from pathlib import Path |
| from PIL import Image |
| from str2bool import str2bool |
|
|
| from render_utils import ( |
| deduce_weak_perspective_params, |
| MeshRenderer, |
| project_keypoints_to_2d, |
| draw_keypoints_on_image, |
| ) |
| from smal_utils import initialize_smal_model_batch |
| import shard_utils |
|
|
| |
| EAR_JOINT_INDICES = [32, 33] |
|
|
|
|
| def apply_horizontal_flip_(pose_6d, device): |
| assert pose_6d is not None |
| assert pose_6d.ndim == 3 and pose_6d.shape[1] == 34 and pose_6d.shape[2] == 6, f"pose_6d.shape: {pose_6d.shape}" |
| assert device is not None |
|
|
| left_indices = [6, 7, 8, 9, 16, 17, 18, 19, 32] |
| right_indices = [10, 11, 12, 13, 20, 21, 22, 23, 33] |
|
|
| pose_6d_flipped = pose_6d.clone() |
| pose_6d_flipped[:, left_indices] = pose_6d[:, right_indices].clone() |
| pose_6d_flipped[:, right_indices] = pose_6d[:, left_indices].clone() |
| pose_6d_flipped[:, :, 1] *= -1 |
| pose_6d_flipped[:, :, 2] *= -1 |
| pose_6d_flipped[:, :, 5] *= -1 |
|
|
| N, J, D = pose_6d.shape |
| pose_6d_flipped = F.normalize(pose_6d_flipped.reshape(N, J, 3, 2), dim=-2).reshape(N, J, D) |
| return pose_6d_flipped |
|
|
|
|
| def rotate_rotmat(rotmat, angle_x=0.0, angle_y=0.0, angle_z=0.0, degrees=True): |
| """Apply additional rotation to existing rotation matrices.""" |
| device = rotmat.device |
| dtype = rotmat.dtype |
| if degrees: |
| angle_x = torch.tensor(angle_x, device=device, dtype=dtype) * (torch.pi / 180.0) |
| angle_y = torch.tensor(angle_y, device=device, dtype=dtype) * (torch.pi / 180.0) |
| angle_z = torch.tensor(angle_z, device=device, dtype=dtype) * (torch.pi / 180.0) |
| else: |
| angle_x = torch.tensor(angle_x, device=device, dtype=dtype) |
| angle_y = torch.tensor(angle_y, device=device, dtype=dtype) |
| angle_z = torch.tensor(angle_z, device=device, dtype=dtype) |
|
|
| cos_x, sin_x = torch.cos(angle_x), torch.sin(angle_x) |
| R_x = torch.eye(3, device=device, dtype=dtype) |
| R_x[1, 1] = cos_x; R_x[1, 2] = -sin_x; R_x[2, 1] = sin_x; R_x[2, 2] = cos_x |
|
|
| cos_y, sin_y = torch.cos(angle_y), torch.sin(angle_y) |
| R_y = torch.eye(3, device=device, dtype=dtype) |
| R_y[0, 0] = cos_y; R_y[0, 2] = sin_y; R_y[2, 0] = -sin_y; R_y[2, 2] = cos_y |
|
|
| cos_z, sin_z = torch.cos(angle_z), torch.sin(angle_z) |
| R_z = torch.eye(3, device=device, dtype=dtype) |
| R_z[0, 0] = cos_z; R_z[0, 1] = -sin_z; R_z[1, 0] = sin_z; R_z[1, 1] = cos_z |
|
|
| return torch.matmul(R_z @ R_y @ R_x, rotmat) |
|
|
|
|
| def generate_rotation_sequence(angle_ranges, device="cpu"): |
| """Generate camera orientations (as 6D) for the turntable views.""" |
| orient = torch.eye(3, device=device, dtype=torch.float32) |
| orient = rotate_rotmat(orient, angle_x=90, angle_y=0, angle_z=0) |
| orient = rotate_rotmat(orient, angle_x=0, angle_y=90, angle_z=0) |
| orient = rotate_rotmat(orient, angle_x=3, angle_y=0, angle_z=0) |
|
|
| angle_ys, angle_xs, angle_zs = [], [], [] |
| for azim_range, elev_range, roll_range in angle_ranges: |
| angle_ys.append(np.random.uniform(azim_range[0], azim_range[1])) |
| angle_xs.append(np.random.uniform(elev_range[0], elev_range[1])) |
| angle_zs.append(np.random.uniform(roll_range[0], roll_range[1])) |
|
|
| orient_6d_list = [] |
| for i in range(len(angle_xs)): |
| f = orient |
| f = rotate_rotmat(f, angle_x=0, angle_y=angle_ys[i], angle_z=0) |
| f = rotate_rotmat(f, angle_x=angle_xs[i], angle_y=0, angle_z=0) |
| f = rotate_rotmat(f, angle_x=0, angle_y=0, angle_z=angle_zs[i]) |
| orient_6d_list.append(f[..., :2].reshape(1, 1, 6)) |
| return torch.cat(orient_6d_list, dim=0) |
|
|
|
|
| def setup_output_dirs(output_dir, args): |
| """Create output directories based on enabled render options.""" |
| output_dir = Path(output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
| dirs = {} |
| if args.save_rgb: |
| dirs["rgb"] = output_dir / "rgb"; dirs["rgb"].mkdir(exist_ok=True) |
| if args.save_keypoints: |
| dirs["rgb_with_keypoints2d"] = output_dir / "rgb_with_keypoints2d"; dirs["rgb_with_keypoints2d"].mkdir(exist_ok=True) |
| if args.save_depth: |
| dirs["depth"] = output_dir / "depth"; dirs["depth"].mkdir(exist_ok=True) |
| if args.save_mask: |
| dirs["mask"] = output_dir / "seg"; dirs["mask"].mkdir(exist_ok=True) |
| if args.save_canny: |
| dirs["canny"] = output_dir / "canny"; dirs["canny"].mkdir(exist_ok=True) |
| return dirs |
|
|
|
|
| def render_frame(smal_mesh, keyp_3d, camera, renderer, args): |
| """Render a single frame with requested outputs.""" |
| results = {} |
| rgb_rgba = renderer.render(smal_mesh, camera, color=None) |
| rgb = rgb_rgba[..., :3] |
| results["rgb"] = rgb |
| if args.save_mask: |
| results["mask"] = (rgb_rgba[..., 3] > 0).astype(np.uint8) * 255 |
| if args.save_depth: |
| depth = renderer.render(smal_mesh, camera, depth_only=True) |
| depth[depth == 0] = np.nan |
| dn = 1 - (depth - np.nanmin(depth)) / (np.nanmax(depth) - np.nanmin(depth)) |
| dn[np.isnan(dn)] = 0 |
| results["depth"] = np.rint(dn * 255).astype(np.uint8) |
| if args.save_canny: |
| results["canny"] = cv2.Canny(rgb, 100, 200) |
| keyp_2d = project_keypoints_to_2d(keyp_3d, camera, img_size=args.resolution) |
| results["keypoints2d"] = (keyp_2d / (args.resolution - 1) * 2 - 1)[None] |
| if args.save_keypoints: |
| results["rgb_with_keypoints2d"] = draw_keypoints_on_image( |
| rgb, keyp_2d, radius=max(2, args.resolution // 128), color=(255, 0, 0), thickness=-1) |
| return results |
|
|
|
|
| def save_frame_results(results, view_name, output_dirs): |
| for key, img in results.items(): |
| if key in output_dirs: |
| Image.fromarray(img).save(output_dirs[key] / f"{view_name}.png") |
|
|
|
|
| def create_gifs(output_dir, output_dirs, file_names, fps=6): |
| import imageio |
| for name, dir_path in output_dirs.items(): |
| images = [] |
| for file_name in file_names: |
| p = dir_path / f"{file_name}.png" |
| if p.exists(): |
| images.append(imageio.imread(p)) |
| if images: |
| gif_path = output_dir / "gif" / f"{name}.gif" |
| gif_path.parent.mkdir(parents=True, exist_ok=True) |
| imageio.mimsave(gif_path, images, format="GIF", fps=fps, loop=0) |
|
|
|
|
| def process_single_pose(pose_idx, pose_6d_single, args, shapes, textures, angle_ranges, num_views, renderer): |
| """Render all views for one pose, sampling a random shape+texture per view.""" |
| shape_beta, shape_blimbs, shape_pose, logscale_part_shared = shapes |
| texture_pngs, atlas = textures |
|
|
| output_dir = Path(args.output_root) / f"pose_{pose_idx:06d}" |
| output_dirs = setup_output_dirs(output_dir, args) |
|
|
| pose_6d_from_motion = torch.from_numpy(np.asarray(pose_6d_single)).float() |
| if pose_6d_from_motion.ndim == 2: |
| pose_6d_from_motion = pose_6d_from_motion.unsqueeze(0) |
| if args.apply_horizontal_flip: |
| pose_6d_from_motion = apply_horizontal_flip_(pose_6d_from_motion, args.device) |
|
|
| |
| num_shapes = shape_beta.shape[0] |
| shape_ids = random.choices(range(num_shapes), k=num_views) |
| beta_list = [torch.from_numpy(shape_beta[s:s + 1]).float() for s in shape_ids] |
| betas_limbs_list = [torch.from_numpy(shape_blimbs[s:s + 1]).float() for s in shape_ids] |
| pose_6d_from_shape_list = [torch.from_numpy(shape_pose[s:s + 1]).float() for s in shape_ids] |
|
|
| |
| pose_6d_list = [] |
| for i in range(num_views): |
| blended = pose_6d_from_motion.clone() |
| blended[:, EAR_JOINT_INDICES, :] = pose_6d_from_shape_list[i][:, EAR_JOINT_INDICES, :] |
| pose_6d_list.append(blended) |
|
|
| |
| tex_ids = random.choices(range(len(texture_pngs)), k=num_views) |
| uvmap_image_list = [Image.open(texture_pngs[t]) for t in tex_ids] |
| xatlas_params_list = [atlas for _ in tex_ids] |
|
|
| orient_6d_list = generate_rotation_sequence(angle_ranges, device=args.device) |
|
|
| beta_batch = torch.cat(beta_list, dim=0) |
| betas_limbs_batch = torch.cat(betas_limbs_list, dim=0) |
| pose_6d_batch = torch.cat(pose_6d_list, dim=0) |
|
|
| if args.tail_drop_prob > 0.0: |
| mask = torch.rand(betas_limbs_batch.shape[0]) < args.tail_drop_prob |
| if "tail_l" in logscale_part_shared: |
| betas_limbs_batch[mask, logscale_part_shared.index("tail_l")] = -6 |
| if "tail_f" in logscale_part_shared: |
| betas_limbs_batch[mask, logscale_part_shared.index("tail_f")] = -6 |
|
|
| smal_outputs = initialize_smal_model_batch( |
| keyp_conf="all", |
| beta_batch=beta_batch, |
| betas_limbs_batch=betas_limbs_batch, |
| logscale_part_list=logscale_part_shared, |
| pose_6d_batch=pose_6d_batch, |
| orient_6d_batch=orient_6d_list, |
| uvmap_image_list=uvmap_image_list, |
| xatlas_params_list=xatlas_params_list, |
| ) |
|
|
| for frame_idx in range(num_views): |
| view_name = args.view_names[frame_idx] |
| smal_output = smal_outputs[frame_idx] |
| orient_6d_frame = orient_6d_list[frame_idx] |
| smal_mesh = smal_output["mesh"] |
| keyp_3d = smal_output["keyp_3d"].data.cpu() |
|
|
| verts = smal_mesh.vertices |
| s, tx, ty = np.array(deduce_weak_perspective_params( |
| verts, img_size=(args.resolution, args.resolution), random=args.random_camera)) / args.resolution |
| s *= 2 |
| tx = (tx - 0.5) * 2 |
| ty = (ty - 0.5) * 2 |
| camera = np.array([s, s, tx / s, ty / s]) |
|
|
| results = render_frame(smal_mesh, keyp_3d, camera, renderer, args) |
| save_frame_results(results, view_name, output_dirs) |
|
|
| if args.save_npz: |
| metadata = { |
| "camera/scale": s, "camera/tx": tx, "camera/ty": ty, |
| "smal/beta": smal_output["beta"].cpu().numpy(), |
| "smal/betas_limbs": smal_output["betas_limbs"].cpu().numpy(), |
| "smal/vert_off_compact": smal_output["vert_off_compact"].cpu().numpy(), |
| "smal/trans": smal_output["trans"].cpu().numpy(), |
| "smal/orient_6d": orient_6d_frame.cpu().numpy(), |
| "smal/pose_6d": pose_6d_batch[frame_idx:frame_idx + 1].cpu().numpy(), |
| "smal/keyp_conf": smal_output["keyp_conf"], |
| "smal/keyp_3d_all": keyp_3d.cpu().numpy(), |
| "smal/keyp_2d_all": results["keypoints2d"], |
| "smal/logscale_part_list": smal_output["logscale_part_list"], |
| "smal/smal_model_type": smal_output["smal_model_type"], |
| } |
| (output_dir / "npz").mkdir(parents=True, exist_ok=True) |
| np.savez_compressed(output_dir / "npz" / f"{view_name}.npz", **metadata) |
|
|
| if args.create_gif: |
| create_gifs(output_dir, output_dirs, list(args.view_names)) |
|
|
|
|
| def argument_parser(): |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| p.add_argument("--pose_npz", required=True, help="library/poses/poses.npz") |
| p.add_argument("--shape_npz", required=True, help="library/shapes/shapes.npz") |
| p.add_argument("--texture_dir", required=True, help="library/textures/ (texture_*.png + uv_atlas_*.pth + uv_atlas_index.npy)") |
| p.add_argument("--output_root", required=True, help="Output root directory for rendered poses") |
| p.add_argument("--bite_root", default="./bite_gradio-hf", help="BITE checkout (code + SMAL weights); see scripts/setup.sh") |
| p.add_argument("--views", default=None, help="Comma-separated view names; default 00..59") |
| p.add_argument("--resolution", type=int, default=256, help="Square image resolution") |
| p.add_argument("--device", default="cuda", help="torch device") |
| p.add_argument("--apply_horizontal_flip", type=str2bool, default=False) |
| p.add_argument("--save_rgb", type=str2bool, default=True) |
| p.add_argument("--save_keypoints", type=str2bool, default=False) |
| p.add_argument("--save_depth", type=str2bool, default=False) |
| p.add_argument("--save_mask", type=str2bool, default=True) |
| p.add_argument("--save_canny", type=str2bool, default=False) |
| p.add_argument("--save_npz", type=str2bool, default=True) |
| p.add_argument("--create_gif", type=str2bool, default=False) |
| p.add_argument("--random_camera", type=str2bool, default=False) |
| p.add_argument("--tail_drop_prob", type=float, default=0.0) |
| p.add_argument("--process_id", type=int, default=0) |
| p.add_argument("--num_processes", type=int, default=1) |
| p.add_argument("--pose_indices_file", default=None, help="File of pose indices (one per line); overrides process partitioning") |
| |
| p.add_argument("--shard", type=str2bool, default=True, help="Pack rendered poses into stored tar shards") |
| p.add_argument("--shard_dir", default=None, help="Shard output dir (default: <output_root>_shards)") |
| p.add_argument("--shard_size", type=int, default=1750, help="Poses per shard") |
| p.add_argument("--shard_cleanup", type=str2bool, default=False, help="Delete loose pose dirs after sharding") |
| p.add_argument("--seed", type=int, default=0, help="Base RNG seed (offset by process_id)") |
| return p.parse_args() |
|
|
|
|
| def main(): |
| from tqdm import tqdm |
| args = argument_parser() |
|
|
| if args.views is None: |
| args.views = ",".join(f"{i:02d}" for i in range(60)) |
| args.view_names = args.views.split(",") |
| num_views = len(args.view_names) |
|
|
| |
| azim_ranges = [[-45, 45], [45, 135], [135, 225], [225, 315]] |
| elev_ranges = [[60, 90], [15, 60], [-15, 15], [-60, -15], [-90, -60]] |
| roll_ranges = [[-180, -60], [-60, 60], [60, 180]] |
| angle_ranges = [(a, e, r) for a in azim_ranges for e in elev_ranges for r in roll_ranges] |
| assert len(angle_ranges) == num_views, \ |
| f"--views count ({num_views}) must match angle_ranges ({len(angle_ranges)})" |
|
|
| random.seed(args.seed + args.process_id) |
| np.random.seed(args.seed + args.process_id) |
|
|
| print(f"Loading poses from {args.pose_npz} ...") |
| all_poses = np.load(args.pose_npz, allow_pickle=True)["pose_6d"] |
| total_poses = len(all_poses) |
| print(f"Loaded {total_poses} poses {all_poses.shape}") |
|
|
| if args.pose_indices_file is not None: |
| pose_indices = [int(l.strip()) for l in open(args.pose_indices_file) if l.strip()] |
| else: |
| per = (total_poses + args.num_processes - 1) // args.num_processes |
| start = args.process_id * per |
| pose_indices = list(range(start, min(start + per, total_poses))) |
| print(f"[Process {args.process_id}/{args.num_processes}] {len(pose_indices)} poses") |
|
|
| |
| sd = np.load(args.shape_npz, allow_pickle=True) |
| shapes = (sd["beta"], sd["betas_limbs"], sd["pose_6d"], list(sd["logscale_part_list"])) |
| print(f"Loaded {shapes[0].shape[0]} shapes") |
|
|
| |
| tex_dir = Path(args.texture_dir) |
| texture_pngs = sorted(tex_dir.glob("texture_*.png")) |
| atlas_path = tex_dir / "uv_atlas.pth" |
| if not atlas_path.exists(): |
| atlas_path = tex_dir / "uv_atlas_0.pth" |
| atlas = torch.load(atlas_path, weights_only=False) |
| textures = (texture_pngs, atlas) |
| print(f"Loaded {len(texture_pngs)} textures (single UV atlas: {atlas_path.name})") |
|
|
| renderer = MeshRenderer(resolution=(args.resolution, args.resolution), randomize_light_orientation=True) |
|
|
| for pose_idx in tqdm(pose_indices, desc=f"[Process {args.process_id}] Rendering"): |
| process_single_pose(pose_idx, all_poses[pose_idx], args, shapes, textures, |
| angle_ranges, num_views, renderer) |
|
|
| try: |
| if hasattr(renderer.renderer, "delete"): |
| renderer.renderer.delete() |
| except Exception: |
| pass |
|
|
| |
| if args.shard: |
| if args.num_processes > 1: |
| print("[shard] skipped: --num_processes > 1. Render loose, then pack with " |
| "build/03_pack_renders_to_shards.py or a single-process --shard run.") |
| else: |
| shard_dir = args.shard_dir or (str(args.output_root).rstrip("/") + "_shards") |
| mods = shard_utils.modalities_from_flags( |
| args.save_rgb, args.save_mask, args.save_npz, |
| args.save_keypoints, args.save_depth, args.save_canny) |
| items = [(pid, str(Path(args.output_root) / f"pose_{pid:06d}")) for pid in pose_indices] |
| shard_utils.pack_to_shards(items, shard_dir, args.shard_size, modalities=mods, |
| index_csv=os.path.join(shard_dir, "shards_index.csv")) |
| if args.shard_cleanup: |
| import shutil |
| for pid in pose_indices: |
| shutil.rmtree(Path(args.output_root) / f"pose_{pid:06d}", ignore_errors=True) |
| print("[shard] removed loose pose dirs") |
|
|
| print(f"[Process {args.process_id}] Done. {len(pose_indices)} poses.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|