#!/usr/bin/env python3
"""
Face Detection Script using OpenCV
==================================
This script detects faces in a given image using OpenCV's pre-trained Haar Cascade Classifier.
Requirements:
- Install OpenCV: `pip install opencv-python`
Usage:
python face_detect.py <input_image_path> [output_image_path]
Examples:
python face_detect.py input.jpg
python face_detect.py input.jpg output.jpg
Features:
- Detects frontal faces.
- Draws blue rectangles around detected faces.
- Displays the result and optionally saves it.
- Prints the number of faces detected.
"""
import sys
import cv2
import argparse
def detect_faces(image_path, output_path=None):
"""
Detect faces in the image and draw bounding boxes.
Args:
image_path (str): Path to the input image.
output_path (str, optional): Path to save the output image.
Returns:
bool: True if successful, False otherwise.
"""
# Load the pre-trained Haar Cascade classifier for frontal faces
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
if face_cascade.empty():
print("Error: Could not load the face cascade classifier.")
return False
# Read the input image
img = cv2.imread(image_path)
if img is None:
print(f"Error: Could not load image from '{image_path}'.")
return False
# Convert to grayscale for face detection
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces (scaleFactor=1.1, minNeighbors=4 are good defaults)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(30, 30))
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Optional: Add text label
cv2.putText(img, f'Face ({len(faces)})', (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
# Print detection results
if len(faces) > 0:
print(f"Found {len(faces)} face(s) in '{image_path}'.")
else:
print(f"No faces detected in '{image_path}'.")
# Display the result
cv2.imshow('Face Detection Result', img)
print("Press any key to close the window...")
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save the output if specified
if output_path:
success = cv2.imwrite(output_path, img)
if success:
print(f"Output saved to '{output_path}'.")
else:
print(f"Error: Could not save output to '{output_path}'.")
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Detect faces in an image using OpenCV.")
parser.add_argument("input", help="Path to the input image.")
parser.add_argument("output", nargs="?", help="Path to save the output image (optional).")
args = parser.parse_args()
success = detect_faces(args.input, args.output)
sys.exit(0 if success else 1)
How to Run:
Save the script as face_detect.py.
Run it with an image file:
code
python face_detect.py your_image.jpg
A window will pop up showing the image with blue rectangles around detected faces.
Performance: Works well on frontal faces. For profiles or varied angles, consider other cascades like haarcascade_frontalface_alt.xml or modern models (e.g., DNN-based detection).
Customization:
Adjust scaleFactor (lower = more detections, slower) or minNeighbors (higher = fewer false positives).
minSize=(30, 30) ignores very small faces.
Batch Processing: Modify the script to loop over multiple images if needed.
Webcam Support: For live detection, replace image loading with cap = cv2.VideoCapture(0) and a loop.
This script is efficient, well-commented, and handles errors gracefully! If you need enhancements (e.g., eye detection, video support), let me know.