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.

Speed up YuNet convolutions and add a higher resolution detector mode

Baurzhan Atynovee217f5b8fbe
diff --git a/docker/server.py b/docker/server.py
index 81e017f..5ea3165 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -29,6 +29,12 @@ EMBED_WEIGHTS = os.environ.get('EMBED_WEIGHTS', 'weights/edgeface_xs_fp32.bin')
DETECT_WEIGHTS = os.environ.get('DETECT_WEIGHTS', 'weights/yunet_fp32.bin')
+DETECT_SIZE = os.environ.get("FACEX_DETECT_SIZE", "640")
+if DETECT_SIZE not in ("640", "800"):
+ raise ValueError("FACEX_DETECT_SIZE must be 640 or 800")
+DETECT_POLICY = "rectangle_bgr_800" if DETECT_SIZE == "800" else "rectangle_bgr"
+
+
class FaceXProcess:
"""Persistent subprocess for face embedding."""
@@ -139,7 +145,7 @@ def detect():
try:
if _detector is None:
engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,
- input_policy="rectangle_bgr", license_key=os.environ.get("LICENSE_KEY"))
+ input_policy=DETECT_POLICY, license_key=os.environ.get("LICENSE_KEY"))
if engine.backend != "ctypes":
raise RuntimeError("Missing native FaceX library")
_detector = engine
diff --git a/docs/research/yunet_detail.md b/docs/research/yunet_detail.md
new file mode 100644
index 0000000..b5c496b
--- /dev/null
+++ b/docs/research/yunet_detail.md
@@ -0,0 +1,51 @@
+# Recovering small faces with a larger detector input
+
+The comparison uses YuNet 2023mar with BGR detector input, original RGB source coordinates and at most 32 results. A budget of 640 means that the aligned rectangular canvas has at most 640² pixels. The 800 budget admits up to 800² pixels (+56.25%). There is one whole-frame inference per image in either case.
+
+## Operating points
+
+- **Current:** 640 budget and threshold 0.70.
+- **Soft:** same canvas and proposals, threshold 0.55. This isolates the cost in false positives of accepting weaker detections.
+- **Full 800:** larger rectangular canvas with a threshold calibrated on development images.
+- **Guided 448:** first run the 640 detector at score 0.35. Look for boxes smaller than 20 reference pixels with scores below 0.85, choose the half-frame neighborhood containing the most such hints, and center the second crop on its seed. Run it at a 448 pixel budget if there is a hint. Merge in source coordinates with IoU suppression at 0.4 and retain 32 results. This rule cannot revisit an area with no initial hint unless it lies inside the chosen crop.
+
+The 128 development and 320 evaluation images were drawn with seed 60177 from WIDER FACE validation after excluding all samples used in the previous rectangular geometry and eight bottleneck experiments. The two calibrated variants select a threshold on the development set to maximize small matches without exceeding the current mode's unmatched count. Ties favor total matches and then closeness to 0.70. Thresholds stay fixed on evaluation images.
+
+We count one-to-one matches at IoU ≥0.50 against valid boxes. Small means geometric mean side below 16 pixels when the original long side is scaled to 320 pixels. Recovered and lost counts compare the specific matched small annotation IDs per image. Percentile intervals resample entire images 2000 times. Unmatched counts use the same local protocol as earlier studies; these are not official WIDER AP results.
+
+## Native CPU kernels
+
+The 1×1 AVX2/FMA path holds four output channels and 16 positions in registers and reuses each loaded input across channels. Interior 3×3 depthwise convolution processes eight adjacent sites per vector. The stride-two stem gathers eight strided samples per tap. Accumulation follows the same channel and tap order; border and tail positions use the existing scalar code. Other CPU backends use the previous implementation.
+
+CPU times include BGR resizing and detection on a single pinned Linux thread. JPEG decoding and embedding are outside the timer. The accuracy experiment uses the reference kernels and a common extraction threshold so all operating points can be recalibrated from the same detections. The separate paired speed comparison measures the previous and new kernels at each budget and checks all returned box coordinates, five keypoints and scores.
+
+## Reproduce
+
+Run in a git checkout containing the reference revision cb672bee, with GCC, NumPy, Pillow and SciPy installed.
+
+```sh
+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_detail.py yunet.bin WIDER_val.zip wider_face_split.zip
+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_kernels.py yunet.bin WIDER_val.zip
+```
+
+## Results and decision
+
+The 320 evaluation images had 2677 valid annotations, including 2171 small faces. The guided pass was triggered on 125 images. On development images the current, full 800 and guided modes gave 17, 16 and 17 unmatched detections respectively.
+
+| Mode | Score | Total matches | Small matches | Unmatched | Small recovered / lost vs current | Mean CPU ms, reference kernels |
+|---|---:|---:|---:|---:|---:|---:|
+| Current | 0.70 | 888 | 425 | 37 | 0 / 0 | 83.13 |
+| Soft | 0.55 | 939 | 468 | 82 | 43 / 0 | 83.13 |
+| Full 800 | 0.75 | 999 | 538 | 32 | 141 / 28 | 126.49 |
+| Guided 448 | 0.76 | 977 | 517 | 25 | 116 / 24 | 98.50 |
+
+Full 800 improved small recall from 19.6% to 24.8%; its gain was 113 small matches (+26.6%). The 95% paired interval was +65 to +171 small matches and −16 to +7 unmatched predictions. Guided refinement gained 92 small matches (interval +52 to +140), with 12 fewer unmatched predictions (interval −24 to −1). It remains a research mode. Lowering the threshold alone more than doubled the unmatched count. Small-face recall is still below 25% on this subset.
+
+On 64 separately sampled WIDER frames (plus one warmup), AMD EPYC 9V74, GCC 14 native, median milliseconds for resize, conversion and detection:
+
+| Canvas budget | Previous kernels | New kernels |
+|---|---:|---:|
+| 640² | 77.41 | 51.58 |
+| 800² | 121.04 | 73.45 |
+
+All returned scores, box coordinates and landmarks were bitwise equal for both builds on both sizes in this test. The local scalar build and the optimized native build passed the ONNX fixture. Timings exclude face embeddings and do not establish performance on other hardware. Relative to the optimized 640 path, the 800 mode costs about 42% more median CPU time. Both SDK and REST expose full 800 as an explicit choice; REST keeps the faster 640 policy as its default.
diff --git a/python/README.md b/python/README.md
index 711d6c8..4aba421 100644
--- a/python/README.md
+++ b/python/README.md
@@ -59,6 +59,10 @@ Alignment and embedding sample the original RGB pixels. Set `score_threshold`
explicitly to override the calibrated threshold. Existing SDK callers use native
image dimensions by default.
+For small faces use `input_policy="rectangle_bgr_800"`. This raises the pixel
+budget to 800² and uses a calibrated threshold of 0.75. The REST equivalent is
+`FACEX_DETECT_SIZE=800`; the default is 640.
+
The Docker REST service uses the BGR rectangle policy for `POST /detect` and returns
up to 32 faces. Mount both weights at the paths above under `/app`, or set
`EMBED_WEIGHTS` and `DETECT_WEIGHTS` to their paths inside the container.
diff --git a/python/facex/core.py b/python/facex/core.py
index dc281a8..f9a81ad 100644
--- a/python/facex/core.py
+++ b/python/facex/core.py
@@ -19,7 +19,7 @@ import numpy as np
# ---------------------------------------------------------------------------
EMBEDDING_DIM = 512
MAX_FACES_DEFAULT = 20
-_POLICY_THRESHOLDS = {"native": 0.5, "rectangle": 0.58, "rectangle_bgr": 0.70}
+_POLICY_THRESHOLDS = {"native": 0.5, "rectangle": 0.58, "rectangle_bgr": 0.70, "rectangle_bgr_800": 0.75}
# FaceXResult struct layout:
# float x1, y1, x2, y2, score (5 floats = 20 bytes)
@@ -206,7 +206,7 @@ class FaceX:
detect_weights: Path to detector weights. Auto-detected if None.
license_key: License key for encrypted weights (None for plain).
score_threshold: Override the score threshold calibrated for the selected input policy.
- input_policy: Use "native", "rectangle" (RGB), or "rectangle_bgr" (YuNet 2023mar).
+ input_policy: Use "native", "rectangle" (RGB), or a YuNet BGR policy ("rectangle_bgr" or "rectangle_bgr_800").
nms_threshold: NMS IoU threshold (default 0.4).
max_faces: Maximum faces to detect per image (default 20).
"""
@@ -386,7 +386,8 @@ class FaceX:
ptr = image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
if self._input_policy != "native":
from .yunet import prepare_rectangle
- canvas, rw, rh = prepare_rectangle(image, bgr=self._input_policy == "rectangle_bgr")
+ side = 800 if self._input_policy == "rectangle_bgr_800" else 640
+ canvas, rw, rh = prepare_rectangle(image, bgr=self._input_policy != "rectangle", side=side)
ch, cw = canvas.shape[:2]
n = self._lib.facex_detect_prepared(
self._handle, ptr, w, h,
diff --git a/python/facex/yunet.py b/python/facex/yunet.py
index 1e35e91..51f9471 100644
--- a/python/facex/yunet.py
+++ b/python/facex/yunet.py
@@ -3,19 +3,21 @@ import numpy as np
from PIL import Image
-def rectangle_shape(w, h):
+def rectangle_shape(w, h, *, side=640):
if min(w, h) <= 0:
raise ValueError("Image dimensions must be positive")
- # Each cell is 32 x 32. A 640 x 640 canvas fits 400 cells.
- scale = min(1280 / max(w, h), max(
- min(32 * cols / w, 32 * (400 // cols) / h) for cols in range(1, 41)))
+ if side not in (448, 640, 800):
+ raise ValueError("Unsupported detector pixel budget")
+ cells = (side // 32) ** 2
+ scale = min(2 * side / max(w, h), max(
+ min(32 * cols / w, 32 * (cells // cols) / h) for cols in range(1, 2 * side // 32 + 1)))
rw, rh = max(1, round(w * scale)), max(1, round(h * scale))
return rw, rh, (rw + 31) // 32 * 32, (rh + 31) // 32 * 32
-def prepare_rectangle(image, *, bgr=False):
+def prepare_rectangle(image, *, bgr=False, side=640):
h, w = image.shape[:2]
- rw, rh, cw, ch = rectangle_shape(w, h)
+ rw, rh, cw, ch = rectangle_shape(w, h, side=side)
x, y = (cw - rw) // 2, (ch - rh) // 2
canvas = np.zeros((ch, cw, 3), dtype=np.uint8)
bicubic = getattr(Image, "Resampling", Image).BICUBIC
diff --git a/src/detect.c b/src/detect.c
index 8091d0e..2783c97 100644
--- a/src/detect.c
+++ b/src/detect.c
@@ -84,6 +84,26 @@ static void conv2d(const float* in, int Ci, int Hi, int Wi,
for (int co = 0; co < Co; co++)
for (int oy = 0; oy < Ho; oy++)
for (int ox = 0; ox < Wo; ox++) {
+#if defined(__AVX2__) && defined(__FMA__)
+ if (K == 3 && s == 2 && pad == 1 && oy > 0 && oy*2 + 1 < Hi &&
+ ox > 0 && (ox + 7)*2 + 1 < Wi) {
+ const __m256i offsets = _mm256_setr_epi32(0, 2, 4, 6, 8, 10, 12, 14);
+ __m256 acc = _mm256_set1_ps(b ? b[co] : 0);
+ for (int ci = 0; ci < Ci; ci++) {
+ for (int ky = 0; ky < 3; ky++) {
+ const float* row = in + (size_t)ci*Hi*Wi + (oy*2 + ky-1)*Wi + ox*2-1;
+ const float* weights = w + ((size_t)co*Ci + ci)*9 + ky*3;
+ for (int kx = 0; kx < 3; kx++) {
+ __m256 pixels = _mm256_i32gather_ps(row + kx, offsets, 4);
+ acc = _mm256_fmadd_ps(pixels, _mm256_set1_ps(weights[kx]), acc);
+ }
+ }
+ }
+ _mm256_storeu_ps(out + (size_t)co*Ho*Wo + oy*Wo + ox, acc);
+ ox += 7;
+ continue;
+ }
+#endif
float sum = b ? b[co] : 0;
for (int ci = 0; ci < Ci; ci++)
for (int ky = 0; ky < K; ky++)
@@ -111,6 +131,21 @@ static void conv_dw(const float* in, int C, int Hi, int Wi,
float w20=wc[6],w21=wc[7],w22=wc[8];
for (int oy = 0; oy < Ho; oy++) {
for (int ox = 0; ox < Wo; ox++) {
+#if defined(__AVX2__) && defined(__FMA__)
+ if (oy > 0 && oy + 1 < Hi && ox > 0 && ox + 8 < Wi) {
+ __m256 acc = _mm256_set1_ps(bc);
+ for (int ky = 0; ky < 3; ky++) {
+ const float* row = inp_c + (oy + ky - 1) * Wi + ox - 1;
+ for (int kx = 0; kx < 3; kx++) {
+ acc = _mm256_fmadd_ps(_mm256_loadu_ps(row + kx),
+ _mm256_set1_ps(wc[3*ky + kx]), acc);
+ }
+ }
+ _mm256_storeu_ps(out + (size_t)c*Ho*Wo + oy*Wo + ox, acc);
+ ox += 7;
+ continue;
+ }
+#endif
float sum = bc;
int iy = oy - 1, ix = ox - 1;
/* Unrolled 3×3 with boundary checks */
@@ -149,6 +184,35 @@ static void conv_dw(const float* in, int C, int Hi, int Wi,
}
static void conv1x1(const float* in, int Ci, int HW, const float* w, const float* b, int Co, float* out) {
+#if defined(__AVX2__) && defined(__FMA__)
+ /* Reuse two input vectors across four output channels. Keep partial
+ * sums in registers until all input channels have been accumulated. */
+ if (Co % 4 == 0 && HW % 16 == 0) {
+ for (int co = 0; co < Co; co += 4) {
+ for (int i = 0; i < HW; i += 16) {
+ __m256 lo[4], hi[4];
+ for (int k = 0; k < 4; k++)
+ lo[k] = hi[k] = _mm256_set1_ps(b ? b[co + k] : 0);
+ for (int ci = 0; ci < Ci; ci++) {
+ const float* pixel = in + (size_t)ci * HW + i;
+ __m256 x = _mm256_loadu_ps(pixel);
+ __m256 y = _mm256_loadu_ps(pixel + 8);
+ for (int k = 0; k < 4; k++) {
+ __m256 weight = _mm256_set1_ps(w[(size_t)(co + k) * Ci + ci]);
+ lo[k] = _mm256_fmadd_ps(weight, x, lo[k]);
+ hi[k] = _mm256_fmadd_ps(weight, y, hi[k]);
+ }
+ }
+ for (int k = 0; k < 4; k++) {
+ float* dst = out + (size_t)(co + k) * HW + i;
+ _mm256_storeu_ps(dst, lo[k]);
+ _mm256_storeu_ps(dst + 8, hi[k]);
+ }
+ }
+ }
+ return;
+ }
+#endif
/* Initialize output with bias */
for (int co = 0; co < Co; co++) {
float bias = b ? b[co] : 0;
diff --git a/tests/bench_yunet_detail.py b/tests/bench_yunet_detail.py
new file mode 100644
index 0000000..c4c94e4
--- /dev/null
+++ b/tests/bench_yunet_detail.py
@@ -0,0 +1,120 @@
+"""Compare detail recovery at full frame, crop and confidence operating points."""
+import argparse
+import ctypes
+import io
+import os
+from pathlib import Path
+import tempfile
+import time
+from zipfile import ZipFile
+
+import numpy as np
+from PIL import Image
+
+from bench_yunet_bottlenecks import annotations, load_lib, match, native_run, prepare_rectangle, source_boxes
+from bench_yunet_tiles import deduplicate
+
+MODES = ("current", "soft", "full800", "guided448")
+
+
+def detect(lib, engine, rgb, side):
+ h, w = rgb.shape[:2]
+ canvas, rw, rh = prepare_rectangle(rgb, bgr=True, side=side)
+ ch, cw = canvas.shape[:2]
+ boxes = native_run(lib, engine, canvas, capacity=32)
+ return source_boxes(boxes, w, h, rw, rh, cw, ch)
+
+
+def refine(lib, engine, rgb, boxes):
+ h, w = rgb.shape[:2]
+ dim = np.sqrt((boxes[:, 2:4] - boxes[:, :2]).prod(1)) * 320 / max(w, h)
+ hints = boxes[(dim < 20) & (boxes[:, 4] < .85)]
+ if not len(hints):
+ return boxes, False
+ # Select the most populated half-frame neighborhood of small proposals.
+ centers = (hints[:, :2] + hints[:, 2:4]) * .5
+ delta = np.abs(centers[:, None] - centers)
+ counts = ((delta[:,:,0] <= w/4) & (delta[:,:,1] <= h/4)).sum(1)
+ cx, cy = centers[np.argmax(counts)]
+ cw, ch = max(1, w//2), max(1, h//2)
+ x, y = int(np.clip(cx-cw/2, 0, w-cw)), int(np.clip(cy-ch/2, 0, h-ch))
+ extra = detect(lib, engine, rgb[y:y+ch, x:x+cw], 448)
+ extra[:, :4] += [x, y, x, y]
+ return deduplicate(np.concatenate((boxes, extra)))[:32], True
+
+
+def score(data, mode, threshold):
+ records, identities = [], []
+ for gt, small, predictions, _, _ in data:
+ det = predictions[mode]
+ det = det[det[:,4] >= np.float32(threshold)]
+ good = match(det, gt)
+ records.append([len(good), len(det)-len(good), small[good].sum()])
+ identities.append(set(good[small[good]]))
+ return np.array(records), identities
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ for key in ("weights", "images", "labels"):
+ parser.add_argument(key, type=Path)
+ args = parser.parse_args()
+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})
+ with ZipFile(args.labels) as archive:
+ labels = annotations(archive)
+ pool = set(labels)
+ for seed, size in ((114, 640), (725, 128), (3519, 672), (9101, 384)):
+ pool -= set(np.random.default_rng(seed).choice(sorted(pool), size, replace=False))
+ names = np.random.default_rng(60177).choice(sorted(pool), 448, replace=False)
+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:
+ lib = load_lib(Path(tmp), "native")
+ engine = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))
+ if not engine:
+ raise RuntimeError("Failed to load detector")
+ lib.detect_set_score_threshold(engine, ctypes.c_float(.35))
+ try:
+ for side in (448, 640, 800):
+ detect(lib, engine, np.zeros((480, 640, 3), dtype=np.uint8), side)
+ data = []
+ for i, name in enumerate(names):
+ image = np.asarray(Image.open(io.BytesIO(photos.read("WIDER_val/images/"+name))).convert("RGB"))
+ gt = labels[name].copy()
+ small = np.sqrt(gt[:,2:].prod(1))*320/max(image.shape[:2]) < 16
+ gt[:,2:] += gt[:,:2]
+ boxes, ms = {}, {}
+ for side in ((640,800) if i%2 else (800,640)):
+ start = time.thread_time_ns()
+ boxes[side] = detect(lib, engine, image, side)
+ ms[side] = (time.thread_time_ns()-start)/1e6
+ start = time.thread_time_ns()
+ guided, used = refine(lib, engine, image, boxes[640])
+ add = (time.thread_time_ns()-start)/1e6
+ data.append((gt,small,[boxes[640],boxes[640],boxes[800],guided],
+ [ms[640],ms[640],ms[800],ms[640]+add],used))
+ finally:
+ lib.detect_free(engine)
+ dev, test = data[:128], data[128:]
+ budget = score(dev,0,.70)[0].sum(0)[1]
+ thresholds = [.70,.55]
+ for mode in (2,3):
+ trials = [(t,score(dev,mode,t)[0].sum(0)) for t in np.round(np.arange(.40,.961,.01),2)]
+ best = max((r for r in trials if r[1][1]<=budget), key=lambda r:(r[1][2],r[1][0],-abs(r[0]-.7)))
+ thresholds.append(best[0])
+ for i,t in enumerate(thresholds):
+ print("dev",MODES[i],t,score(dev,i,t)[0].sum(0))
+ original, ids = score(test,0,.70)
+ print("held out GT / small / crop calls",sum(len(x[0]) for x in test),sum(x[1].sum() for x in test),sum(x[4] for x in test))
+ bs=np.random.default_rng(60178).integers(len(test),size=(2000,len(test)))
+ for i,t in enumerate(thresholds):
+ result, after = score(test,i,t)
+ delta = result-original
+ times=np.array([x[3][i] for x in test])
+ gained=sum(len(a-b) for a,b in zip(after,ids))
+ lost=sum(len(b-a) for a,b in zip(after,ids))
+ print("test",MODES[i],t,result.sum(0),"small recovered/lost", gained,lost,
+ "CPU mean/median",np.round([times.mean(),np.median(times)],2),
+ "delta interval", np.percentile(delta[bs].sum(1),[2.5,97.5],axis=0).round(1).tolist())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/bench_yunet_kernels.py b/tests/bench_yunet_kernels.py
new file mode 100644
index 0000000..2b23756
--- /dev/null
+++ b/tests/bench_yunet_kernels.py
@@ -0,0 +1,60 @@
+"""Compare all returned YuNet coordinates and end-to-end detector CPU on AVX2/FMA."""
+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 bench_yunet_bottlenecks import ROOT, load_lib, native_run, prepare_rectangle
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("weights", type=Path)
+ parser.add_argument("images", type=Path)
+ args = parser.parse_args()
+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})
+ with tempfile.TemporaryDirectory() as work, ZipFile(args.images) as photos:
+ tmp = Path(work)
+ new = tmp / "current.so"
+ subprocess.run(["gcc", "-O3", "-march=native", "-I", str(ROOT/"include"), "-fPIC",
+ "-shared", str(ROOT/"src/detect.c"), "-lm", "-o", str(new)], check=True)
+ libs = [load_lib(tmp, "reference"), ctypes.CDLL(str(new))]
+ engines = []
+ for lib in libs:
+ lib.detect_init.restype = ctypes.c_void_p
+ eng = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))
+ if not eng:
+ raise RuntimeError("Failed to load detector")
+ engines.append(eng)
+ lib.detect_set_score_threshold(eng, ctypes.c_float(.40))
+ times = np.zeros((64, 2, 2))
+ names = np.random.default_rng(781).choice(sorted(n for n in photos.namelist() if n.endswith(".jpg")),65,replace=False)
+ try:
+ for i, name in enumerate(names):
+ rgb = np.asarray(Image.open(io.BytesIO(photos.read(name))).convert("RGB"))
+ for j, side in enumerate((640, 800)):
+ pred = {}
+ for k in (i%2, 1-i%2):
+ start = time.thread_time_ns()
+ canvas, _, _ = prepare_rectangle(rgb, bgr=True, side=side)
+ pred[k] = native_run(libs[k], engines[k], canvas, capacity=10000)
+ if i:
+ times[i-1,j,k] = (time.thread_time_ns()-start)/1e6
+ np.testing.assert_array_equal(pred[0], pred[1])
+ print("CPU ms, rows 640 and 800, columns reference and current")
+ print("median", np.median(times,axis=0), "mean", times.mean(0))
+ finally:
+ for lib, eng in zip(libs, engines):
+ lib.detect_free(eng)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/verify_rectangular_client.py b/tests/verify_rectangular_client.py
index 77d46f8..ce512be 100644
--- a/tests/verify_rectangular_client.py
+++ b/tests/verify_rectangular_client.py
@@ -20,11 +20,12 @@ def main():
lib.detect_init.restype = ctypes.c_void_p
det = ctypes.c_void_p(lib.detect_init(os.fsencode(os.environ["DETECT_WEIGHTS"])))
assert det
- lib.detect_set_score_threshold(det, ctypes.c_float(.70))
+ side = int(os.environ.get("FACEX_DETECT_SIZE", "640"))
+ lib.detect_set_score_threshold(det, ctypes.c_float(.75 if side == 800 else .70))
lib.align_face.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p]
sdk = FaceX(embed_weights=os.environ["EMBED_WEIGHTS"], detect_weights=os.environ["DETECT_WEIGHTS"],
- input_policy="rectangle_bgr")
+ input_policy="rectangle_bgr_800" if side == 800 else "rectangle_bgr")
client = app.test_client()
patch = Image.open(ROOT / "data/test_face.jpg").convert("RGB").resize((241, 241))
try:
@@ -32,7 +33,7 @@ def main():
image = Image.new("RGB", (w, h))
image.paste(patch, ((w - 241) // 2, (h - 241) // 2))
rgb = np.asarray(image)
- canvas, rw, rh = prepare_rectangle(rgb)
+ canvas, rw, rh = prepare_rectangle(rgb, side=side)
ch, cw = canvas.shape[:2]
expected = native_run(lib, det, np.ascontiguousarray(canvas[:, :, ::-1]))
faces = sdk.detect(rgb)