Face Detection with OpenCV: Data Preparation, Cascade Classifiers, and Python Implementation
This guide explains how to prepare Haar and LBP data, use OpenCV's CascadeClassifier and detectMultiScale functions, and run a complete Python script that captures video, detects faces, draws bounding boxes, displays results, and saves detected frames.
1. Data and Knowledge Preparation To perform accurate face detection you need pre‑trained classifiers. Download the Haar‑cascade and LBP‑cascade XML files from the OpenCV repository (https://github.com/opencv/opencv/tree/master/data) and store them locally for later use.
OpenCV related concepts
CascadeClassifier : OpenCV's class for face detection that can work with Haar or LBP features. The classifier is trained on large numbers of positive and negative samples using machine‑learning techniques.
detectMultiScale : The function that scans an image for faces. Important parameters include: - image : input image to process. - scaleFactor : how much the image size is reduced at each image scale. - minNeighbors : how many detections a candidate rectangle must have to be retained. - minSize and maxSize : minimum and maximum object size to be detected.
Haar‑like features : Rectangular features composed of adjacent black and white regions; the feature value is the difference between the sum of pixel intensities in the white and black rectangles. These features are sensitive to simple structures such as edges and lines, allowing the classifier to distinguish faces from non‑faces.
LBP (Local Binary Patterns) : A texture descriptor that compares each pixel with its surrounding neighbors in a 3×3 window, producing an 8‑bit binary code that is converted to a decimal LBP value. The extended version, LBPH, is supported by OpenCV and can be instantiated with cv2.face.LBPHFaceRecognizer_create() for face recognition tasks.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time : 2021/7/17 下午9:53
# @Author : huaan
import cv2 as cv
import time
cap = cv.VideoCapture(r'404.mp4')
# Tell OpenCV where the face‑detection cascade is located (use haarcascade_frontalface_alt2.xml placed in the same folder)
classfier = cv.CascadeClassifier(r'haarcascade_frontalface_alt2.xml')
# Bounding‑box color in BGR format (different from standard RGB)
color = (0, 255, 0)
while cap.isOpened():
ok, frame = cap.read() # read one frame
# if reading fails, exit loop
if not ok:
break
# convert frame to grayscale
grey = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# detect faces using detectMultiScale
faceRects = classfier.detectMultiScale(
grey,
scaleFactor=1.25,
minNeighbors=3,
minSize=(35, 35) # ignore objects smaller than this
# maxSize=(200,200) # optional maximum size
)
if len(faceRects) > 0: # when faces are detected
for faceRect in faceRects: # draw each face separately
x, y, w, h = faceRect
cv.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv.imshow("Face Detection", frame)
time.sleep(1)
# save each captured image
cv.imwrite('create_image/'+str(time.time())+'XXX.png', frame)
c = cv.waitKey(5) # smaller value = smoother playback, must be integer
if c & 0xFF == ord('q'):
break
# release resources
cap.release()
cv.destroyAllWindows()Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.