Skip to main content

Software Sushi JournalComputer vision

Face Detection with OpenCV

Scan a still frame, tune the Haar cascade, and see which face candidates it keeps.

Two adults face the camera at different distances while a third adult sits in profile.
Test scene with two frontal faces and one in profile.

Scan a still frame

Compare recorded OpenCV detections as you change the scale factor and minimum neighbors.

Detection stage
Three adults at different distances, two facing forward and one in profile.
Generated test scene · 720 × 405 px

Closer to 1 checks more sizes.

Higher values require more support for a box.

Minimum size 24 × 24 px

2 boxes returned

Compare the returned rectangles with the image. Look for missed faces as well as extra boxes.

OpenCV’s frontal Haar cascade scans a grayscale image and returns rectangles around face candidates. Start with a still image so you can compare the boxes against the original as you change the settings.

Prepare a still image

Use OpenCV 4. Install it with python -m pip install "opencv-python>=4.13,<5" and place the sample image from the lab next to your script as sample.webp. Load it in BGR for drawing and create a grayscale copy for detection.

Load the image and the frontal cascade
Python
import cv2 as cv

image = cv.imread("sample.webp")
if image is None:
    raise FileNotFoundError("Could not open sample.webp")

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cascade = cv.CascadeClassifier(
    cv.data.haarcascades + "haarcascade_frontalface_default.xml"
)
if cascade.empty():
    raise RuntimeError("Could not load the frontal face cascade")

Tune the cascade

The cascade tests windows at different sizes and rejects many windows early. Adjust one parameter at a time and inspect both the extra boxes and the faces the detector misses.

Scale factor
Controls the spacing between image scales. Values closer to 1 test more sizes and can take longer.
Minimum neighbors
Controls how much support a rectangle needs from nearby detections. Raising it can remove weak boxes and also discard valid candidates.
Minimum size
Sets the smallest candidate size to consider. Lower it when the faces you need to find occupy fewer pixels.
Run detection with the lab settings
Python
faces = cascade.detectMultiScale(
    gray, scaleFactor=1.15, minNeighbors=6, minSize=(24, 24)
)

for x, y, width, height in faces:
    print(f"Face candidate at ({x}, {y}), {width} × {height} px")

For parameter details, see the OpenCV CascadeClassifier reference.

Draw and inspect the boxes

Each result contains a top-left position, width, and height in pixels. Draw the boxes on a copy of the color image. Compare that copy with the original to find missed faces and boxes on background objects.

In the lab, the default settings return two boxes on the frontal faces. Try scale factor 1.05 and minimum neighbors 2 to see four boxes, including one on the jacket. Use the image to check what each box actually covers.

Draw and save the result
Python
annotated = image.copy()
for x, y, width, height in faces:
    cv.rectangle(annotated, (x, y), (x + width, y + height), (120, 230, 120), 2)

if not cv.imwrite("face-detections.png", annotated):
    raise OSError("Could not save face-detections.png")

Search within a detected face

If you need eye candidates, run the eye cascade inside each face box. Its coordinates are relative to the crop, so add the face’s origin before drawing on the full image.

Draw eye candidates inside each face
Python
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_eye.xml")
if eye_cascade.empty():
    raise RuntimeError("Could not load the eye cascade")

height_px, width_px = gray.shape
for x, y, width, height in faces:
    left, top = max(x, 0), max(y, 0)
    crop = gray[top:min(y + height, height_px), left:min(x + width, width_px)]
    if crop.size == 0:
        continue
    for ex, ey, ew, eh in eye_cascade.detectMultiScale(crop, 1.1, 4):
        cv.rectangle(
            annotated, (left + ex, top + ey), (left + ex + ew, top + ey + eh),
            (255, 160, 40), 2
        )

Where to go next

Test on images with the pose, scale, lighting, and occlusion you expect in practice. Inspect misses on turned or partly covered faces, and compare with another detector if those examples matter to your application.

For preprocessing, see the OpenCV image manipulation guide and edge, shape, and feature detection. For another detection workflow, see object detection using YOLO.

For a detector that has to work on your own test images, our computer vision development services cover data, model comparison, evaluation, and deployment.