#!/usr/bin/env python3 """Project prepared COCO133 arrays with one fixed portrait camera.""" from __future__ import annotations import argparse import json from pathlib import Path import numpy as np from PIL import Image import make_coco_json as common def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--sequence-dir", required=True, type=Path) parser.add_argument("--portrait-dir", required=True, type=Path) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--seq-id", required=True) parser.add_argument("--bbox-padding", type=float, default=0.15) args = parser.parse_args() points_all = np.load(args.sequence_dir / "coco133_3d.npy", mmap_mode="r") masks_all = np.load(args.sequence_dir / "coco133_mask.npy", mmap_mode="r") camera = json.loads((args.portrait_dir / "camera.json").read_text(encoding="utf-8")) rgb_frames = sorted((args.portrait_dir / "rgb").glob("frame_*.png")) mask_frames = sorted((args.portrait_dir / "hand_mask").glob("frame_*.png")) hand_rgb_dir = args.portrait_dir / "hand_rgb" hand_rgb_frames = sorted(hand_rgb_dir.glob("frame_*.png")) if hand_rgb_dir.is_dir() else [] if not rgb_frames or len(rgb_frames) != len(mask_frames) or len(rgb_frames) != points_all.shape[0]: raise RuntimeError( f"Frame mismatch: rgb={len(rgb_frames)} mask={len(mask_frames)} coco3d={points_all.shape[0]}" ) if hand_rgb_frames and len(hand_rgb_frames) != len(rgb_frames): raise RuntimeError(f"Hand RGB frame mismatch: rgb={len(rgb_frames)} hand_rgb={len(hand_rgb_frames)}") width, height = int(camera["image_width"]), int(camera["image_height"]) images = [] annotations = [] smplx_world = np.asarray(camera.get("smplx_matrix_world", np.eye(4)), dtype=np.float64) for frame_idx, image_path in enumerate(rgb_frames): with Image.open(image_path) as image: if image.size != (width, height): raise ValueError(f"Unexpected RGB size for {image_path}: {image.size} != {(width, height)}") points = np.asarray(points_all[frame_idx], dtype=np.float32).copy() valid = np.asarray(masks_all[frame_idx], dtype=np.uint8).copy() points[common.COCO_WHOLEBODY_FACE_SLICE] = 0.0 valid[common.COCO_WHOLEBODY_FACE_SLICE] = 0 world = common.transform_points_by_matrix(points, smplx_world) xy, visibility, _ = common.project_points_opencv( points_world=world, valid_mask=valid, K=np.asarray(camera["K"], dtype=np.float64), R_world_to_cam=np.asarray(camera["R_world_to_cam"], dtype=np.float64), t_world_to_cam=np.asarray(camera["t_world_to_cam"], dtype=np.float64), image_width=width, image_height=height, ) bbox = common.bbox_from_keypoints(xy, visibility, width, height, args.bbox_padding) image_id = frame_idx + 1 image_record = { "id": image_id, "file_name": f"{args.seq_id}/rgb/{image_path.name}", "hand_mask_file_name": f"{args.seq_id}/hand_mask/{mask_frames[frame_idx].name}", "width": width, "height": height, "frame_idx": frame_idx, } if hand_rgb_frames: image_record["hand_rgb_file_name"] = f"{args.seq_id}/hand_rgb/{hand_rgb_frames[frame_idx].name}" images.append(image_record) annotations.append({ "id": image_id, "image_id": image_id, "category_id": 1, "iscrowd": 0, "bbox": bbox, "area": float(bbox[2] * bbox[3]), "num_keypoints": int(np.sum(visibility > 0)), "keypoints": common.flatten_keypoints(xy, visibility), "face_box": None, "lefthand_box": common.optional_box_from_slice(xy, visibility, slice(91, 112)), "righthand_box": common.optional_box_from_slice(xy, visibility, slice(112, 133)), "source_frame_idx": frame_idx, }) payload = { "info": { "description": "Synthetic portrait SMPL-X RGB/visible-hand-mask COCO-WholeBody annotations", "version": "portrait_png_v1", }, "licenses": [], "images": images, "annotations": annotations, "categories": [{ "id": 1, "name": "person", "supercategory": "person", "keypoints": common.COCO_WHOLEBODY_KEYPOINTS, "skeleton": [], }], } args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(json.dumps(payload, indent=2), encoding="utf-8") print(f"[OK] Wrote portrait COCO: {len(images)} frames -> {args.out}") if __name__ == "__main__": main()