File size: 7,767 Bytes
358e603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Measure the video<->SMPL-X frame offset EMPIRICALLY. Never assume it.

Why this exists
    The DEGAS captures were first tracked assuming `GT frame = video frame + 1`. That
    offset had been measured on a near-static frame, where every candidate looks alike,
    and it was wrong. A one-frame error is nearly invisible in a still overlay but
    poisons every downstream avatar. So the offset is now MEASURED, on motion, before a
    capture is published.

Method (needs no SMPL-X model, only what the dataset ships)
    The discriminating signal is the FAST-MOVING HAND against the ALPHA MATTE.
    A forearm is only ~40-80 px wide, and during a gesture the wrist moves tens of px
    per frame, so a projected wrist lands inside the silhouette at the correct offset and
    outside it one frame away. Slow signals (body centroid) cannot resolve +-1 frame and
    will happily report nonsense with a margin of ~0.01; that weak-signal trap is exactly
    what produced the original wrong +1, so this script refuses to answer when the margin
    is small.

    1. Rank fit frames by projected 2D WRIST SPEED; keep the fastest ones.
    2. Decode a contiguous low-res window of the ALPHA half (right 2048) of each camera.
    3. For each candidate offset d, measure the fraction of hand/wrist joints that land
       on foreground at video frame (fit_frame + d).
    4. Report argmax, plus the margin. A margin below --min-margin is INCONCLUSIVE and
       exits non-zero rather than guessing.

Usage
    python verify_alignment.py data/P1C1 --cams 6 12 --start 1300 --count 250
    python verify_alignment.py data/P1C1 --expect 0        # non-zero exit if it differs
