Skip to content
OpenCV

Face Detection

Detect faces with a Haar cascade classifier.

By EZ4Code Team
facecascadedetection

Code

import cv2

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,
                                      minSize=(30, 30))
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
    roi_gray = gray[y:y + h, x:x + w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(img, (x + ex, y + ey), (x + ex + ew, y + ey + eh),
                      (0, 255, 0), 2)

cv2.imwrite("faces.jpg", img)
print(f"Found {len(faces)} faces")

Explanation

Haar cascades are XML classifiers bundled with OpenCV that detect objects using trained feature templates. detectMultiScale slides across the image at multiple scales, with scaleFactor controlling the step and minNeighbors filtering out spurious detections. Detected rectangles can be refined by running a second cascade inside each region.

More OpenCV Snippets