pythonintermediate

OpenCV Face Detection with DNN

Detect faces in images using OpenCV's deep neural network face detector for accurate results.

python
import cv2
import numpy as np

def detect_faces(image_path: str, confidence_threshold: float = 0.5) -> list[dict]:
    net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000.caffemodel')
    img = cv2.imread(image_path)
    h, w = img.shape[:2]

    blob = cv2.dnn.blobFromImage(cv2.resize(img, (300,300)), 1.0, (300,300), (104,177,123))
    net.setInput(blob)
    detections = net.forward()

    faces = []
    for i in range(detections.shape[2]):
        conf = float(detections[0,0,i,2])
        if conf > confidence_threshold:
            box = (detections[0,0,i,3:7] * np.array([w,h,w,h])).astype(int)
            faces.append({'confidence': conf, 'bbox': box.tolist()})
    return faces

for face in detect_faces('photo.jpg'):
    print(f'Face: confidence={face["confidence"]:.2%}, bbox={face["bbox"]}')

Use Cases

  • face detection
  • video surveillance
  • photo tagging

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.