"""Are the Haar face boxes good enough to steer the byte budget? ROI weighting would spend the encoder's budget wherever these boxes point, so a box that drifts off the face, flickers out for a few frames, or latches onto something in the background does not merely waste bytes - it takes them away from the face and puts them somewhere nobody is looking. Before any of that is wired into the cost metric, two questions need answering: measurable - how stable are the boxes? Within a shot: what fraction of frames get a detection at all, how far does the centre move between frames, how much does the size jump. Jitter and gaps both make the ROI flicker. not measurable - is the box actually on the face? Only a person can say, so the contact sheets written here are the point of the tool, not a side effect. The worst-jitter frames get their own sheet, because that is where a detector fails and where a confident wrong answer costs most. python tools/face_check.py out/frame_scan.npz fields out/face_check """ from __future__ import annotations import argparse import json import sys from pathlib import Path import numpy as np from PIL import Image, ImageDraw GRID = (6, 4) # columns, rows per contact sheet SCALE = 2 def sheet(paths: list[Path], boxes: list[np.ndarray], labels: list[str], out: Path) -> None: """A grid of frames with their boxes drawn, upscaled so 320x224 is legible.""" cols, rows = GRID w, h = 320 * SCALE, 224 * SCALE canvas = Image.new("RGB", (cols * w, rows * h), (16, 16, 16)) for i, (p, bs, label) in enumerate(zip(paths, boxes, labels)): if i >= cols * rows: break im = Image.open(p).convert("RGB").resize((w, h), Image.NEAREST) d = ImageDraw.Draw(im) for j, (x, y, bw, bh) in enumerate(bs): if bw <= 0: continue colour = (0, 255, 0) if j == 0 else (255, 160, 0) d.rectangle([x * SCALE, y * SCALE, (x + bw) * SCALE, (y + bh) * SCALE], outline=colour, width=2) d.text((4, 4), label, fill=(255, 255, 0)) canvas.paste(im, ((i % cols) * w, (i // cols) * h)) out.parent.mkdir(parents=True, exist_ok=True) canvas.save(out) print(f" wrote {out} ({min(len(paths), cols * rows)} frames)") def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("scan", type=Path) ap.add_argument("fields", type=Path) ap.add_argument("out", type=Path, nargs="?", default=Path("out/face_check")) ap.add_argument("--summary", type=Path, default=Path("out/full/summary.json")) ap.add_argument("--seed", type=int, default=7) args = ap.parse_args(argv) scan = dict(np.load(args.scan, allow_pickle=False)) # tools/face_track.py writes the same shapes under a different name for the count, # so either file can be reviewed with the same sheets and the same statistics. if "counts" in scan and "n_faces" not in scan: scan["n_faces"] = scan["counts"] print("reading a tracked file: boxes may be interpolated or held, not detected") names, boxes, n_faces = scan["names"], scan["boxes"], scan["n_faces"] # a tracked file carries no frame-difference column; the fast-motion sheet is then # simply skipped rather than the whole review failing diff = scan.get("diff") total = len(names) shots = sorted(json.loads(args.summary.read_text())["shots"]) if args.summary.exists() else [0] shots = [s for s in shots if s < total] or [0] # a limited scan has fewer frames than the song # -- stability, within shots only: across a cut, movement means nothing ---------- have = n_faces > 0 centre = np.stack([boxes[:, 0, 0] + boxes[:, 0, 2] / 2, boxes[:, 0, 1] + boxes[:, 0, 3] / 2], 1) area = (boxes[:, 0, 2] * boxes[:, 0, 3]).astype(np.float64) moves, grows, cover, gaps = [], [], [], [] for a, b in zip(shots, shots[1:] + [total]): if b - a < 3: continue seg = slice(a, b) cover.append(have[seg].mean()) run = 0 for i in range(a, b): if have[i]: run = 0 else: run += 1 if i + 1 >= b or have[i + 1]: gaps.append(run) for i in range(a, b - 1): if have[i] and have[i + 1]: moves.append(float(np.hypot(*(centre[i + 1] - centre[i])))) if area[i] > 0: grows.append(100 * abs(area[i + 1] - area[i]) / area[i]) moves_a, grows_a = np.array(moves), np.array(grows) cover_a, gaps_a = np.array(cover), np.array(gaps) print(f"{total} frames, {int(have.sum())} with a detection ({100 * have.mean():.1f}%)") print("\nstability within shots") print(f" shots where a face is found in over half the frames: " f"{int((cover_a > 0.5).sum())} of {len(cover_a)}") print(f" per-shot detection coverage: mean {100 * cover_a.mean():.0f}%, median {100 * np.median(cover_a):.0f}%") if len(gaps_a): print(f" dropout runs (frames with no box inside a shot): {len(gaps_a)}, " f"mean {gaps_a.mean():.1f} frames, p95 {np.percentile(gaps_a, 95):.0f}, max {gaps_a.max()}") print(f" centre movement between consecutive frames: median {np.median(moves_a):5.1f} px, " f"p95 {np.percentile(moves_a, 95):5.1f} px, max {moves_a.max():5.1f} px") print(f" area change between consecutive frames: median {np.median(grows_a):5.1f}%, " f"p95 {np.percentile(grows_a, 95):5.1f}%") jumpy = int((moves_a > 24).sum()) print(f" jumps over 24 px (3 cells) between frames: {jumpy} of {len(moves_a)} " f"({100 * jumpy / len(moves_a):.1f}%) - each one moves the ROI by 3 cells or more") # -- contact sheets: the part a person has to judge ------------------------------- print("\ncontact sheets for review") rng = np.random.default_rng(args.seed) idx_have = np.flatnonzero(have) pick = np.sort(rng.choice(idx_have, min(24, len(idx_have)), replace=False)) sheet([args.fields / str(names[i]) for i in pick], [boxes[i][: n_faces[i]] for i in pick], [f"{i}" for i in pick], args.out / "random_detections.png") # fmt: skip # worst jitter: consecutive pairs inside a shot with the largest centre move pairs = [] for a, b in zip(shots, shots[1:] + [total]): for i in range(a, min(b, total) - 1): if have[i] and have[i + 1]: pairs.append((float(np.hypot(*(centre[i + 1] - centre[i]))), i)) pairs.sort(reverse=True) worst = [i for _, i in pairs[:12]] seq: list[int] = [] for i in worst: seq += [i, i + 1] sheet([args.fields / str(names[i]) for i in seq], [boxes[i][: n_faces[i]] for i in seq], [f"{i} ({'A' if k % 2 == 0 else 'B'})" for k, i in enumerate(seq)], args.out / "worst_jitter_pairs.png") # fmt: skip # fast motion: where a detector is most likely to be wrong fast = np.flatnonzero(have & (diff > np.percentile(diff, 90))) if diff is not None else [] if len(fast): pick = np.sort(rng.choice(fast, min(24, len(fast)), replace=False)) sheet([args.fields / str(names[i]) for i in pick], [boxes[i][: n_faces[i]] for i in pick], [f"{i}" for i in pick], args.out / "fast_motion.png") # fmt: skip # frames with no detection at all, to see what is being missed none = np.flatnonzero(~have) if len(none): pick = np.sort(rng.choice(none, min(24, len(none)), replace=False)) sheet([args.fields / str(names[i]) for i in pick], [[] for _ in pick], [f"{i}" for i in pick], args.out / "no_detection.png") # fmt: skip print("\nGreen box = largest detection (the one ROI weighting would follow); orange = others.") return 0 if __name__ == "__main__": raise SystemExit(main())