Real-time face detection that draws bounding boxes around faces — works on webcam video, images, and saved files. No deep learning or GPU needed.
Load an image, convert to greyscale, and run the Haar Cascade detector in three lines.
import cv2
# Load the pre-trained face detector (built into OpenCV)
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
img = cv2.imread('people.jpg')
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(grey, scaleFactor=1.1, minNeighbors=5, minSize=(30,30))
print(f"Detected {len(faces)} face(s)")
# Draw green rectangles
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite('faces_detected.jpg', img)
print("Saved to faces_detected.jpg")
Capture video frames, detect faces in each frame, and display the result in a window.
import cv2
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
cap = cv2.VideoCapture(0) # 0 = default webcam
print("Starting face detection — press Q to quit")
while True:
ret, frame = cap.read()
if not ret: break
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(grey, 1.1, 5, minSize=(30,30))
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame, 'Face', (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
cv2.putText(frame, f'{len(faces)} face(s)', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
cv2.imshow('Face Detection — press Q to quit', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Replace each face region with a Gaussian blur to anonymise people in photos.
import cv2
def blur_faces(image_path, output_path, blur_strength=31):
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
img = cv2.imread(image_path)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(grey, 1.1, 5, minSize=(30,30))
for (x, y, w, h) in faces:
face_region = img[y:y+h, x:x+w]
blurred = cv2.GaussianBlur(face_region, (blur_strength, blur_strength), 0)
img[y:y+h, x:x+w] = blurred
cv2.imwrite(output_path, img)
print(f"Blurred {len(faces)} face(s) — saved to {output_path}")
blur_faces('group_photo.jpg', 'group_photo_anonymised.jpg')
A three-step script that handles real-time video, static images, and privacy blurring. The Haar Cascade is a 2001 algorithm that still works well for frontal face detection. For better accuracy at angles, use cv2.dnn.readNetFromTensorflow() with a deep learning model.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.