This guide uses two approaches: Haar Cascade (built-in, no extra install) and the DNN-based detector (more accurate, needs a model file). Start with Haar Cascade.
Method 1 — easiest
Haar Cascade face detection
Haar Cascades are built into OpenCV — no extra download needed. Good for simple use cases, fast on CPU.
import cv2
# Load the built-in face detector:
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
# Detect faces in an image:
img = cv2.imread('photo.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
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(f"Found {len(faces)} face(s)")
Live camera
Real-time face detection from webcam
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while True:
ret, frame = cap.read()
if not ret: break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('Face Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'): break
cap.release(); cv2.destroyAllWindows()
Method 2 — more accurate
DNN-based face detector
The DNN detector is more accurate, handles faces at different angles and works better in varying lighting. Requires downloading model files.
import cv2
import urllib.request
# Download model files (one-time):
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt",
"deploy.prototxt"
)
# Also download res10_300x300_ssd_iter_140000.caffemodel from the same repo
# Load the DNN model:
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000.caffemodel')
# Detect:
blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), (104,177,123))
net.setInput(blob)
detects = net.forward()
FAQ
Face detection questions
detectMultiScale detects too many false positives
Increase
minNeighbors (try 8-10) and minSize: detectMultiScale(gray, 1.1, 10, minSize=(50,50)). Higher minNeighbors reduces false positives but may miss some real faces.Face detection is slow on my laptop
Resize the frame before detection:
small = cv2.resize(frame, (0,0), fx=0.5, fy=0.5), detect on small, then scale bounding box coordinates back up by 2. This can give 3-4x speedup.How to do face recognition (not just detection)?
Face recognition requires
opencv-contrib-python for the cv2.face module (LBPH, Eigenfaces) or a deep learning approach. Install: pip install opencv-contrib-python. See Contrib modules guide.