Practical computer vision: Haar cascades, frames, and OpenCV
Exploring real-time detection and video manipulation with Python: integral images, multi-scale detection windows, frame rates, and time stretching.
On this page
There's a version of computer vision that requires a GPU, a large model, and a cloud inference budget. Then there's the version that runs in pure Python on a mid-range laptop and detects faces in a webcam feed at thirty frames per second.
The gap between those two things is bigger than it looks. The second approach doesn't use neural networks at all.
Face-Detector, Car-and-Pedestrian-Detector, and Slow-Mo all use OpenCV and Python. They're experiments in classical image processing — the approach that dominated before deep learning, and that still runs circles around neural networks when the hardware is limited.
How Haar cascades actually work
A Haar cascade is a chain of cheap tests applied to a window of pixels. Each test measures contrast between adjacent rectangular regions — is the area above the nose darker than the area below? Is there a horizontal edge where the eyebrows sit?
Edge features: Line features:
+----------+----------+ +----+----------+----+
| White | Black | | W | Black | W |
+----------+----------+ +----+----------+----+
| White | Black | | W | Black | W |
+----------+----------+ +----+----------+----+None of these individual tests are reliable on their own. The cascade runs hundreds of them, ordered so that the cheapest and most discriminating ones come first. If a window fails any early test, it's rejected immediately — the remaining tests don't run.
The result is that more than 90% of image regions are eliminated in the first two stages. The cascade spends almost all its time doing almost no work.
The integral image is what makes this fast
Evaluating contrast between two rectangles sounds straightforward until you realize you're doing it thousands of times per frame, at multiple image scales, for every possible position. The raw pixel arithmetic would stall a CPU.
The trick is an integral image: a precomputed lookup table where each cell stores the sum of all pixels above and to its left. That lets you compute the sum of any rectangle using exactly four lookups, regardless of the rectangle's size:
+--------+--------+
| A | B |
+--------+--------+
| C | D |
+--------+--------+
Sum of D = D - B - C + AIt costs one pass to build the table. After that, every feature evaluation is constant time. That's why the detection stays fast even though it's checking hundreds of features across thousands of windows per frame.
Running it in practice
The OpenCV implementation is around fifteen lines once you have the cascade XML:
import cv2
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
equalized = cv2.equalizeHist(gray)
faces = face_cascade.detectMultiScale(equalized, scaleFactor=1.1, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()The color information gets dropped early. Haar features depend on intensity gradients, not hue, so running detection on a grayscale image is functionally identical to BGR at a third of the cost.
Histogram equalization before detection matters more than it looks. It spreads pixel values across the full 0–255 range, so faces that would have been washed out under harsh backlighting or lost in deep shadow become detectable.
Tuning the detection
detectMultiScale has two parameters worth understanding:
scaleFactor controls how aggressively the image gets downsampled at each detection pass. 1.1 means the image is reduced by 10% per step, which catches faces across a wide range of sizes. 1.3 runs faster but can skip faces that fall between scale steps.
minNeighbors is how many candidate rectangles have to agree before a detection gets reported. 3 picks up more faces in poor lighting but also produces ghost detections on textured walls. 7 is strict enough to suppress most false positives but will drop detections during fast motion.
For Car-and-Pedestrian-Detector, pedestrians needed higher minNeighbors than cars. Human silhouettes on a street have far more ambiguous edges than the geometric grille of a car. The cascade sees both but needs more convincing for people.
Slow motion as a side project in the same library
Slow-Mo came out of a simple observation: a video file is just a sequence of still frames with a playback speed tag attached.
If you want 2x slow motion from a 30 FPS recording, the cheapest approach is to write each frame twice at the same 30 FPS. The file runs at the original speed, but each moment lasts twice as long.
cap = cv2.VideoCapture("input.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter("slow.mp4", cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
out.write(frame)
out.write(frame) # duplicate for 2x slowdown
cap.release()
out.release()The obvious problem is motion judder — duplicated frames have no information between them, so fast movement looks choppy rather than smooth. The proper solution uses optical flow to synthesize intermediate frames, but that's a meaningfully harder problem. For the original version, honest frame duplication was enough to make the effect obvious.
Browse Face-Detector, Car-and-Pedestrian-Detector, and Slow-Mo on GitHub.