TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Face Detection: Haar Cascades to CNN Detectors

Face Detection: Haar Cascades to CNN Detectors

A face detector answers one narrow question: where are the faces in this image? It returns a box per face, sometimes with five landmarks (eyes, nose tip, mouth corners), and nothing about who the person is. That makes it the first stage of almost every face pipeline: camera autofocus and exposure, photo apps that crop portraits, video-call background blur, privacy tools that blur every face in street footage, and, as the next lesson shows, face recognition, which only works on a well-cropped, aligned face.

Face detection is ordinary object detection with one class, but it has a long history of its own. In 2001 Paul Viola and Michael Jones published a detector that ran in real time on a desktop CPU of the day, built from three ideas: very cheap rectangle features, the integral image that makes them cheaper still, and a cascade that throws away most image windows after a few tests. OpenCV still ships the trained cascades, and they run in your browser here. This lesson builds the core pieces from scratch, measures what the cascade can and cannot do, then turns it into an anonymiser.

Note: A face is personal data, and a face template used to identify someone is biometric data, a "special category" under GDPR Art. 9 that needs an explicit legal basis (often consent). Detecting faces only to blur them is the privacy-friendly use, but the raw footage still contains them. Read privacy, consent and licensing before collecting face images. The only real face in this lesson is scikit-image's astronaut sample, a public-domain NASA portrait of Eileen Collins.

Haar-like features

Look at a frontal face in grey: the eye band is darker than the cheeks below it, and the bridge of the nose is brighter than the eyes on either side. A Haar-like feature measures exactly such a contrast: the sum of the pixels under the white rectangles minus the sum under the black ones, inside a detection window (24 x 24 pixels in the original detector). Viola and Jones used five shapes: two-rectangle edges (horizontal and vertical), three-rectangle lines (horizontal and vertical) and a four-rectangle checkerboard.

edgeedgelinelinefour five feature types 24 x 24 window white: nosedark: eyeswhite: cheeks value =white - dark

Each feature is a placement of one shape at one position and size inside the window. Counting them shows why the features must be cheap and why learning has to pick a few:

python · try it yourself
# Count every Haar-like feature in a 24 x 24 window: each base shape (w, h) can be stretched
# to (i*w, j*h) and placed at every position where it fits.
W = H = 24
shapes = {"edge, side by side": (2, 1), "edge, stacked": (1, 2), "line, 3 across": (3, 1),
          "line, 3 down": (1, 3), "four-rectangle": (2, 2)}
total = 0
for name, (bw, bh) in shapes.items():
    n = sum((W - fw + 1) * (H - fh + 1)
            for fw in range(bw, W + 1, bw) for fh in range(bh, H + 1, bh))
    total += n
    print(f"{name:20s} {n:7d}")
print(f"{'total':20s} {total:7d}")
edge, side by side     43200
edge, stacked          43200
line, 3 across         27600
line, 3 down           27600
four-rectangle         20736
total                 162336

More than 160,000 candidate features for one small window, each a few rectangle sums, evaluated at every position and scale of every frame. That is only feasible because a rectangle sum can be made to cost four memory reads.

The integral image

The integral image (summed-area table) stores at each position the sum of all pixels above and to the left:

I(x,y)=∑x′<x∑y′<yi(x′,y′)I(x, y) = \sum_{x' < x} \sum_{y' < y} i(x', y')

With one row and one column of zeros in front (as cv2.integral returns it), the sum over any rectangle with top-left corner (x,y)(x, y), width ww and height hh is four lookups:

S=I(x+w,y+h)−I(x+w,y)−I(x,y+h)+I(x,y)S = I(x + w, y + h) - I(x + w, y) - I(x, y + h) + I(x, y)

The two subtracted terms remove the strip above and the strip to the left; the last term adds back the corner that was subtracted twice. Building II costs one pass over the image (two cumulative sums); after that, a rectangle of any size costs the same. Here it is from scratch, checked against slicing and against OpenCV, and then used for one two-rectangle feature: "cheek band minus eye band" on the astronaut's face box, compared with the same feature on 500 random windows of the same size.

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

