"""Score an encode inside and outside the face regions, so ROI weighting is judged on the thing it is for. Whole-frame error is the wrong gauge for a change that deliberately moves bytes from the background to the face: it will read slightly worse by design. This splits the encoder's own luma-weighted error (rrmd.encode.LUMA_W, so the numbers are in the same units as encode.log) into face cells, the feathered edge, and the background, for two encodes of the same frames, and reports each region's change. python tools/roi_score.py out/roi-base out/roi-face fields out/face_track.npz """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.encode import LUMA_W, load_picture # noqa: E402 from rrmd.roi import BACKGROUND_WEIGHT, EDGE_WEIGHT, FACE_WEIGHT, cell_weights # noqa: E402 from rrmd.vdp import CELLS_X, CELLS_Y, TILE # noqa: E402 def cell_error(shown: np.ndarray, source: np.ndarray) -> np.ndarray: """(CELLS_Y, CELLS_X) summed luma-weighted squared error per cell.""" d = shown.astype(np.float64) - source.astype(np.float64) px = np.sum(d * d * LUMA_W, axis=-1) return px.reshape(CELLS_Y, TILE, CELLS_X, TILE).sum(axis=(1, 3)) def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("base", type=Path) ap.add_argument("roi", type=Path) ap.add_argument("fields", type=Path) ap.add_argument("track", type=Path) ap.add_argument("--saturation", type=float, default=1.0, help="if the encodes used --saturation, score against the same adjusted source") # fmt: skip args = ap.parse_args(argv) data = np.load(args.track, allow_pickle=False) boxes, counts = data["boxes"], data["counts"] base_paths = sorted((args.base / "expected").glob("e*.png")) n = len(base_paths) totals = {k: {"face": 0.0, "edge": 0.0, "background": 0.0, "all": 0.0} for k in ("base", "roi")} pixels = {"face": 0, "edge": 0, "background": 0, "all": 0} frames_with_face = 0 for i in range(n): src = load_picture(args.fields / f"f{i + 1:05d}.png") if args.saturation != 1.0: from rrmd.roi import saturate src = saturate(src, args.saturation) w = cell_weights(boxes[i], int(counts[i])) if i < len(counts) and counts[i] > 0 else None if w is None: continue frames_with_face += 1 w = w.reshape(CELLS_Y, CELLS_X) masks = {"face": w == FACE_WEIGHT, "edge": w == EDGE_WEIGHT, "background": w == BACKGROUND_WEIGHT, "all": np.ones_like(w, bool)} # fmt: skip for tag, d in (("base", args.base), ("roi", args.roi)): shown = np.asarray(Image.open(d / "expected" / f"e{i:05d}.png").convert("RGB")) ce = cell_error(shown, src) for region, m in masks.items(): totals[tag][region] += float(ce[m].sum()) for region, m in masks.items(): pixels[region] += int(m.sum()) * TILE * TILE print(f"{frames_with_face} of {n} frames have a face region and are scored\n") print(f"{'region':<12}{'pixels':>12}{'base err/px':>14}{'roi err/px':>13}{'change':>10}") for region in ("face", "edge", "background", "all"): if not pixels[region]: continue b = totals["base"][region] / pixels[region] r = totals["roi"][region] / pixels[region] print(f"{region:<12}{pixels[region]:>12,}{b:>14.1f}{r:>13.1f}{100 * (r / b - 1):>+9.1f}%") return 0 if __name__ == "__main__": raise SystemExit(main())