"""
from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from load_capture import Capture  # noqa: E402


# SMPL-X joint indices that move fastest and sit on THIN geometry, which is what makes
# a one-frame error visible: wrists + both hands' finger joints.
HAND_JOINTS = np.r_[20, 21, np.arange(25, 55)]


def decode_alpha_window(video: Path, v_start: int, count: int, scale: float = 0.25
                        ) -> tuple[np.ndarray, float]:
    """(count, h, w) uint8 stack of the ALPHA half, downscaled by `scale`."""
    vf = (f"select='between(n\\,{v_start}\\,{v_start + count - 1})',"
          f"crop=iw/2:ih:iw/2:0,scale=iw*{scale}:ih*{scale},format=gray")
    proc = subprocess.run(
        ["ffmpeg", "-v", "error", "-threads", "1", "-i", str(video),
         "-vf", vf, "-vsync", "0", "-f", "rawvideo", "-pix_fmt", "gray", "-"],
        capture_output=True, check=True)
    buf = np.frombuffer(proc.stdout, np.uint8)
    if len(buf) % count:
        raise RuntimeError(f"{video.name}: raw size {len(buf)} not divisible by {count}")
    hw = len(buf) // count
    # crop=2048x1500 -> scale 0.25 -> 512x375
    w = int(round(2048 * scale))
    h = hw // w
    if h * w * count != len(buf):
        raise RuntimeError(f"{video.name}: cannot reshape {len(buf)} as {count}x?x{w}")
    return buf.reshape(count, h, w), scale


def hand_speed(cap: Capture, cam: str, frames: list[int]) -> np.ndarray:
    """Mean projected 2D speed of the hand joints, px/frame, per fit frame."""
    c = cap.cameras[cam]
    uv = np.stack([c.project(cap.joints(f)[HAND_JOINTS]) for f in frames])
    d = np.linalg.norm(np.diff(uv, axis=0), axis=2).mean(1)
    return np.r_[d[0], d]


def hit_rate(cap: Capture, cam: str, probe: list[int], stack: np.ndarray, scale: float,
             v_first: int, offsets: range) -> dict[int, float]:
    """For each offset d: fraction of hand joints landing on foreground alpha."""
    c = cap.cameras[cam]
    n, h, w = stack.shape
    out = {}
    for d in offsets:
        hits, tot = 0, 0
        for f in probe:
            idx = (f + d) - v_first
            if not (0 <= idx < n):
                continue
            m = stack[idx] > 12
            uv = c.project(cap.joints(f)[HAND_JOINTS]) * scale
            u = np.round(uv[:, 0]).astype(int)
            v = np.round(uv[:, 1]).astype(int)
            ok = (u >= 0) & (u < w) & (v >= 0) & (v < h)
            if not ok.any():
                continue
            hits += int(m[v[ok], u[ok]].sum())
            tot += int(ok.sum())
        out[d] = hits / tot if tot else float("nan")
    return out


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("capture_dir", type=Path)
    ap.add_argument("--cams", type=int, nargs="*", default=[6, 12])
    ap.add_argument("--start", type=int, default=None, help="first FIT frame of the window")
    ap.add_argument("--count", type=int, default=300)
    ap.add_argument("--lags", type=int, nargs=2, default=[-3, 3])
    ap.add_argument("--n-probe", type=int, default=40,
                    help="how many of the fastest-hand frames to score")
    ap.add_argument("--min-margin", type=float, default=0.05,
                    help="required hit-rate gap to the runner-up; below this = INCONCLUSIVE")
    ap.add_argument("--expect", type=int, default=None,
                    help="fail (exit 1) if the measured offset differs from this")
    a = ap.parse_args()

    cap = Capture(a.capture_dir)
    print(cap)
    frames = [int(f) for f in cap.frames]
    if a.start is not None:
        frames = [f for f in frames if f >= a.start]
    frames = frames[:a.count]
    lo, hi = a.lags
    print(f"window: fit frames {frames[0]}..{frames[-1]} ({len(frames)})")

    cam0 = f"cam{a.cams[0]:02d}"
    spd = hand_speed(cap, cam0, frames)
    order = np.argsort(-spd)[:a.n_probe]
    probe = sorted(frames[i] for i in order)
    print(f"hand speed in window: median {np.median(spd):.1f} px/frame, "
          f"probe frames use {spd[order].min():.1f}..{spd[order].max():.1f} px/frame")
    if spd[order].min() < 3.0:
        print("WARNING: probe frames are slow; +-1 frame may be unresolvable here")

    v_first = frames[0] + lo
    n_dec = len(frames) + (hi - lo) + 1
    print(f"decoding alpha window: video frames {v_first}..{v_first + n_dec - 1}")

    per_cam = {}
    for ci in a.cams:
        cam = f"cam{ci:02d}"
        stack, scale = decode_alpha_window(cap.video_dir / f"{cam}.mp4", v_first, n_dec)
        r = hit_rate(cap, cam, probe, stack, scale, v_first, range(lo, hi + 1))
        per_cam[cam] = r
        best = max(r, key=r.get)
        print(f"  {cam} ({stack.shape[2]}x{stack.shape[1]}): "
              + "  ".join(f"d={k:+d}:{v:.3f}" for k, v in sorted(r.items()))
              + f"   -> best d={best:+d}")

    total = {}
    for r in per_cam.values():
        for k, v in r.items():
            total[k] = total.get(k, 0.0) + v / len(per_cam)
    ranked = sorted(total.items(), key=lambda kv: -kv[1])
    best, margin = ranked[0][0], ranked[0][1] - ranked[1][1]
    print("\nhand-on-silhouette hit rate by offset: "
          + "  ".join(f"d={k:+d}:{v:.3f}" for k, v in sorted(total.items())))
    print(f"MEASURED: video_frame = fit_frame + ({best:+d})  "
          f"(margin over d={ranked[1][0]:+d}: {margin:.3f})")

    if margin < a.min_margin:
        print(f"INCONCLUSIVE: margin {margin:.3f} < --min-margin {a.min_margin}. "
              f"This window cannot resolve the offset; do NOT act on it. "
              f"Retry on a higher-motion window or more cameras.")
        return 2
    if a.expect is not None:
        if best != a.expect:
            print(f"FAIL: expected {a.expect:+d}, measured {best:+d}")
            return 1
        print(f"PASS: matches expected {a.expect:+d}")
    return 0


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