Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

Compare square and rectangular inputs with tiled face detection

Baurzhan Atynovf9698626020d
diff --git a/docs/research/yunet_pixel_budget.md b/docs/research/yunet_pixel_budget.md
new file mode 100644
index 0000000..d005616
--- /dev/null
+++ b/docs/research/yunet_pixel_budget.md
@@ -0,0 +1,50 @@
+# YuNet input geometry at a fixed pixel budget
+
+The baseline puts the entire RGB image in a 640 × 640 square with centered padding. We compared three alternatives without changing the detector weights or its native box filters.
+
+| Mode | Input policy | Maximum pixels processed per image |
+|---|---|---:|
+| Square | One 640 × 640 pass | 409600 |
+| Rectangle | One aspect preserving resize to a canvas aligned to 32, longest side at most 1280 | 409600 |
+| Two tiles | Split the longer side in two and letterbox each part to 448 × 448 | 401408 |
+| Four tiles | Split both sides in two and letterbox each part to 320 × 320 | 409600 |
+
+Adjacent tiles overlap by approximately one eighth of the original side. Detections return to original image coordinates before a second, score ordered NMS at IoU 0.4 across tile outputs. A 1920 × 1080 image occupies 640 × 360 pixels in the baseline and 832 × 468 pixels on an 832 × 480 canvas in rectangle mode. This puts more of the same pixel budget into image detail.
+
+## Protocol
+
+WIDER FACE validation, 128 calibration images drawn with seed 725 from outside the fixed 640 image evaluation subset (seed 114). The evaluation subset was used in the earlier 25 task study. The four modes and their thresholds were compared in this experiment using disjoint calibration and evaluation images. Native detection runs at a common extraction threshold of 0.30. On calibration images the square uses a reporting threshold of 0.50. For each other mode choose the threshold with the most matches on a 0.01 grid subject to the square's unmatched detection count; ties use the lower threshold. Freeze the thresholds before evaluation.
+
+One-to-one assignment at IoU ≥0.5 in original coordinates against valid boxes. An unmatched prediction counts as a false positive under this protocol, including predictions on ignored annotations. Small means a geometric mean of box width and height below 16 pixels after scaling the whole image's long side to 320, the same physical definition for all modes. Counts are operating points rather than official WIDER AP.
+
+Linux x86, one pinned CPU thread, GCC with native optimization. CPU time includes crop, resize, canvas allocation, detection, coordinate conversion and cross-tile suppression. It excludes JPEG decoding, scoring and threshold selection. Mode order is randomized per image. Confidence intervals use 2000 paired bootstrap resamples of images. Timing at a common extraction threshold includes processing candidates later filtered by the calibrated threshold.
+
+| Mode | Threshold | Calibration matches | Unmatched | Small matches |
+|---|---:|---:|---:|---:|
+| Square | 0.50 | 404 | 23 | 256 |
+| Rectangle | 0.58 | 440 | 23 | 285 |
+| Two tiles | 0.58 | 403 | 22 | 252 |
+| Four tiles | 0.57 | 304 | 22 | 171 |
+
+## Evaluation results
+
+The 640 evaluation images contain 8909 valid faces, including 7902 small faces using the unrounded, aspect preserving reference scale. The earlier study rounded each resized side independently, which moves one borderline box between bins.
+
+| Mode | Matches | Unmatched | Small matches | Mean CPU ms | Median CPU ms |
+|---|---:|---:|---:|---:|---:|
+| Square | 1570 | 200 | 796 | 74.504 | 73.320 |
+| Rectangle | 1780 | 140 | 1011 | 74.405 | 72.902 |
+| Two tiles | 1539 | 127 | 790 | 73.275 | 71.370 |
+| Four tiles | 1271 | 119 | 563 | 74.129 | 72.644 |
+
+Rectangle gained 210 matches and reduced unmatched detections by 60 with essentially identical mean CPU time. Small matches rose by 215 (+27.0% relative), from 10.1% to 12.8% recall. The other sizes accounted for five fewer matches. Paired 95% intervals for rectangle minus square were +146 to +284 total matches, −90 to −32 unmatched detections and +153 to +288 small matches. Direct native thresholding also reproduced post-filtered outputs across all four modes on 12 spot-check images.
+
+The strongest tested operating point is a single rectangular pass at 0.58 for clients currently resizing to a fixed square. The two-tile mode gained precision but did not improve small-face recall at its calibrated threshold. Four tiles lost 233 small matches. These conclusions cover this model, image protocol and CPU. At the best operating point 6891 small faces still went undetected. The benchmark demonstrates an opt-in input policy; the native API continues to accept the caller's image dimensions.
+
+## Reproduction
+
+Use the native binary weights exported by tools/export_yunet_weights.py from YuNet 2023mar. Requires GCC, NumPy, SciPy and Pillow. Run from the repository root.
+
+```sh
+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_tiles.py yunet.bin WIDER_val.zip wider_face_split.zip
+```
diff --git a/tests/bench_yunet_tiles.py b/tests/bench_yunet_tiles.py
new file mode 100644
index 0000000..8abb2b5
--- /dev/null
+++ b/tests/bench_yunet_tiles.py
@@ -0,0 +1,154 @@
+"""Equal pixel budget WIDER FACE experiment. Run with the YuNet binary and WIDER archives."""
+import argparse
+import ctypes
+import io
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+from zipfile import ZipFile
+
+import numpy as np
+from PIL import Image
+
+from verify_yunet import ROOT, annotations, native_run, match
+
+MODES = ("square640", "rectangle", "two448", "four320")
+GRID = np.round(np.arange(.30, .911, .01), 2)
+
+
+def windows(mode, w, h):
+ if mode in ("square640", "rectangle"):
+ return [(0, 0, w, h)]
+ def halves(n):
+ # Adjacent crops overlap by one eighth of the full side.
+ end = min(n, (9 * n + 15) // 16)
+ return [(0, end), (n - end, n)]
+ xs = halves(w) if mode == "four320" or w >= h else [(0, w)]
+ ys = halves(h) if mode == "four320" or w < h else [(0, h)]
+ return [(l, t, r, b) for t, b in ys for l, r in xs]
+
+
+def shape(mode, w, h):
+ if mode == "rectangle":
+ # Choose the largest uniform scale with padded area <= 640 squared.
+ # Avoid pathological side lengths on panoramas.
+ scale = min(1280 / max(w, h), max(
+ min(32 * k / w, 32 * (400 // k) / h) for k in range(1, 41)))
+ rw, rh = max(1, round(w * scale)), max(1, round(h * scale))
+ return rw, rh, (rw + 31) // 32 * 32, (rh + 31) // 32 * 32
+ side = {"square640": 640, "two448": 448, "four320": 320}[mode]
+ scale = side / max(w, h)
+ return max(1, round(w * scale)), max(1, round(h * scale)), side, side
+
+
+def deduplicate(rows):
+ order = np.argsort(-rows[:, 4], kind="stable")
+ keep = []
+ area = (rows[:, 2:4] - rows[:, :2]).prod(1)
+ while len(order):
+ i = order[0]
+ keep.append(i)
+ rest = order[1:]
+ inter = (np.minimum(rows[i, 2:4], rows[rest, 2:4]) -
+ np.maximum(rows[i, :2], rows[rest, :2])).clip(0).prod(1)
+ order = rest[inter <= .4 * (area[i] + area[rest] - inter)]
+ return rows[keep]
+
+
+def predict(lib, engine, image, mode):
+ rows = []
+ for l, t, r, b in windows(mode, *image.size):
+ w, h = r - l, b - t
+ rw, rh, cw, ch = shape(mode, w, h)
+ ox, oy = (cw - rw) // 2, (ch - rh) // 2
+ canvas = np.zeros((ch, cw, 3), dtype="u1")
+ region = image if (w, h) == image.size else image.crop((l, t, r, b))
+ canvas[oy:oy+rh, ox:ox+rw] = region.resize((rw, rh))
+ det = native_run(lib, engine, canvas, capacity=10000)[:, :5].copy()
+ det[:, (0, 2)] = (det[:, (0, 2)] - ox) * (w / rw) + l
+ det[:, (1, 3)] = (det[:, (1, 3)] - oy) * (h / rh) + t
+ rows.append(det)
+ return rows[0] if len(rows) == 1 else deduplicate(np.concatenate(rows))
+
+
+def counts(out, gt, small, threshold):
+ det = out[out[:, 4] >= threshold]
+ found = match(det, gt)
+ return [len(found), len(det) - len(found), small[found].sum()]
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ for name in ("weights", "images", "labels"):
+ ap.add_argument(name, type=Path)
+ args = ap.parse_args()
+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})
+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as images, ZipFile(args.labels) as archive:
+ binary = Path(tmp) / "detector.so"
+ subprocess.run(["gcc", "-O3", "-march=native", "-shared", "-fPIC", "-I", str(ROOT / "include"),
+ str(ROOT / "src/detect.c"), "-lm", "-o", str(binary)], check=True)
+ lib = ctypes.CDLL(str(binary))
+ lib.detect_init.restype = ctypes.c_void_p
+ engine = ctypes.c_void_p(lib.detect_init(os.fsencode(args.weights)))
+ if not engine:
+ raise ValueError("Cannot load YuNet weights")
+ lib.detect_set_score_threshold(engine, ctypes.c_float(.30))
+ try:
+ run(lib, engine, images, annotations(archive))
+ finally:
+ lib.detect_free(engine)
+
+
+def run(lib, engine, images, labels):
+ names = sorted(labels)
+ test = np.random.default_rng(114).choice(names, 640, replace=False)
+ dev = np.random.default_rng(725).choice(sorted(set(names) - set(test)), 128, replace=False)
+ rng = np.random.default_rng(815)
+ for mode in MODES:
+ predict(lib, engine, Image.new("RGB", (800, 600)), mode)
+ thresholds = {}
+ for split, subset in (("dev", dev), ("test", test)):
+ grid = {m: GRID if split == "dev" else [thresholds[m]] for m in MODES}
+ stats = {m: [] for m in MODES}
+ times = {m: [] for m in MODES}
+ totals = np.zeros(2, int)
+ for name in subset:
+ image = Image.open(io.BytesIO(images.read("WIDER_val/images/" + name))).convert("RGB")
+ gt = labels[name].copy()
+ small = np.sqrt(gt[:, 2] * gt[:, 3]) * (320 / max(image.size)) < 16
+ gt[:, 2:] += gt[:, :2]
+ totals += [len(gt), small.sum()]
+ for mode in rng.permutation(MODES):
+ start = time.thread_time_ns()
+ det = predict(lib, engine, image, mode)
+ times[mode].append((time.thread_time_ns() - start) * 1e-6)
+ stats[mode].append([counts(det, gt, small, t) for t in grid[mode]])
+ print(split, "GT and small:", totals.tolist(), flush=True)
+ data = {m: np.array(stats[m]) for m in MODES}
+ if split == "dev":
+ ref = int(np.flatnonzero(GRID == .5)[0])
+ fp_budget = data["square640"][:, ref, 1].sum()
+ else:
+ bootstrap = np.random.default_rng(637).integers(len(test), size=(2000, len(test)))
+ for m in MODES:
+ overall = data[m].sum(0)
+ if split == "dev":
+ ok = np.flatnonzero(overall[:, 1] <= fp_budget)
+ if not len(ok):
+ raise ValueError("No threshold within false positive budget")
+ i = ref if m == "square640" else ok[np.argmax(overall[ok, 0])]
+ thresholds[m] = GRID[i]
+ else:
+ i = 0
+ print(m, "threshold", thresholds[m], "TP FP smallTP", overall[i].tolist(),
+ "CPU mean/median ms", np.round([np.mean(times[m]), np.median(times[m])], 3), flush=True)
+ if split == "test" and m != "square640":
+ delta = data[m][:, 0] - data["square640"][:, 0]
+ print("paired 95% interval TP FP smallTP",
+ np.percentile(delta[bootstrap].sum(1), [2.5, 97.5], axis=0).round(1).tolist(), flush=True)
+
+
+if __name__ == "__main__":
+ main()