Python Face Detection Tool
This guide demonstrates how to create a simple face detection utility using the OpenCV library (cv2). It uses pre-trained Haar Cascade classifiers to identify faces in static images or a live webcam feed.
Modules Used:
cv2(OpenCV): For image processing and computer vision tasks.- argparse: To handle command-line arguments.
Installation
You need to install the main OpenCV package for Python.
pip install opencv-python
The Code
Save this as face_detect.py.
import cv2
import argparse
import sys
def detect_faces(source):
# Load the pre-trained Haar Cascade classifier for face detection
# cv2.data.haarcascades points to the folder where OpenCV stores xml files
cascade_path = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(cascade_path)
if source == "webcam":
print("Starting webcam... Press 'q' to quit.")
cap = cv2.VideoCapture(0)
while True:
# Read frame-by-frame
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
process_frame(frame, face_cascade)
# Display the resulting frame
cv2.imshow('Face Detection', frame)
# Break loop on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
else:
# Image mode
print(f"Processing image: {source}")
img = cv2.imread(source)
if img is None:
print(f"Error: Could not read image '{source}'")
return
process_frame(img, face_cascade)
cv2.imshow('Face Detection', img)
print("Press any key to close the window.")
cv2.waitKey(0)
cv2.destroyAllWindows()
def process_frame(img, classifier):
# Convert to grayscale (Haar cascades work better on grayscale)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
# scaleFactor: Parameter specifying how much the image size is reduced at each image scale.
# minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it.
faces = classifier.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
return len(faces)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Face Detection Tool")
parser.add_argument("source", nargs="?", default="webcam", help="Path to image file (leave empty for webcam)")
args = parser.parse_args()
detect_faces(args.source)
Usage
# Use Webcam (Default)
python face_detect.py
# Detect faces in an image file
python face_detect.py group_photo.jpg