File size: 12,468 Bytes
73a87be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/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()