Implement a Python script to detect faces in images using OpenCV.
- User
Implement a Python script to detect faces in images using OpenCV.
- Assistant
Providing face detection script
The user wants a Python script for detecting faces with OpenCV, but they didn't specify the detail level needed. I think I should aim for being concise yet still helpful. The focus should be on providing a complete sample script along with explanations, including any necessary instructions for installation.
It's essential to ensure that I only include face detection (not recognition) with methods like Haar cascades, and I should keep the code straightforward for clarity. I'll specify where to find the Haar cascades too.Structuring the face detection script
I'm planning out the answer structure for a face detection script using OpenCV. First, I'll include installation instructions:
pip install opencv-python.Next, I'll provide a basic script with clear functions for detecting faces from an image. I should also include error handling and guidance on parameters, explaining how
detectMultiScaleworks. While I could mention file folder usage, it doesn't seem necessary. I want to keep everything concise and focused strictly on detection, avoiding any references to identity or recognition. Here’s a complete, minimal example using OpenCV’s Haar cascade face detector.1. Install OpenCV
pip install opencv-python2. Save this script as
face_detect.pyimport sys import cv2 from pathlib import Path def detect_faces(image_path, output_path=None): # Load OpenCV's built‑in Haar cascade for frontal face detection cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml" face_cascade = cv2.CascadeClassifier(cascade_path) if face_cascade.empty(): raise IOError(f"Failed to load face cascade from {cascade_path}") # Read image img = cv2.imread(image_path) if img is None: raise IOError(f"Could not read image: {image_path}") # Convert to grayscale (Haar cascades work on grayscale) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale( gray, scaleFactor=1.1, # image pyramid scaling minNeighbors=5, # how many neighbors each rectangle should have minSize=(30, 30) # ignore faces smaller than this ) print(f"Found {len(faces)} face(s)") # Draw rectangles around faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # Save or display result if output_path: cv2.imwrite(output_path, img) print(f"Saved result to {output_path}") else: cv2.imshow("Detected Faces", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python face_detect.py input_image [output_image]") sys.exit(1) input_image = sys.argv[1] output_image = sys.argv[2] if len(sys.argv) > 2 else None detect_faces(input_image, output_image)3. Run the script
- To show the result in a window:
python face_detect.py input.jpg- To save the result with rectangles drawn:
python face_detect.py input.jpg output.jpgIf you want a version that processes all images in a folder or uses a different model (e.g., a DNN-based detector), say so and I’ll adapt the script.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.