gray = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2GRAY)

def integral(img):
    ii = np.zeros((img.shape[0] + 1, img.shape[1] + 1), np.int64)
    ii[1:, 1:] = img.astype(np.int64).cumsum(axis=0).cumsum(axis=1)
    return ii

def rect_sum(ii, x, y, w, h):
    return int(ii[y + h, x + w] - ii[y, x + w] - ii[y + h, x] + ii[y, x])

ii = integral(gray)
print("integral image shape:", ii.shape, "| equals cv2.integral:", bool((ii == cv2.integral(gray)).all()))
x, y, w, h = 177, 66, 95, 95                       # the face box the cascade finds (next sections)
print("sum over the face box: slicing", int(gray[y:y + h, x:x + w].sum()), "| 4 lookups", rect_sum(ii, x, y, w, h))

def eye_cheek(ii, x, y, s):
    """Mean of the cheek band minus mean of the eye band, bands at 25-45 % and 45-65 % of the window height."""
    band = int(0.2 * s)
    eyes = rect_sum(ii, x, y + int(0.25 * s), s, band)
    cheeks = rect_sum(ii, x, y + int(0.45 * s), s, band)
    return (cheeks - eyes) / (s * band)

face_value = eye_cheek(ii, x, y, w)
rng = np.random.default_rng(0)
others = np.array([eye_cheek(ii, int(rng.integers(0, 512 - w)), int(rng.integers(0, 512 - w)), w) for _ in range(500)])
print(f"feature on the face: {face_value:.1f} grey levels")
print(f"random windows: mean {others.mean():.1f}, share above the face value {np.mean(others > face_value):.3f}")
integral image shape: (513, 513) | equals cv2.integral: True
sum over the face box: slicing 1404099 | 4 lookups 1404099
feature on the face: 30.4 grey levels
random windows: mean -2.2, share above the face value 0.078

The table matches OpenCV, and the four-lookup sum equals the 9,025-pixel slice sum exactly. The feature behaves as the picture suggests: on the face the cheek band is 30.4 grey levels brighter than the eye band, while random windows average about −2-2. But 7.8 % of the 500 random windows score even higher than the face. One feature is a weak classifier: better than chance, far from good enough. Detection needs many features combined, and that is the job of boosting.

AdaBoost and the cascade

Which few of the 160,000 features matter, and how should they be combined? Viola and Jones used AdaBoost with one-feature "decision stumps" as weak classifiers: hj(x)=1h_j(\mathbf{x}) = 1 if pjfj(x)<pjθjp_j f_j(\mathbf{x}) < p_j \theta_j, else 0, where fjf_j is the feature value, θj\theta_j a threshold and pj=±1p_j = \pm 1 the direction. Each boosting round picks the stump with the lowest weighted error εt\varepsilon_t on the training windows (thousands of aligned faces and many more non-faces), gives it the weight αt=ln⁡1−εtεt\alpha_t = \ln \frac{1 - \varepsilon_t}{\varepsilon_t}, and raises the weight of the windows it got wrong, so the next stump concentrates on them. The strong classifier is a weighted vote:

H(x)={1if ∑tαtht(x)≥τ0otherwiseH(\mathbf{x}) = \begin{cases} 1 & \text{if } \sum_t \alpha_t h_t(\mathbf{x}) \ge \tau \\ 0 & \text{otherwise} \end{cases}

The second trick is the cascade. Almost every window in a photo is not a face, so the detector does not need a 200-feature vote to reject a patch of sky. It chains stages of increasing size; each stage's threshold τ\tau is set low so that it passes almost every face (say a detection rate d=0.99d = 0.99) while rejecting about half the non-faces (f=0.5f = 0.5). A window is a face only if it passes all KK stages:

D=∏k=1Kdk≈0.9910≈0.904,F=∏k=1Kfk≈0.510≈0.001D = \prod_{k=1}^{K} d_k \approx 0.99^{10} \approx 0.904, \qquad F = \prod_{k=1}^{K} f_k \approx 0.5^{10} \approx 0.001
feature counts per stage are illustrative; OpenCV's frontal cascade has 25 stages all windowsx, y, scale stage 12 features stage 210 features ... stage K200 features face rejected: not a face (most leave at stage 1 or 2)

So a 10-stage cascade keeps about 90 % of the faces and lets through about one non-face window in a thousand, and because half the windows leave at each stage, the average window costs only a handful of features. The trained cascades in OpenCV are XML files of these stages; training your own (opencv_traincascade) needs thousands of positives and hours, and is rarely worth it today. Boosting itself is covered in the Machine Learning course.

Running OpenCV's cascade

detectMultiScale slides the window over an image pyramid: it shrinks the image by scaleFactor again and again (or, equivalently, grows the window), runs the cascade at every position, and then groups overlapping hits: a real face fires at many neighbouring positions and scales, a false alarm usually at few. minNeighbors is the number of neighbouring raw hits a group needs to be reported. The face cascade on the astronaut, and the eye cascade run only inside the face box:

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

gray = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2GRAY)
face_cc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")

print("scaleFactor sweep (minNeighbors=5):")
for sf in [1.05, 1.1, 1.2, 1.3, 1.5]:
    n_scales = int(np.floor(np.log(512 / 24) / np.log(sf))) + 1
    faces = face_cc.detectMultiScale(gray, scaleFactor=sf, minNeighbors=5)
    print(f"  {sf:4.2f}: {n_scales:2d} pyramid levels, boxes {[list(map(int, f)) for f in faces]}")

print("minNeighbors sweep (scaleFactor=1.1):")
for mn in [0, 1, 3, 5, 10, 20]:
    faces = face_cc.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=mn)
    print(f"  {mn:2d}: {len(faces)} boxes")

x, y, w, h = face_cc.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)[0]
roi = gray[y:y + h, x:x + w]
eyes = eye_cc.detectMultiScale(roi, scaleFactor=1.1, minNeighbors=5)
print("eyes inside the face box (image coordinates):", sorted([[int(x + ex), int(y + ey), int(ew), int(eh)] for ex, ey, ew, eh in eyes]))
scaleFactor sweep (minNeighbors=5):
  1.05: 63 pyramid levels, boxes [[175, 66, 97, 97], [284, 125, 127, 127]]
  1.10: 33 pyramid levels, boxes [[177, 66, 95, 95]]
  1.20: 17 pyramid levels, boxes [[177, 66, 95, 95]]
  1.30: 12 pyramid levels, boxes [[176, 66, 95, 95]]
  1.50:  8 pyramid levels, boxes []
minNeighbors sweep (scaleFactor=1.1):
   0: 47 boxes
   1: 3 boxes
   3: 1 boxes
   5: 1 boxes
  10: 1 boxes
  20: 1 boxes
eyes inside the face box (image coordinates): [[187, 86, 29, 29], [232, 89, 29, 29]]

One face, box [177, 66, 95, 95] as (x, y, w, h), and two eyes inside it. The sweeps show the two dials. A smaller scaleFactor tests more pyramid levels (63 at 1.05, 8 at 1.5), which costs time and here also adds a false positive at [284, 125, 127, 127]; at 1.5 the steps are so coarse that no level fits the face well enough and it is lost. minNeighbors=0 returns all 47 raw hits before grouping (nearly all of them the same face at shifted positions and scales); one neighbour already merges them into 3 groups, and from 3 on only the face survives. On a crowded or noisy image the same dial trades missed faces against false alarms, which is why it is tuned on labelled data.

Where the cascade fails

The frontal cascade was trained on upright, frontal, evenly lit faces, and it knows nothing else. Two quick stress tests on the same image: rotate it about the face centre, and darken it (multiply by a factor, which also squeezes the contrast). Histogram equalisation (histograms and thresholding) is the classic fix for the second.

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

gray = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2GRAY)
face_cc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
FACE = (177, 66, 95, 95)
def hits(img):
    """(boxes overlapping the true face with IoU >= 0.3, other boxes)."""
    on = 0
    boxes = face_cc.detectMultiScale(img, scaleFactor=1.1, minNeighbors=5)
    for x, y, w, h in boxes:
        ix = max(0, min(x + w, FACE[0] + FACE[2]) - max(x, FACE[0]))
        iy = max(0, min(y + h, FACE[1] + FACE[3]) - max(y, FACE[1]))
        on += ix * iy / (w * h + FACE[2] * FACE[3] - ix * iy) >= 0.3
    return int(on), len(boxes) - int(on)

centre = (FACE[0] + FACE[2] / 2, FACE[1] + FACE[3] / 2)
print("rotation (degrees): (on the face, elsewhere)")
for angle in [0, 10, 20, 30, 45, 90]:
    M = cv2.getRotationMatrix2D(centre, angle, 1.0)      # turns the image about the face centre
    rot = cv2.warpAffine(gray, M, (512, 512), borderMode=cv2.BORDER_REPLICATE)
    print(f"  {angle:2d}: {hits(rot)}")

print("brightness factor: as is | after equalizeHist")
for k in [1.0, 0.5, 0.25, 0.1, 0.05]:
    dark = (gray * k).astype(np.uint8)
    print(f"  {k:4.2f} (max grey {int(dark.max()):3d}): {hits(dark)} | {hits(cv2.equalizeHist(dark))}")
rotation (degrees): (on the face, elsewhere)
   0: (1, 0)
  10: (1, 0)
  20: (1, 0)
  30: (0, 0)
  45: (0, 1)
  90: (0, 0)
brightness factor: as is | after equalizeHist
  1.00 (max grey 255): (1, 0) | (1, 0)
  0.50 (max grey 127): (1, 0) | (1, 0)
  0.25 (max grey  63): (1, 0) | (1, 0)
  0.10 (max grey  25): (0, 0) | (1, 0)
  0.05 (max grey  12): (0, 0) | (1, 0)

Each line counts boxes on the true face (IoU at least 0.3) and elsewhere. The face survives a tilt of 20 degrees and is lost at 30; at 45 degrees the cascade fires somewhere else, a false positive. For brightness the cascade copes down to a quarter (its features compare sums, so a uniform scale changes little until the 8-bit rounding destroys the contrast); at 0.1 and 0.05 (maximum grey 25 and 12) the face is gone, and histogram equalisation, which stretches those few grey levels back over 0 to 255, brings it back.

Other limits, which a test set of your own would show in the same way (project 4 builds one): profile faces (OpenCV has a separate haarcascade_profileface.xml), faces smaller than the 24-pixel window, occlusion by masks, hands or hair, and false positives on face-like texture. A cascade has no notion of context.

CNN face detectors

Modern face detectors are convolutional detectors of the kind taught in the detection section, trained on large face data sets such as WIDER FACE (32,203 images with 393,703 labelled faces of very varied scale, pose and occlusion):

Detector Year Idea Output
Viola-Jones (Haar cascade) 2001 boosted rectangle features, cascade boxes
HOG + linear SVM (dlib) 2005 / 2014 gradient histograms, sliding window boxes
MTCNN 2016 three small CNNs in a cascade (propose, refine, output) boxes + 5 landmarks
RetinaFace 2019 single-stage, FPN, multi-task head boxes + 5 landmarks
BlazeFace 2019 tiny SSD-style detector for phone GPUs boxes + 6 keypoints
YuNet (OpenCV FaceDetectorYN) 2021-2023 tiny anchor-free CNN, under 100k parameters boxes + 5 landmarks

They handle pose, scale and lighting far better, and the five landmarks they return are exactly what face alignment needs in the next lesson. None of their weights is available offline here, so this is how YuNet is called in OpenCV, shown but not run:

python
# Not run here: needs the YuNet ONNX model file (face_detection_yunet_2023mar.onnx, a download from the OpenCV model zoo)
import cv2
from skimage import data

img = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2BGR)
detector = cv2.FaceDetectorYN.create("face_detection_yunet_2023mar.onnx", "", (img.shape[1], img.shape[0]),
                                     score_threshold=0.8, nms_threshold=0.3)
_, faces = detector.detect(img)        # one row per face: x, y, w, h, 5 landmarks as (x, y) pairs, score
for f in faces if faces is not None else []:
    x, y, w, h = f[:4].astype(int)
    landmarks = f[4:14].reshape(5, 2)  # right eye, left eye, nose tip, right and left mouth corner
    print((x, y, w, h), f[14].round(3))

Anonymising: blur what you detect

A common, privacy-friendly use of face detection is the opposite of recognition: find every face and destroy it before the footage is stored or shared (street-level imagery, dash cams, published research video). Three rules make it work. Pad the box (detectors crop tightly, ears and hair identify too). Destroy the structure: a light blur or a fine mosaic can be partly undone or still recognised (the example below shows one); a coarse mosaic or a solid fill cannot. And prefer recall: a missed face is a privacy leak, a blurred patch of wall costs nothing, so run the detector at a low minNeighbors.

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2BGR)
face_cc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
def detect(bgr, mn=5):
    return face_cc.detectMultiScale(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY), scaleFactor=1.1, minNeighbors=mn)

def anonymise(bgr, boxes, pad=0.25, mode="blur"):
    out = bgr.copy()
    H, W = out.shape[:2]
    for x, y, w, h in boxes:
        x1, y1 = max(int(x - pad * w), 0), max(int(y - pad * h), 0)
        x2, y2 = min(int(x + w + pad * w), W), min(int(y + h + pad * h), H)
        roi = out[y1:y2, x1:x2]
        if mode == "blur":
            k = (max(x2 - x1, y2 - y1) // 2) | 1                  # odd kernel, half the box size
            out[y1:y2, x1:x2] = cv2.GaussianBlur(roi, (k, k), 0)
        elif mode == "fill":                                     # solid mean colour
            out[y1:y2, x1:x2] = roi.reshape(-1, 3).mean(axis=0).astype(np.uint8)
        else:                                                    # mosaic: 6 x 6 blocks
            small = cv2.resize(roi, (6, 6), interpolation=cv2.INTER_AREA)
            out[y1:y2, x1:x2] = cv2.resize(small, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST)
    return out

def near_face(boxes, face=(177, 66, 95, 95)):
    """Boxes whose centre lies inside the original face box."""
    return [list(map(int, b)) for b in boxes
            if face[0] <= b[0] + b[2] / 2 < face[0] + face[2] and face[1] <= b[1] + b[3] / 2 < face[1] + face[3]]

boxes = detect(img, mn=3)
print("faces found (minNeighbors=3):", [list(map(int, b)) for b in boxes])
print("boxes at minNeighbors=1 on the original: near the face", len(near_face(detect(img, mn=1))),
      "| total", len(detect(img, mn=1)))
for mode in ["blur", "mosaic", "fill"]:
    anon = anonymise(img, boxes, mode=mode)
    changed = int(np.any(anon != img, axis=2).sum())
    after = detect(anon, mn=1)
    print(f"{mode:6s}: {changed} pixels changed; at minNeighbors=1 afterwards: near the face {len(near_face(after))}, total {len(after)}")
faces found (minNeighbors=3): [[177, 66, 95, 95]]
boxes at minNeighbors=1 on the original: near the face 1 | total 3
blur  : 20160 pixels changed; at minNeighbors=1 afterwards: near the face 1, total 3
mosaic: 20160 pixels changed; at minNeighbors=1 afterwards: near the face 0, total 2
fill  : 20164 pixels changed; at minNeighbors=1 afterwards: near the face 0, total 2

The result is a lesson in itself. After the Gaussian blur, the cascade at minNeighbors=1 still finds a face at the same place: a blur keeps exactly the coarse light-dark layout (dark eye band, brighter cheeks) that Haar features measure. A mosaic of 6 x 6 blocks and a solid fill remove it; the two other boxes at minNeighbors=1 are the background false positives that the original image already had. A blurred face that a cascade still detects may also still be recognisable to a person who knows her, so use a mosaic coarse enough, a much larger kernel, or a fill.

Re-running a detector on its own output is a weak check (a face it cannot see is not necessarily a face nobody can recognise), but it catches the most common bug, blurring the wrong box. A real anonymiser is evaluated on a labelled test set by recall at the face level, measured separately for small, rotated and dark faces; project 4 does exactly that.

Pitfalls

  • Grey and colour order. Cascades need a grey image; cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) for scikit-image arrays, COLOR_BGR2GRAY for cv2.imread arrays. Mixing them changes the weights of the channels and the result.
  • minNeighbors and scaleFactor are a precision-recall dial. There is no correct value; pick it on a labelled validation set for your task (recall-first for blurring, precision-first for counting).
  • minSize. Faces smaller than the cascade's window (24 pixels for the default frontal model) are never found; upscale the image or use a CNN detector for crowds.
  • Rotation and pose. A frontal cascade misses tilted heads and profiles; running it on rotated copies of the image helps at a cost in time and false positives.
  • Evaluating on the training distribution. A detector that finds the astronaut proves nothing about night-time CCTV. Build a test set that matches deployment, with per-condition recall.
  • Demographic differences. Detectors trained on unbalanced data miss some groups more often; for an anonymiser that means unequal privacy protection. Report recall per group when you can label it lawfully.

