Detecting Multiple Faces
Detecting and tracking multiple faces simultaneously in group photos and crowded scenes.
8 min•By Priygop Team•Updated 2026
Multi-Face Detection with Analysis
Multi-Face Detection with Analysis
import cv2
import numpy as np
def analyse_group_photo(image_path):
"""Detect and analyse all faces in a group photo."""
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
eye_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_eye.xml"
)
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Equalise histogram for better detection in varied lighting
gray_eq = cv2.equalizeHist(gray)
faces = face_cascade.detectMultiScale(
gray_eq, scaleFactor=1.05, minNeighbors=4, minSize=(40, 40)
)
print(f"=== Group Photo Analysis ===")
print(f"Total faces detected: {len(faces)}")
result = image.copy()
face_data = []
for i, (fx, fy, fw, fh) in enumerate(faces):
cv2.rectangle(result, (fx, fy), (fx+fw, fy+fh), (0, 255, 0), 2)
cv2.putText(result, f"#{i+1}", (fx, fy-5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
# Detect eyes within each face region
face_roi_gray = gray_eq[fy:fy+fh, fx:fx+fw]
eyes = eye_cascade.detectMultiScale(face_roi_gray, scaleFactor=1.1, minNeighbors=5)
face_data.append({
"id": i + 1,
"position": (fx, fy),
"size": (fw, fh),
"area": fw * fh,
"eyes_detected": len(eyes),
})
# Draw eyes
for (ex, ey, ew, eh) in eyes:
cv2.circle(result, (fx+ex+ew//2, fy+ey+eh//2), ew//2, (255, 0, 0), 2)
# Sort by size (largest face first = likely closest person)
face_data.sort(key=lambda x: x["area"], reverse=True)
for face in face_data:
print(f" Face {face['id']}: size={face['size'][0]}x{face['size'][1]}, eyes={face['eyes_detected']}")
cv2.imwrite("group_analysis.jpg", result)
return face_data
analyse_group_photo("group.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment