| |
| """Decode one DREAMS-AVATAR capture into an AvatarReX / DEGAS-style training layout. |
| |
| NOTE ON SCOPE |
| This targets the DEGAS / DREAMS avatar *training input* format (flat |
| `calibration_full.json` + per-camera image folders + per-frame SMPL-X). The exact |
| key names and the image/mask split will be RECONCILED WITH THE TRAINING CODE in the |
| retrain phase -- treat the emitted tree as the proposed contract, not as frozen. |
| Everything here is derived from `data/<PxCy>/` alone, so re-emitting after a format |
| change is cheap (one ffmpeg pass per camera). |
| |
| INPUT data/<PxCy>/{videos/cam*.mp4, smplx.npz, cameras.json} |
| OUTPUT <out>/ |
| calibration_full.json {"cam00": {K, R, T, RT, imgSize, ...}, ...} |
| R,T are WORLD-TO-CAMERA in the SMPL-X Y-up world |
| cam_00/00000000.jpg ... RGB from the LEFT half, <frame:08d>.jpg |
| cam_00/mask/00000000.png ... ALPHA MATTE from the RIGHT half (--no-masks to skip) |
| smplx/00000000.npz per-frame SMPL-X params, (1,D) batched |
| smplx_params.npz the same params stacked over the emitted range |
| meta.json what was emitted and with which conventions |
| |
| THE MP4 CARRIES TWO THINGS. Each camNN.mp4 is 4096x1500 and is published uncropped: |
| the LEFT 2048 is the matted RGB and the RIGHT 2048 is the ALPHA MATTE, a binary |
| silhouette registered to the colour half within a few pixels. This script SPLITS them: |
| one ffmpeg pass crops the left half to `<frame>.jpg`, a second crops the right half to |
| `mask/<frame>.png`. Masks are emitted BY DEFAULT because the foreground mask is a |
| training input, not an optional extra. |
| |
| WHY THIS SHAPE |
| * `calibration_full.json` is flat (`{cam_name: entry}`) which is what AvatarReX and |
| the DEGAS trainer both consume -- unlike the capture's nested `rigs[i].cameras[0]`. |
| * The world Y-flip is BAKED IN here (R = R_json @ diag(1,-1,-1)), so the trainer needs |
| no knowledge of the DEGAS calibration quirk: cameras and SMPL-X are in one frame. |
| * Images are written as <GT frame id>, the same number that indexes `smplx.npz`, so a |
| dataloader can pair them by filename with no offset table. |
| |
| Examples |
| # every 4th frame, 8 front cameras (RGB + masks) |
| python prepare_training.py data/P1C1 --out /scratch/train/P1C1 \ |
| --stride 4 --cams 0 3 6 9 12 15 18 21 |
| |
| # everything (32 cams x 1836 frames ~= 59k jpgs, ~40 GB) -- use --workers |
| python prepare_training.py data/P1C1 --out /scratch/train/P1C1 --workers 8 |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import shutil |
| import subprocess |
| import sys |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| from load_capture import PARAM_KEYS, VIDEO_FRAME_OFFSET, Capture |
|
|
|
|
| |
| def write_calibration(cap: Capture, out: Path) -> dict: |
| """Flat AvatarReX-style calibration_full.json (world-to-camera, Y-up world).""" |
| entries = {} |
| for name, c in cap.cameras.items(): |
| entries[name] = { |
| "K": c.K.tolist(), |
| "R": c.R_w2c.tolist(), |
| "T": c.t_w2c.tolist(), |
| "RT": c.extrinsic.tolist(), |
| "imgSize": [c.width, c.height], |
| "width": c.width, |
| "height": c.height, |
| "D": [0.0] * 5, |
| "center": c.center.tolist(), |
| } |
| p = out / "calibration_full.json" |
| p.write_text(json.dumps(entries, indent=1) + "\n") |
| print(f"[calib] {p} ({len(entries)} cameras, world-to-camera, Y-up world)", flush=True) |
| return entries |
|
|
|
|
| |
| def _decode_cam(video: Path, out_dir: Path, frames: list[int], rgb_w: int, |
| quality: int, masks: bool, jpg_dir_fmt: str) -> tuple[str, int]: |
| """One ffmpeg pass per camera; select only the wanted video frames.""" |
| cam = video.stem |
| img_dir = out_dir / jpg_dir_fmt.format(cam=cam) |
| img_dir.mkdir(parents=True, exist_ok=True) |
| vidx = [f + VIDEO_FRAME_OFFSET for f in frames] |
| sel = "+".join(f"eq(n\\,{v})" for v in vidx) |
|
|
| |
| tmp = img_dir / "_tmp" |
| tmp.mkdir(exist_ok=True) |
| subprocess.run( |
| ["ffmpeg", "-y", "-v", "error", "-threads", "1", "-i", str(video), |
| "-vf", f"select='{sel}',crop={rgb_w}:in_h:0:0", "-vsync", "0", |
| "-q:v", str(quality), str(tmp / "%08d.jpg")], |
| check=True) |
| got = sorted(tmp.glob("*.jpg")) |
| if len(got) != len(frames): |
| raise RuntimeError(f"{cam}: ffmpeg returned {len(got)} frames, wanted {len(frames)}") |
| for src, f in zip(got, frames): |
| src.rename(img_dir / f"{f:08d}.jpg") |
| shutil.rmtree(tmp) |
|
|
| if masks: |
| |
| |
| mdir = img_dir / "mask" |
| mdir.mkdir(exist_ok=True) |
| tmp.mkdir(exist_ok=True) |
| subprocess.run( |
| ["ffmpeg", "-y", "-v", "error", "-threads", "1", "-i", str(video), |
| "-vf", f"select='{sel}',crop={rgb_w}:in_h:{rgb_w}:0,format=gray", "-vsync", "0", |
| str(tmp / "%08d.png")], |
| check=True) |
| for src, f in zip(sorted(tmp.glob("*.png")), frames): |
| src.rename(mdir / f"{f:08d}.png") |
| shutil.rmtree(tmp) |
| return cam, len(frames) |
|
|
|
|
| |
| def write_smplx(cap: Capture, out: Path, frames: list[int]) -> None: |
| sdir = out / "smplx" |
| sdir.mkdir(parents=True, exist_ok=True) |
| stack = {k: [] for k in PARAM_KEYS} |
| for f in frames: |
| p = cap.smplx_params(f, batched=True) |
| np.savez(sdir / f"{f:08d}.npz", **p) |
| for k in PARAM_KEYS: |
| stack[k].append(p[k][0]) |
| np.savez_compressed(out / "smplx_params.npz", |
| frames=np.asarray(frames, np.int32), |
| **{k: np.stack(v) for k, v in stack.items()}, |
| smplx_kwargs=np.asarray(json.dumps(cap.smplx_forward_kwargs))) |
| print(f"[smplx] {len(frames)} per-frame npz in {sdir} + smplx_params.npz", flush=True) |
|
|
|
|
| |
| def prepare(capture_dir: Path, out: Path, stride: int, start: int | None, end: int | None, |
| cams: list[int] | None, masks: bool, quality: int, workers: int, |
| jpg_dir_fmt: str, dry_run: bool) -> dict: |
| cap = Capture(capture_dir) |
| print(cap, flush=True) |
| out.mkdir(parents=True, exist_ok=True) |
|
|
| frames = [int(f) for f in cap.frames] |
| if start is not None: |
| frames = [f for f in frames if f >= start] |
| if end is not None: |
| frames = [f for f in frames if f <= end] |
| frames = frames[::stride] |
| names = ([f"cam{c:02d}" for c in cams] if cams else sorted(cap.cameras)) |
| missing = [n for n in names if not (cap.video_dir / f"{n}.mp4").exists()] |
| if missing: |
| raise SystemExit(f"missing videos: {missing}") |
|
|
| rgb_w = next(iter(cap.cameras.values())).width |
| print(f"[plan] {len(names)} cams x {len(frames)} frames = {len(names) * len(frames)} images " |
| f"({rgb_w}x{next(iter(cap.cameras.values())).height}), masks={masks}", flush=True) |
| if dry_run: |
| return {"dry_run": True, "cams": names, "n_frames": len(frames)} |
|
|
| write_calibration(cap, out) |
| write_smplx(cap, out, frames) |
|
|
| jobs = [(cap.video_dir / f"{n}.mp4", out, frames, rgb_w, quality, masks, jpg_dir_fmt) |
| for n in names] |
| done = 0 |
| if workers > 1: |
| with ProcessPoolExecutor(max_workers=workers) as ex: |
| futs = {ex.submit(_decode_cam, *j): j[0].stem for j in jobs} |
| for fu in as_completed(futs): |
| cam, n = fu.result() |
| done += n |
| print(f"[img] {cam}: {n} frames ({done}/{len(jobs) * len(frames)})", flush=True) |
| else: |
| for j in jobs: |
| cam, n = _decode_cam(*j) |
| done += n |
| print(f"[img] {cam}: {n} frames ({done}/{len(jobs) * len(frames)})", flush=True) |
|
|
| meta = { |
| "capture": cap.name, |
| "source": str(capture_dir), |
| "cams": names, |
| "frames": {"first": frames[0], "last": frames[-1], "stride": stride, "count": len(frames)}, |
| "image_dir_format": jpg_dir_fmt, |
| "image_name_format": "{frame:08d}.jpg (frame == smplx.npz['frames'] == video index)", |
| "masks": masks, |
| "mask_source": "right 2048 of the 4096-wide mp4 (alpha matte); RGB is the left 2048", |
| "image_size": [rgb_w, next(iter(cap.cameras.values())).height], |
| "calibration": "calibration_full.json, flat {cam: {K,R,T,RT,imgSize}}, " |
| "world-to-camera, SMPL-X Y-up world (world_flip already applied)", |
| "smplx_kwargs": cap.smplx_forward_kwargs, |
| "video_frame_offset": VIDEO_FRAME_OFFSET, |
| "status": "PROPOSED training contract -- reconcile with the trainer in the retrain phase", |
| } |
| (out / "meta.json").write_text(json.dumps(meta, indent=2) + "\n") |
| print(f"[done] {out}", flush=True) |
| return meta |
|
|
|
|
| def main() -> int: |
| ap = argparse.ArgumentParser(description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| ap.add_argument("capture_dir", type=Path, help="data/<PxCy>") |
| ap.add_argument("--out", type=Path, required=True) |
| ap.add_argument("--stride", type=int, default=1) |
| ap.add_argument("--start", type=int, default=None, help="first GT frame") |
| ap.add_argument("--end", type=int, default=None, help="last GT frame") |
| ap.add_argument("--cams", type=int, nargs="*", default=None, help="camera indices, default all") |
| ap.add_argument("--no-masks", dest="masks", action="store_false", |
| help="skip the alpha matte (it is emitted by default: the mask from " |
| "the mp4's right half is a training input)") |
| ap.set_defaults(masks=True) |
| ap.add_argument("--quality", type=int, default=2, help="ffmpeg -q:v (2 = near-lossless jpg)") |
| ap.add_argument("--workers", type=int, default=4) |
| ap.add_argument("--dir-format", default="cam_{cam}", |
| help="per-camera image dir, e.g. 'cam_{cam}' -> cam_cam00/") |
| ap.add_argument("--dry-run", action="store_true") |
| a = ap.parse_args() |
| prepare(a.capture_dir, a.out, a.stride, a.start, a.end, a.cams, a.masks, |
| a.quality, a.workers, a.dir_format, a.dry_run) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|