Practice

  1. With the integral image II (zero row and column in front), write the sum of the pixels in rows 10 to 19 and columns 30 to 49 as four lookups.
Answer

The rectangle starts at x=30x = 30, y=10y = 10 with width 20 and height 10: S=I(50,20)−I(50,10)−I(30,20)+I(30,10)S = I(50, 20) - I(50, 10) - I(30, 20) + I(30, 10), in NumPy ii[20, 50] - ii[10, 50] - ii[20, 30] + ii[10, 30] (row index first).

  1. A cascade has 20 stages, each with detection rate 0.995 and false-positive rate 0.4. What are the overall detection and false-positive rates? How many false windows pass in an image scanned at 300,000 windows?
Answer

D=0.99520≈0.905D = 0.995^{20} \approx 0.905, F=0.420≈1.1×10−8F = 0.4^{20} \approx 1.1 \times 10^{-8}. Expected false windows: 300,000×1.1×10−8≈0.003300{,}000 \times 1.1 \times 10^{-8} \approx 0.003 per image, before grouping. In practice false positives are more frequent than this because stage errors are not independent.

  1. You blur faces in dash-cam video before uploading it. Would you choose minNeighbors=1 or minNeighbors=8, and how would you check the choice?
Answer

A low value such as 1: a missed face is a privacy failure, an extra blurred patch is harmless. Check it on a labelled sample of the real footage: face-level recall (overall and for small, dark and turned faces), and the false-positive rate only as a cost (how much of the image is blurred).

Test yourself

Why does the integral image make Haar-like features cheap?

  1. It stores the image at lower resolution
  2. Any rectangle sum becomes four lookups, whatever the rectangle's size
  3. It removes the need for a sliding window
  4. It converts the image to grey

What is the main purpose of the cascade structure in Viola-Jones?

  1. To recognise who the face belongs to
  2. To reject most non-face windows with a few cheap features, so the expensive stages run on few windows
  3. To make the detector rotation invariant
  4. To increase the number of features

In detectMultiScale, raising minNeighbors from 1 to 10 usually ...

  1. finds more faces
  2. reports fewer boxes: fewer false positives, but small or unusual faces may be lost
  3. changes the pyramid scale steps
  4. makes the detector work on profiles

An anonymiser should be tuned mainly for ...

  1. precision, so no wall is blurred
  2. recall, because a missed face is a privacy leak while an extra blur costs little
  3. the highest frame rate
  4. the tightest boxes