initialneil commited on
Commit
919e0dd
·
verified ·
1 Parent(s): ef97c58

Add dreams_to_actorshq.py + README: prepare DREAMS-AVATAR for an ActorsHQ loader

Browse files
Files changed (2) hide show
  1. README.md +146 -0
  2. scripts/dreams_to_actorshq.py +580 -0
README.md CHANGED
@@ -109,6 +109,8 @@ previews/
109
  assets/showcase/ the 3-panel images used above
110
  scripts/
111
  load_capture.py minimal reader: videos + smplx + cameras
 
 
112
  prepare_training.py decode into an AvatarReX / DEGAS training layout
113
  upload_capture.sh packaging + upload pipeline (for maintainers)
114
  ```
@@ -292,6 +294,150 @@ change costs one ffmpeg pass per camera.
292
 
293
  ---
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  ## How the registration was produced
296
 
297
  [Holistic-Multiview-Tracker](https://github.com/initialneil/Holistic-Multiview-Tracker),
 
109
  assets/showcase/ the 3-panel images used above
110
  scripts/
111
  load_capture.py minimal reader: videos + smplx + cameras
112
+ dreams_to_actorshq.py convert a capture into an ActorsHQ-format tree
113
+ verify_alignment.py re-measure the video<->SMPL-X frame offset
114
  prepare_training.py decode into an AvatarReX / DEGAS training layout
115
  upload_capture.sh packaging + upload pipeline (for maintainers)
116
  ```
 
294
 
295
  ---
296
 
