Project 4: Face Detection
In this project you build and evaluate a face anonymiser: a component that finds every face in an image and destroys it before the image is stored or published. It is the most common legal use of face detection (street-level imagery, dash-cam footage, research video, newsroom photos of bystanders), and it has an unusual requirement: a missed face is a privacy failure, while an extra blurred patch is nearly free. So the project is about recall, measured honestly per condition, not about a single accuracy number.
You start from the Haar cascade of face detection, build a labelled test set in which every face's position, size, rotation and brightness is known, find where the cascade fails, improve it, and deliver the anonymiser with a measured protection rate.
Note: The test set is built from one public-domain portrait (scikit-image's
astronaut, NASA's Eileen Collins) pasted onto scikit-image backgrounds. A real anonymiser must be tested on footage from the cameras it will run on, with faces of all ages, skin tones and poses, collected and stored lawfully (privacy, consent and licensing). One face cannot tell you anything about demographic differences; say so in your write-up.
Goal and success criteria
| Item | Target |
|---|---|
| Task | single-class face detection, then blurring of every detected face |
| Primary metric | face-level recall at IoU , overall and per condition (size, rotation, brightness) |
| Secondary | false positives per image (cost: needlessly blurred area) |
| Deliverable | anonymise(img) plus a table: share of faces covered by the blur |
| Success | recall for faces of at least 24 pixels, upright to degrees, at normal and low light; at most 1 false positive per image |
IoU 0.4 rather than 0.5 because the ground-truth box of a rotated face is an axis-aligned square of the face size, which a correct detection on a tilted head does not fit exactly; IoU itself is defined in detection metrics.
Step 1: a test set with exact ground truth
The generator cuts the astronaut's face with a 30-pixel margin, scales it so the face box is size pixels wide, rotates it, multiplies its brightness by gain, and blends it with a soft oval edge into a random place on one of six grey backgrounds of 200 x 200 pixels. The ground-truth box is the face box at the pasted centre.
import numpy as np
import cv2
import matplotlib.pyplot as plt
from skimage import data
cv2.setLogLevel(0)
def grey(im):
return cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) if im.ndim == 3 else im
FACE_PATCH = grey(data.astronaut())[36:191, 147:302] # face [177, 66, 95, 95] with a 30 px margin
BACKGROUNDS = [cv2.resize(grey(getattr(data, n)()), (200, 200), interpolation=cv2.INTER_AREA)
for n in ["camera", "coins", "page", "coffee", "rocket", "brick"]]
def paste_face(rng, bg, size, angle=0.0, gain=1.0):
"""Face box `size` px, turned by `angle` degrees, brightness x gain, at a random place.
Returns the grey image and the ground-truth box [x1, y1, x2, y2]."""
n = int(round(155 * size / 95))
patch = cv2.resize(FACE_PATCH, (n, n), interpolation=cv2.INTER_AREA).astype(float)
M = cv2.getRotationMatrix2D((n / 2, n / 2), angle, 1.0)
patch = cv2.warpAffine(patch, M, (n, n), borderMode=cv2.BORDER_REPLICATE) * gain
yy, xx = np.mgrid[0:n, 0:n]
alpha = np.clip((0.5 - np.hypot(xx - n / 2, (yy - n / 2) * 0.85) / n) * 8, 0, 1) # soft oval
x0, y0 = int(rng.integers(0, 200 - n + 1)), int(rng.integers(0, 200 - n + 1))
img = bg.astype(float)
img[y0:y0 + n, x0:x0 + n] = alpha * patch + (1 - alpha) * img[y0:y0 + n, x0:x0 + n]
c = n / 2
box = [int(round(x0 + c - size / 2)), int(round(y0 + c - size / 2)), int(round(x0 + c + size / 2)), int(round(y0 + c + size / 2))]
return img.clip(0, 255).astype(np.uint8), box
rng = np.random.default_rng(0)
examples = [(80, 0, 1.0), (24, 0, 1.0), (56, 30, 1.0), (56, 0, 0.2)]
fig, axes = plt.subplots(1, 4, figsize=(7, 2))
for ax, bg, (s, a, g) in zip(axes, BACKGROUNDS, examples):
img, box = paste_face(rng, bg, s, a, g)
print(f"size {s:2d}, angle {a:2d}, gain {g:.1f}: ground truth {box}")
ax.imshow(img, cmap="gray", vmin=0, vmax=255)
ax.add_patch(plt.Rectangle((box[0], box[1]), box[2] - box[0], box[3] - box[1], fill=False, color="lime"))
ax.set_title(f"{s} px, {a} deg, x{g}", fontsize=8); ax.axis("off")
fig.tight_layout()size 80, angle 0, gain 1.0: ground truth [84, 70, 164, 150]
size 24, angle 0, gain 1.0: ground truth [90, 50, 114, 74]
size 56, angle 30, gain 1.0: ground truth [50, 22, 106, 78]
size 56, angle 0, gain 0.2: ground truth [26, 18, 82, 74]
The four panels show the conditions the cascade will be tested on: a large face, a face at the edge of the cascade's 24-pixel window, a tilted face and a dark one.
Step 2: the baseline, one factor at a time
The baseline is OpenCV's frontal cascade with the settings most tutorials use (scaleFactor=1.1, minNeighbors=5; OpenCV's own default for minNeighbors is 3). Each condition is tested on all six backgrounds, changing one factor at a time from a reference face (56 pixels, upright, gain 1.0), so that each recall curve shows the effect of one cause. With six images per condition every recall is a multiple of ; treat differences of one image as noise.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def grey(im):
return cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) if im.ndim == 3 else im
FACE_PATCH = grey(data.astronaut())[36:191, 147:302]
BACKGROUNDS = [cv2.resize(grey(getattr(data, n)()), (200, 200), interpolation=cv2.INTER_AREA)
for n in ["camera", "coins", "page", "coffee", "rocket", "brick"]]
def paste_face(rng, bg, size, angle=0.0, gain=1.0):
n = int(round(155 * size / 95))
patch = cv2.resize(FACE_PATCH, (n, n), interpolation=cv2.INTER_AREA).astype(float)
M = cv2.getRotationMatrix2D((n / 2, n / 2), angle, 1.0)
patch = cv2.warpAffine(patch, M, (n, n), borderMode=cv2.BORDER_REPLICATE) * gain
yy, xx = np.mgrid[0:n, 0:n]
alpha = np.clip((0.5 - np.hypot(xx - n / 2, (yy - n / 2) * 0.85) / n) * 8, 0, 1)
x0, y0 = int(rng.integers(0, 200 - n + 1)), int(rng.integers(0, 200 - n + 1))
img = bg.astype(float)
img[y0:y0 + n, x0:x0 + n] = alpha * patch + (1 - alpha) * img[y0:y0 + n, x0:x0 + n]
c = n / 2
box = [int(round(x0 + c - size / 2)), int(round(y0 + c - size / 2)), int(round(x0 + c + size / 2)), int(round(y0 + c + size / 2))]
return img.clip(0, 255).astype(np.uint8), box
CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
def detect(img, mn=5):
return [[int(x), int(y), int(x + w), int(y + h)] for x, y, w, h in CASCADE.detectMultiScale(img, 1.1, mn)]
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = iw * ih
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def evaluate(rng, size=56, angle=0, gain=1.0):
hits = fps = 0
for bg in BACKGROUNDS:
img, box = paste_face(rng, bg, size, angle, gain)
dets = detect(img)
hit = any(iou(d, box) >= 0.4 for d in dets)
hits += hit; fps += len(dets) - hit
return hits / len(BACKGROUNDS), fps / len(BACKGROUNDS)
rng = np.random.default_rng(1)
for name, key, values in [("face size (px)", "size", [16, 20, 24, 32, 48, 64, 80]),
("rotation (deg)", "angle", [0, 10, 20, 30, 45]),
("brightness gain", "gain", [1.0, 0.6, 0.35, 0.2, 0.1])]:
print(name)
for v in values:
r, fp = evaluate(rng, **{key: v})
print(f" {v:>5}: recall {r:.2f}, false positives per image {fp:.2f}")face size (px)
16: recall 0.00, false positives per image 0.50
20: recall 0.00, false positives per image 0.50
24: recall 1.00, false positives per image 0.50
32: recall 0.83, false positives per image 0.50
48: recall 1.00, false positives per image 0.17
64: recall 1.00, false positives per image 0.33
80: recall 1.00, false positives per image 0.33
rotation (deg)
0: recall 1.00, false positives per image 0.33
10: recall 1.00, false positives per image 0.50
20: recall 1.00, false positives per image 0.50
30: recall 0.00, false positives per image 0.33
45: recall 0.00, false positives per image 0.33
brightness gain
1.0: recall 1.00, false positives per image 0.33
0.6: recall 1.00, false positives per image 0.50
0.35: recall 1.00, false positives per image 0.50
0.2: recall 1.00, false positives per image 0.50
0.1: recall 0.00, false positives per image 0.50
Three clean failure modes appear. Size: no face below 24 pixels is found (recall 0 at 16 and 20), because the cascade's window is 24 x 24 and it never looks at anything smaller; from 24 pixels on almost every face is found (the one miss at 32 pixels is one image of six). Rotation: recall is 1 up to 20 degrees and 0 from 30 degrees on. Brightness: the cascade copes down to a gain of 0.2, because its features compare sums, and fails at 0.1. False positives (0.17 to 0.50 per image) do not depend on the face: they come from face-like texture in the backgrounds, which is the same whatever is pasted.
Step 3: the minNeighbors dial
detectMultiScale first collects all raw windows that pass the cascade, then groups overlapping ones and keeps groups with more than minNeighbors members. So a whole recall / false-positive curve needs only one cascade pass per image: collect the raw windows with minNeighbors=0 and group them yourself with cv2.groupRectangles, which uses the same rule (overlap tolerance eps=0.2). The example checks that equivalence, then sweeps the dial on a mixed set: sizes 24 to 64, upright and 15 degrees, normal and half brightness, on all six backgrounds (96 images).
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def grey(im):
return cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) if im.ndim == 3 else im
FACE_PATCH = grey(data.astronaut())[36:191, 147:302]
BACKGROUNDS = [cv2.resize(grey(getattr(data, n)()), (200, 200), interpolation=cv2.INTER_AREA)
for n in ["camera", "coins", "page", "coffee", "rocket", "brick"]]
def paste_face(rng, bg, size, angle=0.0, gain=1.0):
n = int(round(155 * size / 95))
patch = cv2.resize(FACE_PATCH, (n, n), interpolation=cv2.INTER_AREA).astype(float)
M = cv2.getRotationMatrix2D((n / 2, n / 2), angle, 1.0)
patch = cv2.warpAffine(patch, M, (n, n), borderMode=cv2.BORDER_REPLICATE) * gain
yy, xx = np.mgrid[0:n, 0:n]
alpha = np.clip((0.5 - np.hypot(xx - n / 2, (yy - n / 2) * 0.85) / n) * 8, 0, 1)
x0, y0 = int(rng.integers(0, 200 - n + 1)), int(rng.integers(0, 200 - n + 1))
img = bg.astype(float)
img[y0:y0 + n, x0:x0 + n] = alpha * patch + (1 - alpha) * img[y0:y0 + n, x0:x0 + n]
c = n / 2
box = [int(round(x0 + c - size / 2)), int(round(y0 + c - size / 2)), int(round(x0 + c + size / 2)), int(round(y0 + c + size / 2))]
return img.clip(0, 255).astype(np.uint8), box
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = iw * ih
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
rng = np.random.default_rng(2)
test = [paste_face(rng, bg, s, a, g) for s in [24, 32, 48, 64] for a in [0, 15] for g in [1.0, 0.5] for bg in BACKGROUNDS]
raw = [[list(map(int, r)) for r in CASCADE.detectMultiScale(img, 1.1, 0)] for img, _ in test]
def grouped(rects, mn):
if not rects:
return []
g, _ = cv2.groupRectangles(rects, mn, 0.2)
return [[int(x), int(y), int(x + w), int(y + h)] for x, y, w, h in g]
same = all(sorted(grouped(raw[i], 5)) == sorted([[int(x), int(y), int(x + w), int(y + h)] for x, y, w, h in
CASCADE.detectMultiScale(test[i][0], 1.1, 5)]) for i in range(12))
print("groupRectangles(raw, 5) equals detectMultiScale(minNeighbors=5) on 12 images:", same)
print(f"{len(test)} images, raw windows per image: mean {np.mean([len(r) for r in raw]):.1f}")
print("minNeighbors recall FP/image")
for mn in [1, 2, 3, 5, 8, 12]:
hits = fps = 0
for (img, box), r in zip(test, raw):
dets = grouped(r, mn)
hit = any(iou(d, box) >= 0.4 for d in dets)
hits += hit; fps += len(dets) - hit
print(f"{mn:11d} {hits / len(test):.3f} {fps / len(test):.2f}")groupRectangles(raw, 5) equals detectMultiScale(minNeighbors=5) on 12 images: True
96 images, raw windows per image: mean 29.4
minNeighbors recall FP/image
1 1.000 2.12
2 1.000 0.93
3 1.000 0.78
5 0.906 0.45
8 0.625 0.15
12 0.500 0.00
The equivalence holds, so the sweep below is exact. On the mixed set every face is found at minNeighbors 1 to 3, with false positives falling from 2.12 to 0.78 per image; at the tutorial value 5 recall drops to 0.906 and false positives to 0.45; at 12 there are no false positives but half of the faces are lost. For an anonymiser, 3 is the sensible choice on this set: full recall at under one false positive per image. A counting application (precision-first) would pick 8 or more.
Step 4: an improved detector
The baseline's failures from step 2 suggest three cheap fixes that need no new model:
- Histogram equalisation before detection, for dark faces.
- Upscaling the image by 1.6 before detection, so that faces down to about 15 pixels fill the 24-pixel window.
- Rotated passes at and degrees, mapping each detection's centre back with the inverse rotation, for tilted heads.
The passes produce overlapping boxes for the same face, which are merged by a simple overlap rule (a box is dropped if it overlaps an already kept box with IoU above 0.3), a crude form of non-maximum suppression. The comparison runs on a hard set of small, tilted and dark faces (sizes 20, 32, 56; angles 0 and 25; gains 1.0 and 0.3; four backgrounds: 48 images), against the baseline at minNeighbors=3, the value step 3 suggests for a recall-first task. The improved detector is evaluated at three values of the dial; as in step 3, the raw windows of each pass are computed once and grouped per value.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def grey(im):
return cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) if im.ndim == 3 else im
FACE_PATCH = grey(data.astronaut())[36:191, 147:302]
BACKGROUNDS = [cv2.resize(grey(getattr(data, n)()), (200, 200), interpolation=cv2.INTER_AREA)
for n in ["camera", "coins", "page", "coffee", "rocket", "brick"]]
def paste_face(rng, bg, size, angle=0.0, gain=1.0):
n = int(round(155 * size / 95))
patch = cv2.resize(FACE_PATCH, (n, n), interpolation=cv2.INTER_AREA).astype(float)
M = cv2.getRotationMatrix2D((n / 2, n / 2), angle, 1.0)
patch = cv2.warpAffine(patch, M, (n, n), borderMode=cv2.BORDER_REPLICATE) * gain
yy, xx = np.mgrid[0:n, 0:n]
alpha = np.clip((0.5 - np.hypot(xx - n / 2, (yy - n / 2) * 0.85) / n) * 8, 0, 1)
x0, y0 = int(rng.integers(0, 200 - n + 1)), int(rng.integers(0, 200 - n + 1))
img = bg.astype(float)
img[y0:y0 + n, x0:x0 + n] = alpha * patch + (1 - alpha) * img[y0:y0 + n, x0:x0 + n]
c = n / 2
box = [int(round(x0 + c - size / 2)), int(round(y0 + c - size / 2)), int(round(x0 + c + size / 2)), int(round(y0 + c + size / 2))]
return img.clip(0, 255).astype(np.uint8), box
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = iw * ih
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
def merge(boxes, thr=0.3):
kept = []
for b in sorted(boxes, key=lambda b: -(b[2] - b[0])):
if all(iou(b, k) <= thr for k in kept):
kept.append(b)
return kept
def grouped(rects, mn):
if not rects:
return []
g, _ = cv2.groupRectangles(rects, mn, 0.2)
return [list(map(int, r)) for r in g]
def raw_passes(img):
"""Raw cascade windows (minNeighbors=0) of each pass, with the inverse transform of that pass."""
H, W = img.shape
eq = cv2.equalizeHist(img)
passes = []
for angle, up in [(0, 1.6), (-25, 1.0), (25, 1.0)]:
M = cv2.getRotationMatrix2D((W / 2, H / 2), angle, up)
M[:, 2] += [(up - 1) * W / 2, (up - 1) * H / 2] # keep the scaled image inside the canvas
view = cv2.warpAffine(eq, M, (int(W * up), int(H * up)), borderMode=cv2.BORDER_REPLICATE)
raw = [list(map(int, r)) for r in CASCADE.detectMultiScale(view, 1.1, 0)]
passes.append((raw, cv2.invertAffineTransform(M), up))
return passes
def detect_plus(passes, mn):
found = []
for raw, inv, up in passes:
for x, y, w, h in grouped(raw, mn):
cx, cy = inv @ [x + w / 2, y + h / 2, 1] # box centre back in the original image
s = w / up
found.append([int(cx - s / 2), int(cy - s / 2), int(cx + s / 2), int(cy + s / 2)])
return merge(found)
rng = np.random.default_rng(3)
test = [(s, a, g) + paste_face(rng, bg, s, a, g) for s in [20, 32, 56] for a in [0, 25] for g in [1.0, 0.3] for bg in BACKGROUNDS[:4]]
base_raw = [[list(map(int, r)) for r in CASCADE.detectMultiScale(img, 1.1, 0)] for *_, img, _ in test]
plus_raw = [raw_passes(img) for *_, img, _ in test]
def run(name, detector):
rows = []
for (s, a, g, img, box), br, pr in zip(test, base_raw, plus_raw):
dets = detector(br, pr)
hit = any(iou(d, box) >= 0.4 for d in dets)
rows.append((s, a, g, hit, len(dets) - hit))
print(f"{name:20s} recall {np.mean([r[3] for r in rows]):.3f}, FP/image {np.mean([r[4] for r in rows]):.2f}")
return rows
def xyxy(rects):
return [[x, y, x + w, y + h] for x, y, w, h in rects]
base = run("baseline, mn=3", lambda br, pr: xyxy(grouped(br, 3)))
for mn in [3, 5, 8]:
plus = run(f"improved, mn={mn}", lambda br, pr, mn=mn: detect_plus(pr, mn))
if mn == 5:
chosen = plus
for key, idx in [("size", 0), ("angle", 1), ("gain", 2)]:
for v in sorted({r[idx] for r in base}):
rb = np.mean([r[3] for r in base if r[idx] == v]); ri = np.mean([r[3] for r in chosen if r[idx] == v])
print(f" {key} {v:>4}: baseline mn=3 {rb:.2f} -> improved mn=5 {ri:.2f}")
print("missed by improved mn=5 (size, angle, gain):", [(s, a, g) for s, a, g, hit, _ in chosen if not hit])baseline, mn=3 recall 0.438, FP/image 1.15
improved, mn=3 recall 0.708, FP/image 3.94
improved, mn=5 recall 0.688, FP/image 2.44
improved, mn=8 recall 0.562, FP/image 1.21
size 20: baseline mn=3 0.12 -> improved mn=5 0.31
size 32: baseline mn=3 0.50 -> improved mn=5 0.75
size 56: baseline mn=3 0.69 -> improved mn=5 1.00
angle 0: baseline mn=3 0.75 -> improved mn=5 0.83
angle 25: baseline mn=3 0.12 -> improved mn=5 0.54
gain 0.3: baseline mn=3 0.46 -> improved mn=5 0.62
gain 1.0: baseline mn=3 0.42 -> improved mn=5 0.75
missed by improved mn=5 (size, angle, gain): [(20, 0, 1.0), (20, 0, 0.3), (20, 0, 0.3), (20, 25, 1.0), (20, 25, 1.0), (20, 25, 1.0), (20, 25, 1.0), (20, 25, 0.3), (20, 25, 0.3), (20, 25, 0.3), (20, 25, 0.3), (32, 0, 0.3), (32, 25, 1.0), (32, 25, 0.3), (32, 25, 0.3)]
On these deliberately hard faces the baseline finds 43.8 % (21 of 48). The improved detector raises recall to 0.708 at minNeighbors=3, and the per-condition lines (at 5) show where: 56-pixel faces from 0.69 to 1.00, tilted faces from 0.12 to 0.54, small 20-pixel faces from 0.12 to 0.31. The price is false positives: three passes see three times the background texture, and the upscaled pass finds face-like patterns at scales the baseline never examined, so false positives rise from 1.15 to 3.94 per image at minNeighbors=3. Raising the dial to 8 brings them back to the baseline's level (1.21) but recall falls to 0.562. The remaining misses are almost all 20-pixel faces and tilted 32-pixel faces, often dark: the limits of a 2001 detector that a few tricks cannot remove. The success criteria are not met for faces this small, tilted and dark; that is the finding to report, together with the recommendation to evaluate a CNN detector on the same test set.
Step 5: the deliverable and its protection rate
The anonymiser pads each detected box by 25 % on every side and replaces it with a coarse mosaic (the face detection lesson showed that a Gaussian blur can leave a face the cascade still finds). Its quality measure is not IoU but coverage: the share of each ground-truth face box that ended up inside a mosaic region. A face counts as protected when at least 90 % of its box is covered. The cost is the share of the image that was mosaicked although it contains no face.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def grey(im):
return cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) if im.ndim == 3 else im
FACE_PATCH = grey(data.astronaut())[36:191, 147:302]
BACKGROUNDS = [cv2.resize(grey(getattr(data, n)()), (200, 200), interpolation=cv2.INTER_AREA)
for n in ["camera", "coins", "page", "coffee", "rocket", "brick"]]
def paste_face(rng, bg, size, angle=0.0, gain=1.0):
n = int(round(155 * size / 95))
patch = cv2.resize(FACE_PATCH, (n, n), interpolation=cv2.INTER_AREA).astype(float)
M = cv2.getRotationMatrix2D((n / 2, n / 2), angle, 1.0)
patch = cv2.warpAffine(patch, M, (n, n), borderMode=cv2.BORDER_REPLICATE) * gain
yy, xx = np.mgrid[0:n, 0:n]
alpha = np.clip((0.5 - np.hypot(xx - n / 2, (yy - n / 2) * 0.85) / n) * 8, 0, 1)
x0, y0 = int(rng.integers(0, 200 - n + 1)), int(rng.integers(0, 200 - n + 1))
img = bg.astype(float)
img[y0:y0 + n, x0:x0 + n] = alpha * patch + (1 - alpha) * img[y0:y0 + n, x0:x0 + n]
c = n / 2
box = [int(round(x0 + c - size / 2)), int(round(y0 + c - size / 2)), int(round(x0 + c + size / 2)), int(round(y0 + c + size / 2))]
return img.clip(0, 255).astype(np.uint8), box
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = iw * ih
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
def merge(boxes, thr=0.3):
kept = []
for b in sorted(boxes, key=lambda b: -(b[2] - b[0])):
if all(iou(b, k) <= thr for k in kept):
kept.append(b)
return kept
def detect_plus(img, mn=5):
H, W = img.shape
eq = cv2.equalizeHist(img)
found = []
for angle, up in [(0, 1.6), (-25, 1.0), (25, 1.0)]:
M = cv2.getRotationMatrix2D((W / 2, H / 2), angle, up)
M[:, 2] += [(up - 1) * W / 2, (up - 1) * H / 2]
view = cv2.warpAffine(eq, M, (int(W * up), int(H * up)), borderMode=cv2.BORDER_REPLICATE)
inv = cv2.invertAffineTransform(M)
for x, y, w, h in CASCADE.detectMultiScale(view, 1.1, mn):
cx, cy = inv @ [x + w / 2, y + h / 2, 1]
s = w / up
found.append([int(cx - s / 2), int(cy - s / 2), int(cx + s / 2), int(cy + s / 2)])
return merge(found)
def anonymise(img, pad=0.25, blocks=6):
"""Returns the anonymised image and the boolean mask of the mosaicked pixels."""
out, mask = img.copy(), np.zeros(img.shape, bool)
H, W = img.shape
for x1, y1, x2, y2 in detect_plus(img): # minNeighbors=5 per pass, chosen in step 4
w, h = x2 - x1, y2 - y1
x1, y1 = max(int(x1 - pad * w), 0), max(int(y1 - pad * h), 0)
x2, y2 = min(int(x2 + pad * w), W), min(int(y2 + pad * h), H)
small = cv2.resize(out[y1:y2, x1:x2], (blocks, blocks), interpolation=cv2.INTER_AREA)
out[y1:y2, x1:x2] = cv2.resize(small, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST)
mask[y1:y2, x1:x2] = True
return out, mask
rng = np.random.default_rng(4)
test = [(s, g) + paste_face(rng, bg, s, 0, g) for s in [24, 40, 64] for g in [1.0, 0.4] for bg in BACKGROUNDS[:4]]
covered, wasted = [], []
for s, g, img, (x1, y1, x2, y2) in test:
out, mask = anonymise(img)
covered.append(mask[y1:y2, x1:x2].mean())
face = np.zeros_like(mask); face[y1:y2, x1:x2] = True
wasted.append((mask & ~face).mean())
covered = np.array(covered)
print(f"{len(test)} faces: protected (>= 90 % covered) {np.mean(covered >= 0.9):.3f}, mean coverage {covered.mean():.3f}")
print(f"image share mosaicked outside the face boxes: mean {np.mean(wasted):.3f}, max {np.max(wasted):.3f}")
print("unprotected faces (size, gain, coverage):", [(s, g, round(float(c), 2)) for (s, g, *_), c in zip(test, covered) if c < 0.9])24 faces: protected (>= 90 % covered) 0.833, mean coverage 0.895
image share mosaicked outside the face boxes: mean 0.194, max 0.700
unprotected faces (size, gain, coverage): [(24, 1.0, 0.61), (24, 1.0, 0.0), (24, 0.4, 0.0), (24, 0.4, 0.88)]
On the 24 upright test faces (sizes 24, 40 and 64 pixels, normal and dark), 83.3 % are protected and the mean coverage is 0.895. All four unprotected faces are the 24-pixel ones: two were missed completely (coverage 0), two partly covered (0.61 and 0.88) because a detection was off-centre. The cost is high: on average 19.4 % of each image is mosaicked outside the face boxes, and on one image 70 %, because the false positives of the three passes are padded and mosaicked too. A product team would read this table as: acceptable for faces of 40 pixels and more, not for crowds of small faces, and too destructive on busy backgrounds.
Error analysis
Go back through the misses of steps 2, 4 and 5 and sort them by cause before changing anything else:
| Cause | Evidence in this project | Fix to try |
|---|---|---|
| Face smaller than the cascade window | recall falls below 24 px in step 2 | upscale (done), or a CNN detector with small anchors |
| In-plane rotation | recall falls from about 30 degrees on | rotated passes (done); landmark-based CNN detectors |
| Low light, low contrast | recall falls to 0 at gain 0.1 (step 2); dark small faces stay hard (step 4) | equalisation (done); CLAHE; better exposure at capture |
| Texture that looks like a face | false positives on busy backgrounds | higher minNeighbors (costs recall), a second-stage check |
| Out-of-plane pose, occlusion, other people | not tested: one frontal face | a real, lawfully collected test set |
The last row is the most important line of the write-up: everything measured here is about one frontal face under synthetic changes.
Your turn
- Add
haarcascade_profileface.xmlas a fourth pass (and on the mirrored image, since it only finds faces turned one way). Build a "profile" test condition by squeezing the face patch horizontally to 60 % of its width. Does recall improve, and what does it cost in false positives?
Hint
Run the profile cascade on img and on img[:, ::-1], and mirror the second set of boxes back: x1' = W - x2, x2' = W - x1. Squeezing is a poor stand-in for a real profile; say so when you report the number.
- Tune
minNeighborsfor the improved detector on one set of images and report the result on a different set (other seeds and backgrounds). Why does that matter?
Answer
Choosing the dial on the same images you report on is tuning on the test set: the reported recall is optimistic. Use one seed (or backgrounds) as a validation set to pick the value, then report on a test set generated with another seed and the other backgrounds.
- Measure the processing time per image of
detectanddetect_pluson your own machine (do not put timings into shared outputs). How many frames per second could each anonymise in a 1280 x 720 video?
Hint
Cascade cost grows roughly with the number of pixels times the number of pyramid levels; detect_plus runs on times the pixels. Scale your 200 x 200 timing by .
Write-up template
| Section | Content |
|---|---|
| Goal | anonymise faces in ...; recall-first because ... |
| Data | test set: source, number of images and faces, conditions, how ground truth was made; licence and consent |
| Method | detector, passes, minNeighbors, padding, mosaic size |
| Results | recall overall and per condition (table), FP per image, protection rate, area wasted |
| Errors | causes of the misses, with counts |
| Limits | what was not tested (pose, occlusion, demographics, real cameras) |
| Next steps | e.g. a CNN detector (YuNet / RetinaFace) evaluated on the same test set |
Test yourself
Why is the anonymiser tuned for recall rather than precision?
- Recall is easier to measure
- A missed face exposes a person, while a false positive only blurs some background
- Precision cannot be computed for faces
- The cascade has no precision
How can you get the whole minNeighbors curve with only one cascade pass per image?
- Run
detectMultiScaleonce with minNeighbors=20 - Collect the raw windows with minNeighbors=0 and group them yourself with
cv2.groupRectanglesfor each value - Lower
scaleFactor - Use the eye cascade
The improved detector reaches high recall on this test set. What may the write-up claim?
- The anonymiser works on any footage
- It meets the target for one frontal face under synthetic changes of size, rotation and brightness; pose, occlusion, other people and real cameras were not tested
- It has no demographic bias
- It is better than every CNN detector