"""Catalogue every source frame so a measurement can be stratified rather than guessed. Records, per frame: mean luma, mean absolute difference from the previous frame, and the face boxes OpenCV's frontal/profile Haar cascades find. Written to a .npz so the scan is paid for once. Faces are a heuristic - the cascades miss and false-positive - so the study that uses this also writes crops for a person to check. python tools/frame_scan.py fields out/frame_scan.npz """ from __future__ import annotations import sys from pathlib import Path import numpy as np from PIL import Image LUMA = np.array([0.299, 0.587, 0.114]) MAX_FACES = 4 def cascades() -> list: import cv2 names = ("haarcascade_frontalface_default.xml", "haarcascade_profileface.xml") out = [] for n in names: c = cv2.CascadeClassifier(str(Path(cv2.data.haarcascades) / n)) if c.empty(): print(f"warning: could not load {n}") else: out.append(c) return out def main(fields: Path, out: Path) -> int: import cv2 paths = sorted(fields.glob("f*.png")) if not paths: raise SystemExit(f"no frames in {fields}") casc = cascades() luma = np.zeros(len(paths)) diff = np.zeros(len(paths)) boxes = np.zeros((len(paths), MAX_FACES, 4), dtype=np.int32) n_faces = np.zeros(len(paths), dtype=np.int32) prev_grey = None for i, p in enumerate(paths): rgb = np.asarray(Image.open(p).convert("RGB")) grey = (rgb @ LUMA).astype(np.float64) luma[i] = grey.mean() diff[i] = 0.0 if prev_grey is None else np.abs(grey - prev_grey).mean() prev_grey = grey g8 = grey.astype(np.uint8) found: list[tuple[int, int, int, int]] = [] for c in casc: for x, y, w, h in c.detectMultiScale(g8, scaleFactor=1.1, minNeighbors=5, minSize=(24, 24)): found.append((int(x), int(y), int(w), int(h))) found.sort(key=lambda b: -b[2] * b[3]) # largest first: a close-up leads n_faces[i] = min(len(found), MAX_FACES) for j, b in enumerate(found[:MAX_FACES]): boxes[i, j] = b if (i + 1) % 500 == 0: print(f" {i + 1}/{len(paths)} scanned, {int((n_faces[: i + 1] > 0).sum())} with a face") out.parent.mkdir(parents=True, exist_ok=True) np.savez(out, names=np.array([p.name for p in paths]), luma=luma, diff=diff, boxes=boxes, n_faces=n_faces) # fmt: skip print(f"\n{len(paths)} frames -> {out}") print(f"luma: mean {luma.mean():.1f}, p10 {np.percentile(luma, 10):.1f}, p90 {np.percentile(luma, 90):.1f}") print(f"frame difference: median {np.median(diff):.2f}, p90 {np.percentile(diff, 90):.2f}") print(f"frames with at least one face box: {int((n_faces > 0).sum())} " f"({100 * (n_faces > 0).mean():.1f}%)") area = (boxes[:, 0, 2] * boxes[:, 0, 3]).astype(np.float64) big = area > 48 * 48 print(f"frames whose largest box is over 48x48 (a close-up): {int(big.sum())}") return 0 if __name__ == "__main__": raise SystemExit(main(Path(sys.argv[1]), Path(sys.argv[2] if len(sys.argv) > 2 else "out/frame_scan.npz")))