297
+ ## Prepare for an ActorsHQ loader
298
+
299
+ Most full-body avatar codebases already read the **ActorsHQ** layout. `scripts/dreams_to_actorshq.py`
300
+ writes one, so an *unmodified* ActorsHQ reader can train on DREAMS-AVATAR without knowing
301
+ anything about mp4 halves or Y-down calibration.
302
+
303
+ ### 1. Download
304
+
305
+ ```bash
306
+ pip install "huggingface_hub[cli]" numpy opencv-python torch # torch only for the .pt
307
+ huggingface-cli download initialneil/DREAMS-AVATAR --repo-type dataset \
308
+ --local-dir ./DREAMS-AVATAR
309
+ ```
310
+
311
+ One capture is ~2 GiB, so pull only what you need:
312
+
313
+ ```bash
314
+ huggingface-cli download initialneil/DREAMS-AVATAR --repo-type dataset \
315
+ --include "data/P1C1/*" "scripts/*" --local-dir ./DREAMS-AVATAR
316
+ ```
317
+
318
+ Equivalent from Python:
319
+
320
+ ```python
321
+ from huggingface_hub import snapshot_download
322
+ snapshot_download("initialneil/DREAMS-AVATAR", repo_type="dataset",
323
+ allow_patterns=["data/P1C1/*", "scripts/*"],
324
+ local_dir="./DREAMS-AVATAR")
325
+ ```
326
+
327
+ `load_dataset("initialneil/DREAMS-AVATAR")` gives you the **QC preview index only** (the
328
+ `imagefolder` build over `previews/`) — it is for browsing in the Data tab, not for
329
+ training. Training needs the files on disk, so use `huggingface-cli download` /
330
+ `snapshot_download`.
331
+
332
+ ### 2. Convert a capture
333
+
334
+ ```bash
335
+ cd DREAMS-AVATAR
336
+ python scripts/dreams_to_actorshq.py --capture-dir data/P1C1 --out actorshq/P1C1
337
+ ```
338
+
339
+ Needs `ffmpeg` on `PATH`. Full-resolution, all 32 cameras, all 1836 frames is ~59k images;
340
+ subset while you are still wiring things up:
341
+
342
+ ```bash
343
+ python scripts/dreams_to_actorshq.py --capture-dir data/P1C1 --out actorshq/P1C1 \
344
+ --scale 2x --stride 4 --cams 0 2 4 6 8 10 12 14 --workers 8 \
345
+ --smplx-model-dir /path/to/smplx --verify
346
+ ```
347
+
348
+ | flag | effect |
349
+ |---|---|
350
+ | `--scale 1x\|2x\|4x` | image size: `2048x1500` / `1024x750` / `512x375`. `calibration.csv` stores focal and principal point **normalised**, so the same rows are valid at every scale; only `w,h` change. Default `2x`. |
351
+ | `--stride`, `--frames A B` | frame subset (frame ids, not row numbers) |
352
+ | `--cams` | which cameras to **decode**. `calibration.csv` always holds all 32 (see the warning below). |
353
+ | `--smplx-model-dir` | dir with `SMPLX_NEUTRAL.npz`; lets the compat `.npz` fold in `hands_mean` |
354
+ | `--verify` | re-projects the SMPL-X joints through `cameras.json` and through the emitted csv and fails if they disagree by more than 1e-3 px |
355
+ | `--no-masks`, `--no-images` | skip the alpha mattes / skip decoding entirely |
356
+
357
+ Output:
358
+
359
+ ```
360
+ actorshq/P1C1/
361
+ 2x/
362
+ calibration.csv ActorsHQ convention, all 32 cameras
363
+ rgbs/Cam001/Cam001_rgb000000.jpg ... the mp4's LEFT half
364
+ masks/Cam001/Cam001_mask000000.png ... the mp4's RIGHT half (alpha matte)
365
+ smplx_dreams.pt SMPL-X, lossless, with model metadata
366
+ smpl_params.npz SMPL-X, float arrays only (compat)
367
+ dreams_meta.json what was emitted, and under which conventions
368
+ ```
369
+
370
+ ### 3. Point the loader at it
371
+
372
+ `calibration.csv` is exactly Synthesia's:
373
+
374
+ ```
375
+ name,w,h,rx,ry,rz,tx,ty,tz,fx,fy,px,py
376
+ ```
377
+
378
+ `(rx,ry,rz)` is the axis-angle of the **camera-to-world** rotation, `(tx,ty,tz)` is the
379
+ **camera centre in world space**, and `fx,fy,px,py` are **normalised** by `w,h`
380
+ (`fx_pixels = fx * w`). That is what `actorshq.dataset.camera_data.read_calibration_csv`
381
+ expects, and what DEGAS's own `read_ActorsHQ_cameras` reconstructs as
382
+ `R = Rodrigues(rvec).T`, `c = (tx,ty,tz)`.
383
+
384
+ > **Camera numbering.** ActorsHQ readers derive the image folder from the calibration
385
+ > **row index** (`Cam%03d % (i+1)`), not from the `name` column. So the csv is always
386
+ > written **dense**: row `i` is DREAMS `cam{i:02d}` is `Cam{i+1:03d}`, whether or not that
387
+ > camera was decoded. A 1-based `cam_select` in your config therefore means what it looks
388
+ > like it means. Do not filter rows out of the csv.
389
+
390
+ SMPL-X is not part of the ActorsHQ spec (ActorsHQ ships none), so two files are written:
391
+
392
+ * **`smplx_dreams.pt`** — `torch.load` → dict. Lossless: keeps `flat_hand_mean=False`,
393
+ `num_betas=300`, `num_expression_coeffs=100`, plus `gender`/`model_type`/`use_pca`.
394
+ **Prefer this one.** In DEGAS: `smplx_type: smplx_dreams.pt`.
395
+ * **`smpl_params.npz`** — float arrays only, the AnimatableGaussians-style file some
396
+ readers insist on. An `.npz` cannot carry the model metadata (a loader that turns every
397
+ array into a tensor chokes on strings and 0-d scalars), which costs two things:
398
+ `flat_hand_mean` is assumed `True`, so `hands_mean` is **folded into the hand poses**
399
+ (needs `--smplx-model-dir`); and `num_expression_coeffs` cannot be expressed, so
400
+ `expression` is **omitted** by default (`--npz-expression-coeffs 10` writes the leading
401
+ 10 instead). Geometry is otherwise identical; only the face is dropped.
402
+
403
+ Both are indexed so that **row index == frame id**, matching the `%06d` in the image
404
+ filenames, because ActorsHQ-style loaders index the SMPL-X arrays with the raw frame
405
+ number.
406
+
407
+ ### Things worth knowing before you start
408
+
409
+ * **`videos/camNN.mp4` is 4096x1500 and holds two images**: LEFT 2048 = matted RGB,
410
+ RIGHT 2048 = the alpha matte. The converter splits them into `rgbs/` and `masks/`.
411
+ * **There is no frame offset (d = 0)**: `smplx.npz["frames"][i]` is the mp4 frame index is
412
+ the number in the emitted filenames. Re-derive it yourself with
413
+ `scripts/verify_alignment.py`.
414
+ * **`C1` is the train capture and `C2` the test capture** of the same subject. Convert both
415
+ and hold `C2` out; `P5`/`P6` ship `C2` only, as cross-reenactment driving sequences.
416
+ * The world is **Y-up** everywhere in the emitted tree — the `cameras.json` Y-down flip is
417
+ baked into the calibration, so cameras and SMPL-X share one frame.
418
+
419
+ ### Not using ActorsHQ? DEGAS reads this dataset natively
420
+
421
+ If you are training [DEGAS](https://initialneil.github.io/DEGAS) itself, there is no need
422
+ to convert or to duplicate ~40 GB of jpgs. DEGAS has a `frameset_type: dreams` reader that
423
+ consumes `cameras.json` + `smplx.npz` + the mp4s directly and decodes only the
424
+ (camera, frame) pairs a split asks for into a local cache:
425
+
426
+ ```yaml
427
+ dataset:
428
+ dat_dir: /path/to/DREAMS-AVATAR/data/P1C1
429
+ frameset_type: dreams
430
+ scale: 2x
431
+ resolution: 1
432
+ train: {frm_list: np.arange(0, 1836, 4).tolist(), cam_select: [0, 2, 4, 6], mini_batch: 1}
433
+ ```
434
+
435
+ `cam_select` is **0-based** there (`cam00`..`cam31`, matching the mp4 names), unlike the
436
+ 1-based ActorsHQ path. The two paths are checked against each other: identical cameras,
437
+ byte-identical decoded RGB and masks, identical SMPL-X tensors.
438
+
439
+ ---
440
+
441
  ## How the registration was produced
442
 
443
  [Holistic-Multiview-Tracker](https://github.com/initialneil/Holistic-Multiview-Tracker),
scripts/dreams_to_actorshq.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Convert one DREAMS-AVATAR capture into an on-disk **ActorsHQ-format** tree.
3
+
4
+ Goal: an UNMODIFIED ActorsHQ reader -- DEGAS's own `dataset/actorshq_data.py`, or
5
+ Synthesia's `actorshq.dataset.camera_data`, or anything else that speaks the
6
+ ActorsHQ layout -- can open the result and train, with no knowledge that the data
7
+ came from a video bundle.
8
+
9
+ huggingface-cli download initialneil/DREAMS-AVATAR --repo-type dataset \
10
+ --local-dir DREAMS-AVATAR
11
+ cd DREAMS-AVATAR
12
+ python scripts/dreams_to_actorshq.py --capture-dir data/P1C1 --out actorshq/P1C1
13
+
14
+ Needs only numpy + ffmpeg on PATH (torch too, but only for the optional `.pt`).
15
+ Subsetting, for a quick look or a smoke train:
16
+
17
+ python scripts/dreams_to_actorshq.py --capture-dir data/P1C1 --out actorshq/P1C1 \
18
+ --scale 2x --stride 4 --cams 0 3 6 9 12 15 18 21 --workers 8
19
+
20
+ OUTPUT TREE
21
+ <out>/
22
+ <scale>/ e.g. 1x, 2x, 4x (ActorsHQ calls this the "scale" dir)
23
+ calibration.csv ActorsHQ calibration, exact column order
24
+ rgbs/Cam001/Cam001_rgb000000.jpg ...
25
+ masks/Cam001/Cam001_mask000000.png ...
26
+ smplx_dreams.pt LOSSLESS SMPL-X, full metadata <- use this one
27
+ smpl_params.npz float-array-only compat file <- see CAVEAT below
28
+ dreams_meta.json what was emitted, and with which conventions
29
+
30
+ ============================== THE CALIBRATION ==============================
31
+ ActorsHQ `calibration.csv` (verified against synthesiaresearch/humanrf
32
+ `actorshq/dataset/camera_data.py`) is:
33
+
34
+ name,w,h,rx,ry,rz,tx,ty,tz,fx,fy,px,py
35
+
36
+ * (rx,ry,rz) axis-angle of the **camera-to-world** rotation.
37
+ world = R_c2w @ cam + t (their docstring, verbatim)
38
+ * (tx,ty,tz) the **camera centre in world space** -- NOT the w2c translation.
39
+ * (fx,fy) focal length **normalised**: fx_pixels = fx * w, fy_pixels = fy * h
40
+ * (px,py) principal point **normalised**: cx_pixels = px * w, cy = py * h
41
+
42
+ DREAMS-AVATAR ships the DEGAS-native rig calibration instead:
43
+ `cameras.json` -> rigs[i].cameras[0] with fx,fy,cx,cy in pixels, `R`, and the camera
44
+ centre `c`, in a **Y-down** world. `capture.json["camera_convention"]` fixes the
45
+ mapping to the Y-up world the SMPL-X fit lives in:
46
+
47
+ A = diag(1, -1, -1) # world_flip, Y-down -> Y-up
48
+ R_w2c = R_json @ A
49
+ t_w2c = -R_json @ c_json
50
+
51
+ so the ActorsHQ row for camera i is
52
+
53
+ R_c2w = R_w2c.T = A @ R_json.T (A is symmetric and A@A = I)
54
+ rx,ry,rz = Rodrigues(R_c2w)
55
+ tx,ty,tz = -R_w2c.T @ t_w2c = A @ c_json # centre, moved into the Y-up world
56
+ fx = fx_px / w ; fy = fy_px / h ; px = cx_px / w ; py = cy_px / h
57
+
58
+ Because the focal/principal are normalised, the SAME csv row is valid at every
59
+ `--scale`; only `w` and `h` change. That is why the scale dir owns its own csv.
60
+
61
+ Round-trip sanity: DEGAS's reader does `cam.R = Rodrigues(rvec).T ; cam.c = t`, and
62
+ its `libcore.Camera.t` property is `-R @ c`. So it recovers exactly (R_w2c, t_w2c).
63
+ `--verify` re-projects the SMPL-X joints through both paths and asserts they agree.
64
+
65
+ ============================== THE IMAGES ==============================
66
+ Each `videos/camNN.mp4` is 4096x1500 and holds two things side by side:
67
+ LEFT 2048 = matted RGB, RIGHT 2048 = the alpha matte (binary silhouette). One
68
+ ffmpeg pass per camera per half. ActorsHQ camera `Cam%03d` is 1-based, so DREAMS
69
+ `cam00` becomes `Cam001`. File numbering is the GT frame id, `%06d`, which is the
70
+ same number that indexes `smplx.npz` (frame offset d = 0).
71
+
72
+ ============================== THE SMPL-X ==============================
73
+ ActorsHQ itself ships **no** SMPL-X; DEGAS reads a registration file next to the
74
+ scale dir, chosen by `dataset.smplx_type`, and supports two formats:
75
+
76
+ `.pt` torch.load -> dict. Non-tensor entries pass through untouched, so the
77
+ model metadata survives. **This is the lossless path.** We write
78
+ `smplx_dreams.pt` with gender/model_type/use_pca/flat_hand_mean/
79
+ num_betas(300)/num_expression_coeffs(100) plus every per-frame tensor.
80
+ Config: `smplx_type: smplx_dreams.pt`
81
+
82
+ `.npz` `dataset/dataset_utils.py:load_smplx_npz` turns EVERY array into a
83
+ tensor and then indexes anything with shape[0] > 1. A 0-d scalar or a
84
+ string in the npz therefore crashes it, so an npz can only carry the
85
+ per-frame float arrays. Two consequences, both handled here:
86
+ 1. `flat_hand_mean` defaults to True in that loader, but the DREAMS fit
87
+ is flat_hand_mean=False. We bake the difference in:
88
+ hand_pose_npz = hand_pose_dreams + hands_mean
89
+ (smplx does `full_pose += pose_mean`, and pose_mean carries
90
+ hands_meanl/r only when flat_hand_mean=False -- so adding the mean
91
+ makes a flat_hand_mean=True model reproduce the same hands).
92
+ Needs `--smplx-model-dir` (reads hands_meanl/hands_meanr straight
93
+ out of SMPLX_NEUTRAL.npz with numpy; the smplx package is not
94
+ imported).
95
+ 2. `num_expression_coeffs` cannot be expressed, so the loader would
96
+ build a 10-coefficient model and choke on our (N,100) expression.
97
+ By default `expression` is OMITTED from the npz -- which is also
98
+ what DEGAS's own ActorsHQ configs effectively do
99
+ (`smplx_nofacial: exp+jaw`). `--npz-expression-coeffs 10` writes
100
+ the leading 10 instead. Either way the npz is a COMPAT artifact:
101
+ for full fidelity use the .pt.
102
+
103
+ Row index == frame id. `load_smplx_npz` indexes the arrays with the raw frame
104
+ numbers from `frm_list`, so the arrays are emitted at full length
105
+ (max(frame)+1 rows) and rows for frames without a fit are filled with the nearest
106
+ preceding fit. `dreams_meta.json["smplx"]["valid_rows"]` records which are real.
107
+ """
108
+ from __future__ import annotations
109
+
110
+ import argparse
111
+ import csv
112
+ import json
113
+ import shutil
114
+ import subprocess
115
+ import sys
116
+ from concurrent.futures import ProcessPoolExecutor, as_completed
117
+ from pathlib import Path
118
+
119
+ import numpy as np
120
+
121
+ # --------------------------------------------------------------------------------
122
+ # Self-contained copies of the two conventions, so this script can be dropped into
123
+ # the published dataset repo and run with nothing but numpy + ffmpeg on PATH.
124
+ WORLD_FLIP = np.diag([1.0, -1.0, -1.0]) # cameras.json is Y-down; SMPL-X world is Y-up
125
+ VIDEO_FRAME_OFFSET = 0 # measured per capture by verify_alignment.py
126
+
127
+ PARAM_KEYS = ("global_orient", "body_pose", "jaw_pose", "leye_pose", "reye_pose",
128
+ "left_hand_pose", "right_hand_pose", "betas", "expression", "transl")
129
+
130
+ # per-frame arrays that go into the ActorsHQ-compat npz (expression handled separately)
131
+ NPZ_KEYS = ("global_orient", "body_pose", "jaw_pose", "leye_pose", "reye_pose",
132
+ "left_hand_pose", "right_hand_pose", "betas", "transl")
133
+
134
+ CALIB_HEADER = ["name", "w", "h", "rx", "ry", "rz", "tx", "ty", "tz", "fx", "fy", "px", "py"]
135
+
136
+ SCALES = {"1x": 1, "2x": 2, "4x": 4}
137
+
138
+
139
+ # --------------------------------------------------------------------------- cameras
140
+ def load_dreams_cameras(cameras_json: Path) -> list[dict]:
141
+ """cameras.json -> [{K, R_w2c, t_w2c, w, h, info}, ...]; index i == videos/cam{i:02d}.mp4."""
142
+ d = json.loads(cameras_json.read_text())
143
+ out = []
144
+ for rig in d["rigs"]:
145
+ c = rig["cameras"][0]
146
+ K = np.array([[c["fx"], 0.0, c["cx"]],
147
+ [0.0, c["fy"], c["cy"]],
148
+ [0.0, 0.0, 1.0]], np.float64)
149
+ R = np.asarray(c["R"], np.float64).reshape(3, 3)
150
+ C = np.asarray(c["c"], np.float64).reshape(3)
151
+ out.append({
152
+ "K": K,
153
+ "R_w2c": R @ WORLD_FLIP,
154
+ "t_w2c": -R @ C,
155
+ "w": int(c["w"]),
156
+ "h": int(c["h"]),
157
+ "info": str(c.get("info", "")),
158
+ })
159
+ return out
160
+
161
+
162
+ def orthonormalize(R: np.ndarray) -> np.ndarray:
163
+ """Nearest true rotation to R (SVD). cameras.json rows are ~1e-7 off orthonormal, and
164
+ axis-angle can only represent an exact rotation, so project before converting."""
165
+ U, _, Vt = np.linalg.svd(R)
166
+ S = np.eye(3)
167
+ S[2, 2] = np.sign(np.linalg.det(U @ Vt))
168
+ return U @ S @ Vt
169
+
170
+
171
+ def rodrigues(R: np.ndarray) -> np.ndarray:
172
+ """Rotation matrix -> axis-angle vector, via a quaternion.
173
+
174
+ NOT the textbook `axis = (R - R.T) / (2 sin th)`: that divides by sin(th), so it
175
+ bleeds precision as th approaches pi, and several of these rigs sit there. Measured
176
+ on P1C1 the naive form round-tripped to only 4e-3 (worst camera, and cv2.Rodrigues
177
+ is no better); Shepperd's branch-on-the-largest-diagonal quaternion form round-trips
178
+ to ~1e-15 everywhere.
179
+ """
180
+ R = orthonormalize(np.asarray(R, np.float64))
181
+ m00, m01, m02 = R[0]
182
+ m10, m11, m12 = R[1]
183
+ m20, m21, m22 = R[2]
184
+ tr = m00 + m11 + m22
185
+ if tr > 0.0:
186
+ s = np.sqrt(tr + 1.0) * 2.0
187
+ qw, qx, qy, qz = 0.25 * s, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
188
+ elif m00 > m11 and m00 > m22:
189
+ s = np.sqrt(1.0 + m00 - m11 - m22) * 2.0
190
+ qw, qx, qy, qz = (m21 - m12) / s, 0.25 * s, (m01 + m10) / s, (m02 + m20) / s
191
+ elif m11 > m22:
192
+ s = np.sqrt(1.0 + m11 - m00 - m22) * 2.0
193
+ qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, 0.25 * s, (m12 + m21) / s
194
+ else:
195
+ s = np.sqrt(1.0 + m22 - m00 - m11) * 2.0
196
+ qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, 0.25 * s
197
+
198
+ q = np.array([qw, qx, qy, qz], np.float64)
199
+ q /= np.linalg.norm(q)
200
+ if q[0] < 0:
201
+ q = -q # shortest arc, so |theta| <= pi
202
+ v = q[1:]
203
+ nv = float(np.linalg.norm(v))
204
+ if nv < 1e-15:
205
+ return np.zeros(3)
206
+ theta = 2.0 * np.arctan2(nv, q[0])
207
+ return v / nv * theta
208
+
209
+
210
+ def rodrigues_inv(rvec: np.ndarray) -> np.ndarray:
211
+ """Axis-angle -> rotation matrix (only used by --verify)."""
212
+ theta = float(np.linalg.norm(rvec))
213
+ if theta < 1e-12:
214
+ return np.eye(3)
215
+ k = rvec / theta
216
+ K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
217
+ return np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K)
218
+
219
+
220
+ def actorshq_rows(cams: list[dict], cam_ids: list[int], down: int) -> list[list]:
221
+ """ActorsHQ calibration.csv rows, at 1/`down` resolution.
222
+
223
+ ALWAYS every camera, even when only a subset is decoded. ActorsHQ readers derive the
224
+ image folder from the ROW INDEX -- DEGAS's is literally
225
+ `cam_sn = 'Cam%03d' % (cam_id + 1)` over `range(len(cams))` -- and ignore the `name`
226
+ column. A csv holding only the decoded cameras would therefore silently shift every
227
+ camera onto the wrong images. Keeping it dense makes row i == DREAMS cam{i:02d} ==
228
+ Cam{i+1:03d}, so a config's 1-based `cam_select` means what it looks like it means.
229
+ Rows for cameras that were not decoded are still correct calibration; the reader only
230
+ touches the ones `cam_select` asks for.
231
+ """
232
+ rows = []
233
+ for i in range(len(cams)):
234
+ c = cams[i]
235
+ R_c2w = c["R_w2c"].T
236
+ centre = -c["R_w2c"].T @ c["t_w2c"]
237
+ rvec = rodrigues(R_c2w)
238
+ w, h = c["w"] // down, c["h"] // down
239
+ rows.append([
240
+ "Cam%03d" % (i + 1), w, h,
241
+ rvec[0], rvec[1], rvec[2],
242
+ centre[0], centre[1], centre[2],
243
+ # normalised -- scale-invariant, so `down` never enters here
244
+ c["K"][0, 0] / c["w"], c["K"][1, 1] / c["h"],
245
+ c["K"][0, 2] / c["w"], c["K"][1, 2] / c["h"],
246
+ ])
247
+ return rows
248
+
249
+
250
+ def write_calibration(rows: list[list], path: Path) -> None:
251
+ path.parent.mkdir(parents=True, exist_ok=True)
252
+ with path.open("w", newline="") as fp:
253
+ w = csv.writer(fp)
254
+ w.writerow(CALIB_HEADER)
255
+ for r in rows:
256
+ w.writerow(r)
257
+ print(f"[calib] {path} ({len(rows)} cameras)", flush=True)
258
+
259
+
260
+ def verify_calibration(cams: list[dict], rows: list[list],
261
+ joints: np.ndarray, down: int) -> float:
262
+ """Re-project `joints` through cameras.json and through the emitted csv; max |du,dv|."""
263
+ worst = 0.0
264
+ for i, row in enumerate(rows):
265
+ c = cams[i]
266
+ # native path
267
+ x = joints @ c["R_w2c"].T + c["t_w2c"]
268
+ uv_native = (x @ c["K"].T)[:, :2] / x[:, 2:3] / down
269
+ # ActorsHQ path, replayed exactly as DEGAS's reader does it
270
+ rvec = np.array(row[3:6], float)
271
+ R_w2c = rodrigues_inv(rvec).T
272
+ centre = np.array(row[6:9], float)
273
+ t_w2c = -R_w2c @ centre
274
+ w, h = int(row[1]), int(row[2])
275
+ K = np.array([[row[9] * w, 0, row[11] * w],
276
+ [0, row[10] * h, row[12] * h],
277
+ [0, 0, 1.0]])
278
+ x2 = joints @ R_w2c.T + t_w2c
279
+ uv_ahq = (x2 @ K.T)[:, :2] / x2[:, 2:3]
280
+ worst = max(worst, float(np.abs(uv_native - uv_ahq).max()))
281
+ return worst
282
+
283
+
284
+ # ---------------------------------------------------------------------------- images
285
+ def _select_expr(frames: list[int]) -> str:
286
+ """ffmpeg select expression for a video-frame list; compact for arithmetic runs."""
287
+ v = [f + VIDEO_FRAME_OFFSET for f in frames]
288
+ if len(v) > 1:
289
+ step = v[1] - v[0]
290
+ if step > 0 and all(b - a == step for a, b in zip(v, v[1:])):
291
+ if step == 1:
292
+ return f"between(n\\,{v[0]}\\,{v[-1]})"
293
+ return f"between(n\\,{v[0]}\\,{v[-1]})*not(mod(n-{v[0]}\\,{step}))"
294
+ return "+".join(f"eq(n\\,{n})" for n in v)
295
+
296
+
297
+ def _decode_cam(video: Path, out_root: Path, cam_id: int, frames: list[int],
298
+ rgb_w: int, rgb_h: int, down: int, quality: int, masks: bool) -> tuple[str, int]:
299
+ """Two ffmpeg passes for one camera: LEFT half -> rgbs/, RIGHT half -> masks/."""
300
+ sn = "Cam%03d" % (cam_id + 1)
301
+ sel = _select_expr(frames)
302
+ w, h = rgb_w // down, rgb_h // down
303
+ scale = "" if down == 1 else f",scale={w}:{h}:flags=area"
304
+
305
+ img_dir = out_root / "rgbs" / sn
306
+ img_dir.mkdir(parents=True, exist_ok=True)
307
+ tmp = img_dir / "_tmp"
308
+ if tmp.exists():
309
+ shutil.rmtree(tmp)
310
+ tmp.mkdir()
311
+ subprocess.run(
312
+ ["ffmpeg", "-y", "-v", "error", "-threads", "1", "-i", str(video),
313
+ "-vf", f"select='{sel}',crop={rgb_w}:in_h:0:0{scale}", "-vsync", "0",
314
+ "-q:v", str(quality), str(tmp / "%08d.jpg")],
315
+ check=True)
316
+ got = sorted(tmp.glob("*.jpg"))
317
+ if len(got) != len(frames):
318
+ raise RuntimeError(f"{sn}: ffmpeg produced {len(got)} rgb frames, wanted {len(frames)}")
319
+ for src, f in zip(got, frames):
320
+ src.rename(img_dir / f"{sn}_rgb{f:06d}.jpg")
321
+ shutil.rmtree(tmp)
322
+
323
+ if masks:
324
+ msk_dir = out_root / "masks" / sn
325
+ msk_dir.mkdir(parents=True, exist_ok=True)
326
+ tmp.mkdir()
327
+ subprocess.run(
328
+ ["ffmpeg", "-y", "-v", "error", "-threads", "1", "-i", str(video),
329
+ "-vf", f"select='{sel}',crop={rgb_w}:in_h:{rgb_w}:0{scale},format=gray",
330
+ "-vsync", "0", "-pix_fmt", "gray", str(tmp / "%08d.png")],
331
+ check=True)
332
+ got = sorted(tmp.glob("*.png"))
333
+ if len(got) != len(frames):
334
+ raise RuntimeError(f"{sn}: ffmpeg produced {len(got)} masks, wanted {len(frames)}")
335
+ for src, f in zip(got, frames):
336
+ src.rename(msk_dir / f"{sn}_mask{f:06d}.png")
337
+ shutil.rmtree(tmp)
338
+
339
+ return sn, len(frames)
340
+
341
+
342
+ # ---------------------------------------------------------------------------- smplx
343
+ def _dense(arr: np.ndarray, frames: np.ndarray, n_rows: int) -> np.ndarray:
344
+ """Scatter (T,...) fit rows to (n_rows,...) indexed by frame id; gaps hold-forward."""
345
+ out = np.zeros((n_rows, *arr.shape[1:]), arr.dtype)
346
+ filled = np.zeros(n_rows, bool)
347
+ out[frames] = arr
348
+ filled[frames] = True
349
+ last = None
350
+ for i in range(n_rows):
351
+ if filled[i]:
352
+ last = i
353
+ elif last is not None:
354
+ out[i] = out[last]
355
+ if last is None:
356
+ return out
357
+ first = int(frames.min())
358
+ out[:first] = out[first]
359
+ return out
360
+
361
+
362
+ def read_hands_mean(model_dir: Path, gender: str = "neutral") -> tuple[np.ndarray, np.ndarray]:
363
+ """(hands_meanl, hands_meanr) straight out of SMPLX_<GENDER>.npz -- no smplx import."""
364
+ fn = model_dir / f"SMPLX_{gender.upper()}.npz"
365
+ if not fn.exists():
366
+ fn = model_dir / "smplx" / f"SMPLX_{gender.upper()}.npz"
367
+ if not fn.exists():
368
+ raise FileNotFoundError(f"no SMPLX_{gender.upper()}.npz under {model_dir}")
369
+ z = np.load(fn, allow_pickle=True)
370
+ return (np.asarray(z["hands_meanl"], np.float64).reshape(-1),
371
+ np.asarray(z["hands_meanr"], np.float64).reshape(-1))
372
+
373
+
374
+ def write_smplx(z: dict, frames: np.ndarray, out: Path, kwargs: dict,
375
+ smplx_model_dir: Path | None, npz_expr_coeffs: int) -> dict:
376
+ """Write smplx_dreams.pt (lossless) and smpl_params.npz (ActorsHQ compat)."""
377
+ import torch
378
+
379
+ n_rows = int(frames.max()) + 1
380
+ note = {}
381
+
382
+ # ---- lossless .pt: tensors + the metadata SMPLXOptimizer.init_keys asks for
383
+ pt = {k: torch.from_numpy(_dense(z[k], frames, n_rows).astype(np.float32))
384
+ for k in PARAM_KEYS if k in z}
385
+ pt.update({
386
+ "gender": str(kwargs.get("gender", "neutral")),
387
+ "model_type": str(kwargs.get("model_type", "smplx")),
388
+ "use_pca": bool(kwargs.get("use_pca", False)),
389
+ "flat_hand_mean": bool(kwargs.get("flat_hand_mean", False)),
390
+ "num_betas": int(z["betas"].shape[-1]),
391
+ "num_expression_coeffs": int(z["expression"].shape[-1]) if "expression" in z else 10,
392
+ })
393
+ pt_fn = out / "smplx_dreams.pt"
394
+ torch.save(pt, pt_fn)
395
+ print(f"[smplx] {pt_fn} ({n_rows} rows, lossless, flat_hand_mean="
396
+ f"{pt['flat_hand_mean']}, num_betas={pt['num_betas']}, "
397
+ f"num_expression_coeffs={pt['num_expression_coeffs']})", flush=True)
398
+ note["pt"] = pt_fn.name
399
+
400
+ # ---- ActorsHQ-compat .npz: float arrays only
401
+ npz = {k: _dense(z[k], frames, n_rows).astype(np.float32) for k in NPZ_KEYS if k in z}
402
+
403
+ if not bool(kwargs.get("flat_hand_mean", False)):
404
+ if smplx_model_dir is None:
405
+ note["npz_hands"] = "RAW -- no --smplx-model-dir given, hands are WRONG for a " \
406
+ "flat_hand_mean=True reader"
407
+ print("[smplx][WARN] no --smplx-model-dir: smpl_params.npz hand poses are NOT "
408
+ "converted to the flat_hand_mean=True convention that load_smplx_npz "
409
+ "assumes. Use smplx_dreams.pt, or re-run with --smplx-model-dir.",
410
+ flush=True)
411
+ else:
412
+ ml, mr = read_hands_mean(Path(smplx_model_dir), str(kwargs.get("gender", "neutral")))
413
+ npz["left_hand_pose"] = (npz["left_hand_pose"] + ml).astype(np.float32)
414
+ npz["right_hand_pose"] = (npz["right_hand_pose"] + mr).astype(np.float32)
415
+ note["npz_hands"] = "hands_mean folded in (flat_hand_mean False -> True)"
416
+ else:
417
+ note["npz_hands"] = "already flat_hand_mean=True"
418
+
419
+ if npz_expr_coeffs > 0 and "expression" in z:
420
+ npz["expression"] = _dense(z["expression"], frames, n_rows)[:, :npz_expr_coeffs] \
421
+ .astype(np.float32)
422
+ note["npz_expression"] = f"first {npz_expr_coeffs} coefficients"
423
+ else:
424
+ note["npz_expression"] = "omitted (load_smplx_npz cannot carry " \
425
+ "num_expression_coeffs; the model would default to 10)"
426
+
427
+ npz_fn = out / "smpl_params.npz"
428
+ np.savez(npz_fn, **npz)
429
+ print(f"[smplx] {npz_fn} (compat: {note['npz_hands']}; expression: "
430
+ f"{note['npz_expression']})", flush=True)
431
+ note["npz"] = npz_fn.name
432
+ note["n_rows"] = n_rows
433
+ note["valid_rows"] = [int(frames.min()), int(frames.max())]
434
+ return note
435
+
436
+
437
+ # ----------------------------------------------------------------------------- main
438
+ def main() -> int:
439
+ ap = argparse.ArgumentParser(description=__doc__,
440
+ formatter_class=argparse.RawDescriptionHelpFormatter)
441
+ ap.add_argument("capture_dir_pos", type=Path, nargs="?", default=None,
442
+ help=argparse.SUPPRESS)
443
+ ap.add_argument("--capture-dir", type=Path, default=None,
444
+ help="DREAMS-AVATAR capture dir, e.g. data/P1C1 (may also be positional)")
445
+ ap.add_argument("--out", type=Path, required=True)
446
+ ap.add_argument("--scale", default="2x", choices=sorted(SCALES),
447
+ help="ActorsHQ scale dir; 2x halves 2048x1500 to 1024x750 (default 2x)")
448
+ ap.add_argument("--cams", type=int, nargs="*", default=None, help="0-based DREAMS cam ids")
449
+ ap.add_argument("--frames", type=int, nargs=2, metavar=("START", "END"), default=None)
450
+ ap.add_argument("--stride", type=int, default=1)
451
+ ap.add_argument("--workers", type=int, default=4)
452
+ ap.add_argument("--quality", type=int, default=2, help="ffmpeg -q:v for the jpgs")
453
+ ap.add_argument("--no-masks", action="store_true")
454
+ ap.add_argument("--no-images", action="store_true", help="calibration + SMPL-X only")
455
+ ap.add_argument("--smplx-model-dir", type=Path, default=None,
456
+ help="dir holding SMPLX_NEUTRAL.npz; needed to fold hands_mean into "
457
+ "smpl_params.npz")
458
+ ap.add_argument("--npz-expression-coeffs", type=int, default=0,
459
+ help="how many expression coefficients to put in smpl_params.npz "
460
+ "(0 = omit; >10 will break an unmodified reader)")
461
+ ap.add_argument("--verify", action="store_true",
462
+ help="re-project SMPL-X joints through cameras.json and through the "
463
+ "emitted csv and report the worst pixel disagreement")
464
+ ap.add_argument("--verify-tol", type=float, default=1e-3,
465
+ help="px; the floor is cameras.json's ~1e-7 orthonormality defect, "
466
+ "which axis-angle has to project away (default 1e-3)")
467
+ a = ap.parse_args()
468
+
469
+ cap = a.capture_dir if a.capture_dir is not None else a.capture_dir_pos
470
+ if cap is None:
471
+ raise SystemExit("give the capture dir, either positionally or with --capture-dir")
472
+ for need in ("cameras.json", "smplx.npz"):
473
+ if not (cap / need).exists():
474
+ raise SystemExit(f"{cap} is not a DREAMS-AVATAR capture dir (no {need}). "
475
+ f"After `huggingface-cli download initialneil/DREAMS-AVATAR "
476
+ f"--repo-type dataset --local-dir DREAMS-AVATAR` the captures "
477
+ f"live at DREAMS-AVATAR/data/<PxCy>/.")
478
+ down = SCALES[a.scale]
479
+ out = a.out
480
+ scale_dir = out / a.scale
481
+ scale_dir.mkdir(parents=True, exist_ok=True)
482
+
483
+ cams = load_dreams_cameras(cap / "cameras.json")
484
+ card = json.loads((cap / "capture.json").read_text()) if (cap / "capture.json").exists() else {}
485
+
486
+ z = dict(np.load(cap / "smplx.npz", allow_pickle=False))
487
+ frames_all = z["frames"].astype(int)
488
+ kwargs = json.loads(str(z["smplx_kwargs"])) if "smplx_kwargs" in z else {}
489
+
490
+ cam_ids = a.cams if a.cams is not None else list(range(len(cams)))
491
+ bad = [i for i in cam_ids if not (0 <= i < len(cams))]
492
+ if bad:
493
+ raise SystemExit(f"camera ids out of range: {bad} (capture has {len(cams)})")
494
+
495
+ frames = frames_all
496
+ if a.frames is not None:
497
+ frames = frames[(frames >= a.frames[0]) & (frames <= a.frames[1])]
498
+ frames = frames[::a.stride]
499
+ frame_list = [int(f) for f in frames]
500
+ if not frame_list:
501
+ raise SystemExit("no frames selected")
502
+
503
+ print(f"[dreams->actorshq] {cap.name}: {len(cam_ids)} cams x {len(frame_list)} frames "
504
+ f"-> {out} (scale {a.scale}, {cams[0]['w'] // down}x{cams[0]['h'] // down})",
505
+ flush=True)
506
+
507
+ rows = actorshq_rows(cams, cam_ids, down)
508
+ write_calibration(rows, scale_dir / "calibration.csv")
509
+
510
+ reproj_err = None
511
+ if a.verify:
512
+ j = z["joints"][int(np.searchsorted(frames_all, frame_list[len(frame_list) // 2]))]
513
+ reproj_err = verify_calibration(cams, rows, j.astype(np.float64), down)
514
+ print(f"[verify] cameras.json vs calibration.csv reprojection: "
515
+ f"max |delta| = {reproj_err:.3e} px (tol {a.verify_tol:g})", flush=True)
516
+ if reproj_err > a.verify_tol:
517
+ raise SystemExit(f"calibration round-trip failed ({reproj_err:.3e} px)")
518
+
519
+ smplx_note = write_smplx(z, frames_all, out, kwargs, a.smplx_model_dir,
520
+ a.npz_expression_coeffs)
521
+
522
+ n_done = 0
523
+ if not a.no_images:
524
+ jobs = []
525
+ with ProcessPoolExecutor(max_workers=a.workers) as ex:
526
+ for i in cam_ids:
527
+ jobs.append(ex.submit(_decode_cam, cap / "videos" / f"cam{i:02d}.mp4",
528
+ scale_dir, i, frame_list,
529
+ cams[i]["w"], cams[i]["h"], down,
530
+ a.quality, not a.no_masks))
531
+ for fut in as_completed(jobs):
532
+ sn, n = fut.result()
533
+ n_done += 1
534
+ print(f"[decode] {sn}: {n} frames ({n_done}/{len(cam_ids)})", flush=True)
535
+
536
+ meta = {
537
+ "source_capture": str(cap),
538
+ "capture": cap.name,
539
+ "format": "ActorsHQ",
540
+ "scale": a.scale,
541
+ "downscale": down,
542
+ "width": cams[0]["w"] // down,
543
+ "height": cams[0]["h"] // down,
544
+ "n_cameras_in_calibration": len(cams),
545
+ "cam_ids_decoded_dreams": cam_ids,
546
+ "cam_names_decoded_actorshq": ["Cam%03d" % (i + 1) for i in cam_ids],
547
+ "cam_select_hint_1based": [i + 1 for i in cam_ids],
548
+ "frames": {"n": len(frame_list), "first": frame_list[0], "last": frame_list[-1],
549
+ "stride": a.stride},
550
+ "frame_convention": card.get("frame_convention", {"offset_d": VIDEO_FRAME_OFFSET}),
551
+ "calibration": {
552
+ "file": f"{a.scale}/calibration.csv",
553
+ "columns": CALIB_HEADER,
554
+ "rotation": "axis-angle of R_cam2world",
555
+ "translation": "camera centre in world space",
556
+ "focal": "normalised by (w, h)",
557
+ "principal_point": "normalised by (w, h)",
558
+ "world": "Y-up (cameras.json world_flip diag(1,-1,-1) applied)",
559
+ "reprojection_max_px_vs_cameras_json": reproj_err,
560
+ },
561
+ "images": {
562
+ "rgb": f"{a.scale}/rgbs/Cam%03d/Cam%03d_rgb%06d.jpg",
563
+ "mask": None if a.no_masks else f"{a.scale}/masks/Cam%03d/Cam%03d_mask%06d.png",
564
+ "note": "rgb is the LEFT half of camNN.mp4, mask is the RIGHT half (alpha matte)",
565
+ },
566
+ "smplx": {**smplx_note, "smplx_kwargs": kwargs},
567
+ "degas_config_hint": {
568
+ "frameset_type": "actorshq",
569
+ "scale": a.scale,
570
+ "smplx_type": "smplx_dreams.pt",
571
+ "resolution": 1,
572
+ },
573
+ }
574
+ (out / "dreams_meta.json").write_text(json.dumps(meta, indent=2) + "\n")
575
+ print(f"[done] {out}", flush=True)
576
+ return 0
577
+
578
+
579
+ if __name__ == "__main__":
580
+ sys.exit(main())