Datasets:
Download generator/scripts/make_coco_json.py from mage0001/H2SMV-FPV: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/make_coco_json.py
- Command line
-
hf download hf://datasets/mage0001/H2SMV-FPV/generator/scripts/make_coco_json.py
-
curl -L -o make_coco_json.py https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/make_coco_json.py
12.5 kB
| #!/usr/bin/env python3 | |
| """ | |
| Project prepared COCO-WholeBody 133 3D keypoints to rendered Blender images | |
| and write a COCO-style annotation JSON. | |
| Usage: | |
| python scripts/make_coco_json.py \ | |
| --sequence-dir cache/seq_000001 \ | |
| --render-dir renders/seq_000001 \ | |
| --out annotations/seq_000001_coco_wholebody.json \ | |
| --image-prefix seq_000001 \ | |
| --disable-face | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image | |
| from tqdm import tqdm | |
| COCO_WHOLEBODY_FACE_SLICE = slice(23, 91) | |
| COCO_WHOLEBODY_KEYPOINTS = [ | |
| "nose", "left_eye", "right_eye", "left_ear", "right_ear", | |
| "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", | |
| "left_wrist", "right_wrist", "left_hip", "right_hip", | |
| "left_knee", "right_knee", "left_ankle", "right_ankle", | |
| "left_big_toe", "left_small_toe", "left_heel", | |
| "right_big_toe", "right_small_toe", "right_heel", | |
| ] | |
| # COCO-WholeBody face points are conventionally 68 landmarks. | |
| COCO_WHOLEBODY_KEYPOINTS += [f"face_{i}" for i in range(68)] | |
| # COCO-WholeBody hand order: wrist, thumb1-4, index1-4, middle1-4, ring1-4, pinky1-4. | |
| HAND_NAMES = [ | |
| "wrist", | |
| "thumb1", "thumb2", "thumb3", "thumb4", | |
| "index1", "index2", "index3", "index4", | |
| "middle1", "middle2", "middle3", "middle4", | |
| "ring1", "ring2", "ring3", "ring4", | |
| "pinky1", "pinky2", "pinky3", "pinky4", | |
| ] | |
| COCO_WHOLEBODY_KEYPOINTS += [f"left_hand_{name}" for name in HAND_NAMES] | |
| COCO_WHOLEBODY_KEYPOINTS += [f"right_hand_{name}" for name in HAND_NAMES] | |
| assert len(COCO_WHOLEBODY_KEYPOINTS) == 133 | |
| def frame_index_from_path(path: Path) -> int: | |
| """Extract integer frame index from frame_000001.json/png.""" | |
| match = re.search(r"frame_(\d+)", path.stem) | |
| if not match: | |
| raise ValueError(f"Could not parse frame index from {path}") | |
| return int(match.group(1)) | |
| def transform_points_by_matrix(points_3d: np.ndarray, matrix_4x4: np.ndarray) -> np.ndarray: | |
| """Apply a 4x4 homogeneous transform to [N,3] or [T,N,3] points.""" | |
| points_3d = np.asarray(points_3d, dtype=np.float64) | |
| matrix_4x4 = np.asarray(matrix_4x4, dtype=np.float64) | |
| if matrix_4x4.shape != (4, 4): | |
| raise ValueError(f"matrix_4x4 must be [4,4], got {matrix_4x4.shape}") | |
| original_shape = points_3d.shape | |
| if points_3d.ndim == 2: | |
| flat = points_3d | |
| elif points_3d.ndim == 3: | |
| flat = points_3d.reshape(-1, 3) | |
| else: | |
| raise ValueError(f"points_3d must be [N,3] or [T,N,3], got {points_3d.shape}") | |
| ones = np.ones((flat.shape[0], 1), dtype=np.float64) | |
| homo = np.concatenate([flat, ones], axis=1) | |
| transformed = (matrix_4x4 @ homo.T).T[:, :3] | |
| return transformed.reshape(original_shape) | |
| def project_points_opencv( | |
| points_world: np.ndarray, | |
| valid_mask: np.ndarray, | |
| K: np.ndarray, | |
| R_world_to_cam: np.ndarray, | |
| t_world_to_cam: np.ndarray, | |
| image_width: int, | |
| image_height: int, | |
| min_depth: float = 1e-6, | |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: | |
| """Project [N,3] world points to OpenCV-style image pixels.""" | |
| points_world = np.asarray(points_world, dtype=np.float64) | |
| valid_mask = np.asarray(valid_mask).astype(bool) | |
| K = np.asarray(K, dtype=np.float64) | |
| R_world_to_cam = np.asarray(R_world_to_cam, dtype=np.float64) | |
| t_world_to_cam = np.asarray(t_world_to_cam, dtype=np.float64).reshape(3) | |
| if points_world.shape != (133, 3): | |
| raise ValueError(f"Expected points_world [133,3], got {points_world.shape}") | |
| if valid_mask.shape != (133,): | |
| raise ValueError(f"Expected valid_mask [133], got {valid_mask.shape}") | |
| points_cam = (R_world_to_cam @ points_world.T).T + t_world_to_cam[None, :] | |
| depth = points_cam[:, 2] | |
| points_2d = np.zeros((133, 2), dtype=np.float64) | |
| depth_ok = depth > min_depth | |
| points_2d[depth_ok, 0] = K[0, 0] * points_cam[depth_ok, 0] / depth[depth_ok] + K[0, 2] | |
| points_2d[depth_ok, 1] = K[1, 1] * points_cam[depth_ok, 1] / depth[depth_ok] + K[1, 2] | |
| inside = ( | |
| valid_mask | |
| & depth_ok | |
| & (points_2d[:, 0] >= 0) | |
| & (points_2d[:, 0] < image_width) | |
| & (points_2d[:, 1] >= 0) | |
| & (points_2d[:, 1] < image_height) | |
| ) | |
| visibility = np.zeros((133,), dtype=np.uint8) | |
| visibility[inside] = 2 | |
| return points_2d.astype(np.float32), visibility, depth.astype(np.float32) | |
| def bbox_from_keypoints(points_2d: np.ndarray, visibility: np.ndarray, image_width: int, image_height: int, padding: float) -> list[float]: | |
| """Compute a padded bbox from visible/labeled keypoints.""" | |
| valid = visibility > 0 | |
| if not np.any(valid): | |
| return [0.0, 0.0, 0.0, 0.0] | |
| xy = points_2d[valid] | |
| x1 = float(np.min(xy[:, 0])) | |
| y1 = float(np.min(xy[:, 1])) | |
| x2 = float(np.max(xy[:, 0])) | |
| y2 = float(np.max(xy[:, 1])) | |
| w = x2 - x1 | |
| h = y2 - y1 | |
| pad = padding * max(w, h, 1.0) | |
| x1 = max(0.0, x1 - pad) | |
| y1 = max(0.0, y1 - pad) | |
| x2 = min(float(image_width - 1), x2 + pad) | |
| y2 = min(float(image_height - 1), y2 + pad) | |
| return [x1, y1, max(0.0, x2 - x1), max(0.0, y2 - y1)] | |
| def flatten_keypoints(points_2d: np.ndarray, visibility: np.ndarray) -> list[float]: | |
| """Flatten [133,2] + [133] to COCO [x,y,v,...].""" | |
| result: list[float] = [] | |
| for idx in range(133): | |
| if visibility[idx] == 0: | |
| result.extend([0.0, 0.0, 0]) | |
| else: | |
| result.extend([float(points_2d[idx, 0]), float(points_2d[idx, 1]), int(visibility[idx])]) | |
| return result | |
| def optional_box_from_slice(points_2d: np.ndarray, visibility: np.ndarray, keypoint_slice: slice) -> list[float]: | |
| """Compute a small box for face/hand fields from keypoints.""" | |
| sub_points = points_2d[keypoint_slice] | |
| sub_vis = visibility[keypoint_slice] | |
| valid = sub_vis > 0 | |
| if not np.any(valid): | |
| return [0.0, 0.0, 0.0, 0.0] | |
| xy = sub_points[valid] | |
| x1 = float(np.min(xy[:, 0])) | |
| y1 = float(np.min(xy[:, 1])) | |
| x2 = float(np.max(xy[:, 0])) | |
| y2 = float(np.max(xy[:, 1])) | |
| return [x1, y1, max(0.0, x2 - x1), max(0.0, y2 - y1)] | |
| def make_coco_json( | |
| sequence_dir: Path, | |
| render_dir: Path, | |
| out_path: Path, | |
| image_prefix: str, | |
| disable_face: bool, | |
| bbox_padding: float, | |
| ) -> None: | |
| """Create COCO-WholeBody JSON for one rendered sequence.""" | |
| coco133_3d_path = sequence_dir / "coco133_3d.npy" | |
| mask_path = sequence_dir / "coco133_mask.npy" | |
| if not coco133_3d_path.exists(): | |
| raise FileNotFoundError(f"Missing {coco133_3d_path}") | |
| if not mask_path.exists(): | |
| raise FileNotFoundError(f"Missing {mask_path}") | |
| coco133_3d = np.load(coco133_3d_path, mmap_mode="r") | |
| coco133_mask = np.load(mask_path, mmap_mode="r") | |
| if coco133_3d.ndim != 3 or coco133_3d.shape[1:] != (133, 3): | |
| raise ValueError(f"Expected coco133_3d [F,133,3], got {coco133_3d.shape}") | |
| if coco133_mask.ndim != 2 or coco133_mask.shape[1] != 133: | |
| raise ValueError(f"Expected coco133_mask [F,133], got {coco133_mask.shape}") | |
| images_dir = render_dir / "images" | |
| cameras_dir = render_dir / "cameras" | |
| camera_files = sorted(cameras_dir.glob("frame_*.json")) | |
| if not camera_files: | |
| raise FileNotFoundError(f"No camera json files found in {cameras_dir}") | |
| images: list[dict] = [] | |
| annotations: list[dict] = [] | |
| image_id = 1 | |
| ann_id = 1 | |
| for cam_file in tqdm(camera_files, desc="Projecting COCO133"): | |
| frame_idx = frame_index_from_path(cam_file) | |
| image_file = images_dir / f"frame_{frame_idx:06d}.png" | |
| if not image_file.exists(): | |
| raise FileNotFoundError(f"Image missing for camera {cam_file}: {image_file}") | |
| with open(cam_file, "r", encoding="utf-8") as f: | |
| calib = json.load(f) | |
| image_width = int(calib["image_width"]) | |
| image_height = int(calib["image_height"]) | |
| # Use actual image size if readable. This catches mismatched render settings. | |
| with Image.open(image_file) as im: | |
| actual_width, actual_height = im.size | |
| if actual_width != image_width or actual_height != image_height: | |
| raise ValueError( | |
| f"Camera json size {image_width}x{image_height} does not match image size " | |
| f"{actual_width}x{actual_height} for {image_file}" | |
| ) | |
| points_3d = np.asarray(coco133_3d[frame_idx], dtype=np.float32).copy() | |
| valid_mask = np.asarray(coco133_mask[frame_idx], dtype=np.uint8).copy() | |
| if disable_face: | |
| points_3d[COCO_WHOLEBODY_FACE_SLICE, :] = 0.0 | |
| valid_mask[COCO_WHOLEBODY_FACE_SLICE] = 0 | |
| # render_blender_sequence.py renders vertices directly in world coordinates. | |
| # If a future render script stores a non-identity smplx_matrix_world, apply it here. | |
| smplx_matrix_world = np.asarray(calib.get("smplx_matrix_world", np.eye(4)), dtype=np.float64) | |
| points_world = transform_points_by_matrix(points_3d, smplx_matrix_world) | |
| points_2d, visibility, _depth = project_points_opencv( | |
| points_world=points_world, | |
| valid_mask=valid_mask, | |
| K=np.asarray(calib["K"], dtype=np.float64), | |
| R_world_to_cam=np.asarray(calib["R_world_to_cam"], dtype=np.float64), | |
| t_world_to_cam=np.asarray(calib["t_world_to_cam"], dtype=np.float64), | |
| image_width=image_width, | |
| image_height=image_height, | |
| ) | |
| bbox = bbox_from_keypoints(points_2d, visibility, image_width, image_height, bbox_padding) | |
| area = float(bbox[2] * bbox[3]) | |
| keypoints = flatten_keypoints(points_2d, visibility) | |
| num_keypoints = int(np.sum(visibility > 0)) | |
| rel_image_path = str(image_file).replace("\\", "/") | |
| if image_prefix: | |
| # Keep file_name stable but searchable by sequence prefix. | |
| rel_image_path = f"{image_prefix}/{image_file.name}" | |
| images.append( | |
| { | |
| "id": image_id, | |
| "file_name": rel_image_path, | |
| "width": image_width, | |
| "height": image_height, | |
| "frame_idx": frame_idx, | |
| } | |
| ) | |
| annotations.append( | |
| { | |
| "id": ann_id, | |
| "image_id": image_id, | |
| "category_id": 1, | |
| "iscrowd": 0, | |
| "bbox": bbox, | |
| "area": area, | |
| "num_keypoints": num_keypoints, | |
| "keypoints": keypoints, | |
| "face_box": optional_box_from_slice(points_2d, visibility, slice(23, 91)), | |
| "lefthand_box": optional_box_from_slice(points_2d, visibility, slice(91, 112)), | |
| "righthand_box": optional_box_from_slice(points_2d, visibility, slice(112, 133)), | |
| "source_frame_idx": frame_idx, | |
| } | |
| ) | |
| image_id += 1 | |
| ann_id += 1 | |
| categories = [ | |
| { | |
| "id": 1, | |
| "name": "person", | |
| "supercategory": "person", | |
| "keypoints": COCO_WHOLEBODY_KEYPOINTS, | |
| "skeleton": [], | |
| } | |
| ] | |
| coco = { | |
| "info": { | |
| "description": "Synthetic SMPL-X rendered COCO-WholeBody annotations", | |
| "version": "0.1", | |
| }, | |
| "licenses": [], | |
| "images": images, | |
| "annotations": annotations, | |
| "categories": categories, | |
| } | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(coco, f, indent=2) | |
| print(f"[OK] Wrote {len(images)} images / {len(annotations)} annotations to {out_path}") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--sequence-dir", required=True, type=Path) | |
| parser.add_argument("--render-dir", required=True, type=Path) | |
| parser.add_argument("--out", required=True, type=Path) | |
| parser.add_argument("--image-prefix", default="") | |
| parser.add_argument("--disable-face", action="store_true") | |
| parser.add_argument("--bbox-padding", type=float, default=0.15) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| make_coco_json( | |
| sequence_dir=args.sequence_dir, | |
| render_dir=args.render_dir, | |
| out_path=args.out, | |
| image_prefix=args.image_prefix, | |
| disable_face=args.disable_face, | |
| bbox_padding=args.bbox_padding, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |