#!/usr/bin/env python """Minimal reader for one DREAMS-AVATAR capture: videos + SMPL-X + cameras. Zero dependencies beyond numpy + opencv-python. Nothing here needs the SMPL-X model file -- that is only required if you want vertices (see `smplx_forward_kwargs`). from load_capture import Capture cap = Capture("data/P1C1") print(cap) # P1C1: 32 cams, 1836 frames, 2048x1500 # --- cameras ------------------------------------------------------------- cam = cap.cameras["cam03"] uv = cam.project(cap.joints(frame=1400)) # (144,2) pixel coords in the RGB half # --- images -------------------------------------------------------------- rgb, alpha = cap.read_frame("cam03", frame=1400) # (1500,2048,3) uint8, (1500,2048) uint8 for frame, rgb, alpha in cap.iter_frames("cam03", start=1400, end=1410): ... # --- SMPL-X -------------------------------------------------------------- p = cap.smplx_params(frame=1400) # dict of (1,D) float32 torch-ready arrays kw = cap.smplx_forward_kwargs # exact smplx.SMPLX(**kw) constructor args Frame convention (d = 0, uniform across every capture) frame index == smplx.npz["frames"][i] == the 0-based frame index inside camNN.mp4. There is no offset. `Capture.video_frame(frame)` exists so call sites read clearly, but it is the identity. Historical note: P1C1 was first tracked assuming `GT = video + 1`. That offset had been measured on a near-static frame, where all candidates look alike, and it was wrong. It was re-measured on high-motion frames against the alpha matte and is 0 for every capture. `verify_alignment.py` re-measures it from the shipped files. Video layout Each camNN.mp4 is 4096x1500 and is published UNCROPPED on purpose: LEFT 2048x1500 = matted RGB (black background) RIGHT 2048x1500 = the ALPHA MATTE, a binary silhouette registered to the left half within a few pixels, replicated over 3 channels. The alpha half is the foreground mask avatar training needs, so it is part of the data, not a rendering artifact. The calibration (fx, fy, cx, cy, w=2048, h=1500) refers to the LEFT half; both halves share it. Camera convention K = [[fx, 0, cx], [0, fy, cy], [0, 0, 1]] from cameras.json rigs[i].cameras[0] R_w2c = R @ diag(1, -1, -1) (world_flip: cameras.json is Y-down) t_w2c = -R @ c (c = camera centre, unflipped world) x_cam = R_w2c @ x_world + t_w2c ; uv = (K @ x_cam)[:2] / x_cam[2] """ from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from typing import Iterator import numpy as np WORLD_FLIP = np.diag([1.0, -1.0, -1.0]) # cameras.json world (Y-down) -> SMPL-X world (Y-up) # SINGLE SOURCE OF TRUTH for the frame mapping, imported by every other script here: # video_frame_index = smplx_frame + VIDEO_FRAME_OFFSET # Measured, not assumed (see verify_alignment.py). Do not hard-code the number anywhere # else; a silent disagreement between two files is exactly how the original +1 survived. VIDEO_FRAME_OFFSET = 0 PARAM_KEYS = ("global_orient", "body_pose", "jaw_pose", "leye_pose", "reye_pose", "left_hand_pose", "right_hand_pose", "betas", "expression", "transl") @dataclass(frozen=True) class PinholeCamera: name: str K: np.ndarray # (3,3) R_w2c: np.ndarray # (3,3) t_w2c: np.ndarray # (3,) width: int height: int def project(self, xyz_world: np.ndarray) -> np.ndarray: """(N,3) world points -> (N,2) pixels in the RGB half.""" x = np.asarray(xyz_world, np.float64).reshape(-1, 3) @ self.R_w2c.T + self.t_w2c uvw = x @ self.K.T return uvw[:, :2] / uvw[:, 2:3] @property def center(self) -> np.ndarray: """Camera centre in the SMPL-X (Y-up) world.""" return -self.R_w2c.T @ self.t_w2c @property def extrinsic(self) -> np.ndarray: """(3,4) world-to-camera [R|t].""" return np.concatenate([self.R_w2c, self.t_w2c[:, None]], 1) def load_cameras(path: str | Path, world_flip: bool = True) -> dict[str, PinholeCamera]: """cameras.json -> {"cam00": PinholeCamera, ...}; index i == videos/cam{i:02d}.mp4.""" d = json.loads(Path(path).read_text()) A = WORLD_FLIP if world_flip else np.eye(3) cams: dict[str, PinholeCamera] = {} for i, rig in enumerate(d["rigs"]): c = rig["cameras"][0] K = np.array([[c["fx"], 0.0, c["cx"]], [0.0, c["fy"], c["cy"]], [0.0, 0.0, 1.0]], np.float64) R = np.asarray(c["R"], np.float64).reshape(3, 3) C = np.asarray(c["c"], np.float64).reshape(3) cams[f"cam{i:02d}"] = PinholeCamera(f"cam{i:02d}", K, R @ A, -R @ C, int(c["w"]), int(c["h"])) return cams class Capture: """One `data//` directory.""" def __init__(self, root: str | Path): self.root = Path(root) self.name = self.root.name self.cameras = load_cameras(self.root / "cameras.json") self.video_dir = self.root / "videos" z = np.load(self.root / "smplx.npz", allow_pickle=False) self.smplx = {k: z[k] for k in z.files} self.frames: np.ndarray = self.smplx["frames"].astype(int) self._idx = {int(f): i for i, f in enumerate(self.frames)} self.smplx_forward_kwargs: dict = json.loads(str(self.smplx["smplx_kwargs"])) self.meta: dict = json.loads(str(self.smplx["meta"])) self.card: dict = json.loads((self.root / "capture.json").read_text()) \ if (self.root / "capture.json").exists() else {} # ---------------------------------------------------------------- indexing def index(self, frame: int) -> int: if frame not in self._idx: raise KeyError(f"{self.name}: no SMPL-X fit for GT frame {frame} " f"(have {self.frames[0]}..{self.frames[-1]})") return self._idx[frame] def video_frame(self, frame: int) -> int: """0-based index into camNN.mp4. Identity: d=0 (see VIDEO_FRAME_OFFSET).""" return frame + VIDEO_FRAME_OFFSET # ---------------------------------------------------------------- SMPL-X def smplx_params(self, frame: int, batched: bool = True) -> dict[str, np.ndarray]: """The 10 SMPL-X forward() tensors at `frame`, shaped (1,D) if batched.""" i = self.index(frame) out = {k: self.smplx[k][i] for k in PARAM_KEYS} return {k: v[None] for k, v in out.items()} if batched else out def joints(self, frame: int) -> np.ndarray: return self.smplx["joints"][self.index(frame)] # ---------------------------------------------------------------- video def read_frame(self, cam: str, frame: int) -> tuple[np.ndarray, np.ndarray]: """(rgb HxWx3 uint8, alpha HxW uint8) for one camera at one GT frame.""" import cv2 vf = self.video_frame(frame) cap = cv2.VideoCapture(str(self.video_dir / f"{cam}.mp4")) try: cap.set(cv2.CAP_PROP_POS_FRAMES, vf) ok, bgr = cap.read() if not ok: raise RuntimeError(f"{cam}: cannot read video frame {vf}") finally: cap.release() return _split(bgr) def iter_frames(self, cam: str, start: int | None = None, end: int | None = None ) -> Iterator[tuple[int, np.ndarray, np.ndarray]]: """Sequential decode (much faster than repeated seeks). Yields (frame, rgb, alpha).""" import cv2 start = int(self.frames[0]) if start is None else start end = int(self.frames[-1]) if end is None else end cap = cv2.VideoCapture(str(self.video_dir / f"{cam}.mp4")) try: cap.set(cv2.CAP_PROP_POS_FRAMES, self.video_frame(start)) for frame in range(start, end + 1): ok, bgr = cap.read() if not ok: break rgb, alpha = _split(bgr) yield frame, rgb, alpha finally: cap.release() def __repr__(self) -> str: c = next(iter(self.cameras.values())) return (f"") def _split(bgr: np.ndarray) -> tuple[np.ndarray, np.ndarray]: w = bgr.shape[1] // 2 return bgr[:, :w, ::-1].copy(), bgr[:, w:, 0].copy() if __name__ == "__main__": import argparse ap = argparse.ArgumentParser(description="Smoke-test a capture directory.") ap.add_argument("capture_dir", help="e.g. data/P1C1") ap.add_argument("--frame", type=int, default=None) ap.add_argument("--cam", default="cam03") a = ap.parse_args() cap = Capture(a.capture_dir) print(cap) print("smplx kwargs:", cap.smplx_forward_kwargs) f = a.frame if a.frame is not None else int(cap.frames[len(cap.frames) // 2]) p = cap.smplx_params(f) print(f"frame {f}: " + ", ".join(f"{k}{tuple(v.shape)}" for k, v in p.items())) rgb, alpha = cap.read_frame(a.cam, f) print(f"{a.cam} rgb{rgb.shape} alpha{alpha.shape} fg={float((alpha > 12).mean()):.3f}") uv = cap.cameras[a.cam].project(cap.joints(f)) inside = ((uv[:, 0] >= 0) & (uv[:, 0] < rgb.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < rgb.shape[0])).mean() print(f"reprojected joints inside image: {inside:.1%}")