"""Per-frame face regions good enough to steer the encoder's byte budget. tools/frame_scan.py ran one cascade at its default threshold and the result was judged by eye: boxes on the right thing about 80 % of the time, one wall mistaken for a face, *and a lot of obvious faces missed* - 44 % of frames had no detection at all, with dropout runs inside shots averaging 10 frames and reaching 93. Recall is the binding problem: a missing box does not merely waste the budget, it moves the budget off the face, and a budget that lurches every few frames is worse than a uniform one. So this does three things the scan did not: 1. **Detects permissively.** Three cascades, a finer scale step and a lower neighbour threshold, accepting false positives to recover the misses. 2. **Rejects the false positives structurally rather than by threshold.** A flat wall has little interior detail and no skin chroma; a face has both. Neither test needs a model, and both reject the thing a threshold cannot. 3. **Tracks within a shot and interpolates.** Detections are linked frame to frame, short-lived tracks are dropped, and the surviving track is interpolated across its gaps - so the region a frame gets is continuous even where the detector blinked. Tracks never cross a shot boundary, because position means nothing across a cut. Writes a box per frame (or none, where a shot really has no face) plus the evidence for judging it: coverage, how far boxes move between frames, and contact sheets. python tools/face_track.py fields out/face_track.npz --summary out/full/summary.json """ from __future__ import annotations import argparse import json from pathlib import Path import numpy as np from PIL import Image LUMA = np.array([0.299, 0.587, 0.114]) MIN_TRACK = 5 # frames: a shorter run is noise, not a face MIN_VARIANCE = 55.0 # interior luma variance: a flat wall falls below this MIN_SKIN = 0.25 # fraction of interior pixels with skin chroma MAX_REGIONS = 3 # faces weighted per frame HOLD = 45 # frames a track's box is held past its last detection, within the shot def cascades() -> list: import cv2 names = ("haarcascade_frontalface_default.xml", "haarcascade_frontalface_alt2.xml", "haarcascade_profileface.xml") # fmt: skip out = [] for n in names: c = cv2.CascadeClassifier(str(Path(cv2.data.haarcascades) / n)) if not c.empty(): out.append((n, c)) else: print(f" warning: {n} did not load") return out def looks_like_skin(rgb: np.ndarray) -> float: """Fraction of pixels whose chroma is plausibly skin, over any complexion. Deliberately crude and deliberately wide: it is here to reject a wall or a patch of floor, not to classify anyone. Works on the ratios between channels rather than absolute brightness, so it holds across lighting and skin tone. """ r, g, b = (rgb[..., i].astype(np.float64) for i in range(3)) total = r + g + b + 1e-6 rn, gn = r / total, g / total # red above green above blue, with red not dominating completely (that is a light) ordered = (r > g) & (g > b) ratios = (rn > 0.33) & (rn < 0.58) & (gn > 0.26) & (gn < 0.38) return float(np.mean(ordered & ratios)) def interior(rgb: np.ndarray, box: tuple[int, int, int, int]) -> np.ndarray: x, y, w, h = box pad_x, pad_y = w // 6, h // 6 # trim the border, which is usually background return rgb[y + pad_y : y + h - pad_y, x + pad_x : x + w - pad_x] def detect(rgb: np.ndarray, casc: list, scale: float, neighbours: int, min_size: int) -> list: """Permissive detection, then the structural filters. Returns boxes, largest first.""" import cv2 grey = (rgb @ LUMA).astype(np.uint8) found: list[tuple[int, int, int, int]] = [] for _, c in casc: for x, y, w, h in c.detectMultiScale(grey, scaleFactor=scale, minNeighbors=neighbours, minSize=(min_size, min_size)): # fmt: skip found.append((int(x), int(y), int(w), int(h))) kept = [] for box in found: patch = interior(rgb, box) if patch.size == 0: continue var = float((patch @ LUMA).var()) skin = looks_like_skin(patch) if var >= MIN_VARIANCE and skin >= MIN_SKIN: kept.append((box, var, skin)) # merge heavy overlaps, keeping the larger kept.sort(key=lambda t: -t[0][2] * t[0][3]) merged: list[tuple] = [] for box, var, skin in kept: if not any(iou(box, m[0]) > 0.45 for m in merged): merged.append((box, var, skin)) return merged def iou(a: tuple[int, int, int, int], b: tuple[int, int, int, int]) -> float: ax, ay, aw, ah = a bx, by, bw, bh = b x0, y0 = max(ax, bx), max(ay, by) x1, y1 = min(ax + aw, bx + bw), min(ay + ah, by + bh) if x1 <= x0 or y1 <= y0: return 0.0 inter = (x1 - x0) * (y1 - y0) return inter / float(aw * ah + bw * bh - inter) def track_shot(per_frame: list[list[tuple]], start: int) -> dict[int, tuple[int, int, int, int]]: """Link detections across a shot's frames, keep the best track, fill its gaps. Greedy association by overlap, nearest first. A track that lives for fewer than MIN_TRACK frames is dropped: a wall that only fires occasionally cannot survive it, and neither can a one-frame flicker. """ tracks: list[dict] = [] # {"boxes": {frame: box}, "last": frame} for offset, boxes in enumerate(per_frame): frame = start + offset used = set() for t in tracks: if frame - t["last"] > 6: # lost for too long: do not resume it continue best, best_i = 0.0, None for i, (box, _, _) in enumerate(boxes): if i in used: continue score = iou(box, t["boxes"][t["last"]]) if score > best: best, best_i = score, i if best_i is not None and best > 0.2: t["boxes"][frame] = boxes[best_i][0] t["last"] = frame used.add(best_i) for i, (box, _, _) in enumerate(boxes): if i not in used: tracks.append({"boxes": {frame: box}, "last": frame}) tracks = [t for t in tracks if len(t["boxes"]) >= MIN_TRACK] if not tracks: return {} # Every surviving track is kept, not just the best one: a frame with two faces in it # wants both weighted, and the budget does not care which is the "subject". tracks.sort(key=lambda t: (-len(t["boxes"]), -np.mean([b[2] * b[3] for b in t["boxes"].values()]))) out: dict[int, list[tuple[int, int, int, int]]] = {} shot_end = start + len(per_frame) for t in tracks[:MAX_REGIONS]: boxes = t["boxes"] frames = sorted(boxes) # Interpolate the gaps the detector blinked through, then hold the first and # last box outwards to the edges of the shot, up to HOLD frames. A detector # that found the face for MIN_TRACK frames of a shot is better evidence that # the face is in the shot than its silence is evidence that it left, and a # region that is slightly stale still beats one that vanishes and returns. lo = max(start, frames[0] - HOLD) hi = min(shot_end, frames[-1] + HOLD + 1) for frame in range(lo, hi): if frame in boxes: box = boxes[frame] elif frame < frames[0]: box = boxes[frames[0]] elif frame > frames[-1]: box = boxes[frames[-1]] else: before = max(f for f in frames if f < frame) after = min(f for f in frames if f > frame) w = (frame - before) / (after - before) box = tuple(int(round(boxes[before][i] * (1 - w) + boxes[after][i] * w)) for i in range(4)) out.setdefault(frame, []).append(box) return out def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("fields", type=Path) ap.add_argument("out", type=Path, nargs="?", default=Path("out/face_track.npz")) ap.add_argument("--summary", type=Path, default=Path("out/full/summary.json")) ap.add_argument("--scale", type=float, default=1.06) ap.add_argument("--neighbours", type=int, default=3) ap.add_argument("--min-size", type=int, default=20) ap.add_argument("--limit", type=int) args = ap.parse_args(argv) paths = sorted(args.fields.glob("f*.png"))[: args.limit] casc = cascades() print(f"{len(paths)} frames, {len(casc)} cascades, scale {args.scale}, " f"minNeighbors {args.neighbours}, minSize {args.min_size}") shots = sorted(json.loads(args.summary.read_text())["shots"]) if args.summary.exists() else [0] shots = [s for s in shots if s < len(paths)] bounds = list(zip(shots, shots[1:] + [len(paths)])) raw_hits = 0 boxes = np.zeros((len(paths), MAX_REGIONS, 4), dtype=np.int32) counts = np.zeros(len(paths), dtype=np.int32) tracked = np.zeros(len(paths), dtype=bool) detected = np.zeros(len(paths), dtype=bool) for shot, (start, end) in enumerate(bounds): per_frame = [] for i in range(start, end): rgb = np.asarray(Image.open(paths[i]).convert("RGB")) found = detect(rgb, casc, args.scale, args.neighbours, args.min_size) detected[i] = bool(found) raw_hits += len(found) per_frame.append(found) for frame, found in track_shot(per_frame, start).items(): for k, box in enumerate(found[:MAX_REGIONS]): boxes[frame, k] = box counts[frame] = min(len(found), MAX_REGIONS) tracked[frame] = True if (shot + 1) % 10 == 0: print(f" shot {shot + 1}/{len(bounds)}: {int(tracked[:end].sum()):,} frames tracked", flush=True) # fmt: skip np.savez(args.out, names=np.array([p.name for p in paths]), boxes=boxes, counts=counts, tracked=tracked, detected=detected) # fmt: skip print(f"\n{raw_hits:,} detections survived the filters across {len(paths):,} frames") print(f"frames with a raw detection : {int(detected.sum()):,} ({100 * detected.mean():.1f}%)") print(f"frames with a tracked box : {int(tracked.sum()):,} ({100 * tracked.mean():.1f}%)") gained = int((tracked & ~detected).sum()) print(f" of which filled by interpolation: {gained:,}") # stability, which is what the budget actually cares about moves = [] for start, end in bounds: for i in range(start, end - 1): if tracked[i] and tracked[i + 1]: a, b = boxes[i, 0], boxes[i + 1, 0] moves.append(float(np.hypot((a[0] + a[2] / 2) - (b[0] + b[2] / 2), (a[1] + a[3] / 2) - (b[1] + b[3] / 2)))) # fmt: skip if moves: m = np.array(moves) print(f"centre movement between frames: median {np.median(m):.1f} px, p95 " f"{np.percentile(m, 95):.1f} px, max {m.max():.1f} px") print(f" jumps over 24 px (3 cells): {int((m > 24).sum())} of {len(m)} " f"({100 * np.mean(m > 24):.2f}%)") print(f"\n-> {args.out}") return 0 if __name__ == "__main__": raise SystemExit(main())