File size: 8,590 Bytes
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
aa991fc
 
 
 
 
 
 
 
358e603
 
 
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
 
aa991fc
 
 
 
358e603
 
 
 
 
 
 
 
 
 
aa991fc
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Consolidate per-frame Holistic-Multiview-Tracker SMPL-X npz -> ONE per-capture smplx.npz.

Source (READ ONLY, produced by the tracker):
    <DEGAS_DATASET>/<PxCy>/hmt_seq_out/smplx/smplx_<gt_frame:08d>.npz

Each per-frame file holds unbatched arrays:
    global_orient(3) body_pose(63) jaw_pose(3) leye_pose(3) reye_pose(3)
    left_hand_pose(45) right_hand_pose(45) betas(300) expression(100) transl(3)
    vertices(10475,3) joints(144,3)
    view_ids(V,) gt_frame() n_face_views() stages()

Output `smplx.npz` stacks every parameter over time, LOSSLESSLY (identical dtypes,
no downcast, no re-quantisation) and adds an explicit frame index:

    frames        int32 (T,)      frame id, == the number in the source filename
    video_frames  int32 (T,)      == frames (offset d=0; kept as an explicit column so a
                                  reader never has to remember whether an offset applies)
    global_orient float32 (T,3)
    body_pose     float32 (T,63)
    jaw_pose      float32 (T,3)
    leye_pose     float32 (T,3)
    reye_pose     float32 (T,3)
    left_hand_pose  float32 (T,45)   axis-angle, use_pca=False
    right_hand_pose float32 (T,45)   axis-angle, use_pca=False
    betas         float32 (T,300)
    expression    float32 (T,100)
    transl        float32 (T,3)
    joints        float32 (T,144,3)  SMPL-X joints in world frame (derived, shipped for convenience)
    view_ids      int16   (T,Vmax)   camera indices actually used at that frame, -1 padded
    n_views       int16   (T,)
    n_face_views  int16   (T,)
    stages        <U..    (T,)       fit schedule for that frame ("A+B+C+F" cold / "W" warm)
    smplx_kwargs  <U..    ()         JSON: exact smplx.SMPLX(...) kwargs to rebuild the model
    meta          <U..    ()         JSON: capture, n_frames, source, tracker commit, ...

`vertices` (10475,3 per frame, ~230 MB per capture) is DERIVED and omitted by default;
pass --with-vertices to also emit <out_dir>/smplx_vertices.npz.

Usage:
    python consolidate_smplx.py P1C1 --out /path/to/staging/data/P1C1/smplx.npz
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from load_capture import VIDEO_FRAME_OFFSET  # noqa: E402  single source of truth for d

DATASET_ROOT = Path("/mnt/sdb/degas_project/DEGAS_DATASET")

# Params that are stacked over time. Order is the SMPL-X forward() kwarg order.
PARAM_KEYS = [
    "global_orient", "body_pose", "jaw_pose", "leye_pose", "reye_pose",
    "left_hand_pose", "right_hand_pose", "betas", "expression", "transl",
]
EXTRA_KEYS = ["joints"]

# Locked by the tracker (configs/degas.yaml + hmt/smplx_builder.py LOCKED_KWARGS).
SMPLX_KWARGS = dict(
    model_type="smplx",
    gender="neutral",
    use_pca=False,
    num_betas=300,
    num_expression_coeffs=100,
    use_face_contour=True,
    flat_hand_mean=False,
    create_global_orient=False,
    create_body_pose=False,
    create_betas=False,
    create_left_hand_pose=False,
    create_right_hand_pose=False,
    create_jaw_pose=False,
    create_leye_pose=False,
    create_reye_pose=False,
    create_expression=False,
    create_transl=False,
)


def consolidate(capture: str, dataset_root: Path, out_path: Path,
                with_vertices: bool = False, verify: bool = True) -> dict:
    seq = dataset_root / capture / "hmt_seq_out" / "smplx"
    files = sorted(seq.glob("smplx_*.npz"))
    if not files:
        raise SystemExit(f"no per-frame npz under {seq}")

    frames = np.array([int(f.stem.split("_")[1]) for f in files], np.int32)
    T = len(files)
    print(f"[consolidate] {capture}: {T} frames, GT {frames[0]}..{frames[-1]}", flush=True)

    acc: dict[str, list] = {k: [] for k in PARAM_KEYS + EXTRA_KEYS}
    view_ids, n_face, stages, verts = [], [], [], []

    for i, f in enumerate(files):
        z = np.load(f, allow_pickle=False)
        for k in PARAM_KEYS + EXTRA_KEYS:
            acc[k].append(z[k])
        view_ids.append(np.asarray(z["view_ids"], np.int16))
        n_face.append(int(z["n_face_views"]))
        stages.append(str(z["stages"]))
        if with_vertices:
            verts.append(z["vertices"])
        assert int(z["gt_frame"]) == int(frames[i]), f"{f}: gt_frame != filename"
        if (i + 1) % 500 == 0:
            print(f"  .. {i + 1}/{T}", flush=True)

    vmax = max(len(v) for v in view_ids)
    vids = np.full((T, vmax), -1, np.int16)
    for i, v in enumerate(view_ids):
        vids[i, :len(v)] = v

    out = {k: np.stack(acc[k]) for k in PARAM_KEYS + EXTRA_KEYS}
    out["frames"] = frames
    out["video_frames"] = (frames + VIDEO_FRAME_OFFSET).astype(np.int32)
    out["view_ids"] = vids
    out["n_views"] = np.array([len(v) for v in view_ids], np.int16)
    out["n_face_views"] = np.asarray(n_face, np.int16)
    out["stages"] = np.asarray(stages)
    out["smplx_kwargs"] = np.asarray(json.dumps(SMPLX_KWARGS))
    out["meta"] = np.asarray(json.dumps({
        "capture": capture,
        "n_frames": T,
        "frame_first": int(frames[0]),
        "frame_last": int(frames[-1]),
        "video_frame_offset": VIDEO_FRAME_OFFSET,
        "note": ("video frame index = frame + %d; d=0 is measured (verify_alignment.py), "
                 "not assumed, and is uniform across all captures" % VIDEO_FRAME_OFFSET),
        "source": "Holistic-Multiview-Tracker run_degas_sequence.py (branch reusable-v0.2.0)",
        "world_frame": "Y-up; cameras.json world is Y-down -> world_flip=diag(1,-1,-1)",
    }))

    out_path.parent.mkdir(parents=True, exist_ok=True)
    np.savez_compressed(out_path, **out)
    mb = out_path.stat().st_size / 2**20
    print(f"[consolidate] wrote {out_path}  ({mb:.1f} MB)", flush=True)

    if with_vertices:
        vp = out_path.with_name("smplx_vertices.npz")
        np.savez_compressed(vp, frames=frames, vertices=np.stack(verts))
        print(f"[consolidate] wrote {vp}  ({vp.stat().st_size / 2**20:.1f} MB)", flush=True)

    if verify:
        _verify(out_path, files, frames)

    return {"capture": capture, "n_frames": T, "bytes": out_path.stat().st_size,
            "gt_first": int(frames[0]), "gt_last": int(frames[-1]),
            "n_views_max": int(vmax)}


def _verify(out_path: Path, files: list[Path], frames: np.ndarray) -> None:
    """Bit-exact round-trip check on a random sample of frames."""
    z = np.load(out_path, allow_pickle=False)
    rng = np.random.default_rng(0)
    idx = rng.choice(len(files), size=min(25, len(files)), replace=False)
    for i in idx:
        src = np.load(files[int(i)], allow_pickle=False)
        for k in PARAM_KEYS + EXTRA_KEYS:
            a, b = src[k], z[k][int(i)]
            if a.dtype != b.dtype or not np.array_equal(a, b):
                raise SystemExit(f"LOSSY: frame {frames[i]} key {k} mismatch")
    print(f"[consolidate] verify OK: {len(idx)} random frames bit-identical to source", flush=True)


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("capture", help="e.g. P1C1")
    ap.add_argument("--dataset-root", type=Path, default=DATASET_ROOT)
    ap.add_argument("--out", type=Path, required=True, help="output smplx.npz path")
    ap.add_argument("--expect-first-frame", type=int, default=None,
                    help="assert the first source frame id equals this. Guards against "
                         "consolidating a capture whose per-frame npz have not been "
                         "relabelled to the d=0 convention (P1C1 shipped as 1..N once).")
    ap.add_argument("--with-vertices", action="store_true",
                    help="also write smplx_vertices.npz (~200 MB/capture)")
    ap.add_argument("--no-verify", action="store_true")
    a = ap.parse_args()
    if a.expect_first_frame is not None:
        seq = a.dataset_root / a.capture / "hmt_seq_out" / "smplx"
        first = sorted(seq.glob("smplx_*.npz"))
        if not first:
            raise SystemExit(f"no per-frame npz under {seq}")
        got = int(first[0].stem.split("_")[1])
        if got != a.expect_first_frame:
            raise SystemExit(
                f"REFUSING: {a.capture} first frame is {got}, expected "
                f"{a.expect_first_frame}. The source has not been relabelled to d=0 yet.")
    info = consolidate(a.capture, a.dataset_root, a.out, a.with_vertices, not a.no_verify)
    print(json.dumps(info))
    return 0


if __name__ == "__main__":
    sys.exit(main())