Detecting Faces in Images
Using OpenCV's Haar cascade to detect all faces in a still image.
10 min•By Priygop Team•Updated 2026
Face Detection in Images
Face Detection in Images
import cv2
def detect_faces_in_image(image_path, output_path="faces_detected.jpg"):
"""Detect all faces in an image and draw bounding boxes."""
# Load cascade and image
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces
# scaleFactor: how much the image size is reduced at each scale
# minNeighbors: how many neighbours each rectangle should retain
# minSize: minimum face size to detect
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1, # Try 1.05 for more sensitive detection
minNeighbors=5, # Higher = fewer false positives
minSize=(30, 30), # Minimum face size in pixels
flags=cv2.CASCADE_SCALE_IMAGE
)
print(f"Detected {len(faces)} face(s) in '{image_path}'")
result = image.copy()
for i, (x, y, w, h) in enumerate(faces):
# Draw rectangle around each face
cv2.rectangle(result, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Add label
label = f"Face {i+1}"
cv2.putText(result, label, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# Print details
print(f" Face {i+1}: position=({x},{y}), size={w}x{h}px")
cv2.imwrite(output_path, result)
print(f"Result saved: {output_path}")
return faces
detect_faces_in_image("group_photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment