A comprehensive Python program for detecting faces in images, video files, and live webcam streams using OpenCV. Supports both Haar Cascade and Deep Neural Network (DNN) detection methods.
- ✅ Multiple Input Sources: Images, video files, and live webcam
- ✅ Dual Detection Methods: Haar Cascade (fast) and DNN (accurate)
- ✅ Real-time Processing: Live webcam face detection
- ✅ Face Extraction: Save detected faces as separate images
- ✅ Quality Analysis: Analyze and filter faces by quality metrics
- ✅ Image Enhancement: Preprocessing for better detection
- ✅ Benchmarking: Compare performance of different methods
- ✅ Detection Logging: Track and analyze detection history
- ✅ Configurable: JSON-based configuration system
- Clone or download this repository
- Install dependencies:
pip install -r requirements.txt
- Python 3.7 or higher
- OpenCV 4.8.0 or higher
- NumPy 1.21.0 or higher
For enhanced features, you can install:
# For facial landmark detection
pip install dlib
# For visualization and analysis
pip install matplotlib pillow-
Detect faces in an image:
python face_detector.py --image path/to/your/image.jpg
-
Use webcam for real-time detection:
python face_detector.py --webcam
-
Process a video file:
python face_detector.py --video path/to/your/video.mp4
-
Use DNN method for higher accuracy:
python face_detector.py --method dnn --image path/to/image.jpg
-
Save detected faces as separate images:
python face_detector.py --image path/to/image.jpg --save-faces
-
Specify output directory:
python face_detector.py --image path/to/image.jpg --save-faces --output-dir my_detected_faces
- Pros: Fast, lightweight, good for real-time applications
- Cons: Less accurate, may have false positives
- Best for: Real-time webcam detection, resource-constrained environments
- Pros: Higher accuracy, better handling of various face orientations
- Cons: Slower, requires model files download
- Best for: High-accuracy applications, batch processing
Face Detection Project/
├── face_detector.py # Main detection program
├── face_utils.py # Utility functions and advanced features
├── example_usage.py # Example usage demonstrations
├── config.json # Configuration file
├── requirements.txt # Python dependencies
└── README.md # This file
Run the example script to see different capabilities:
python example_usage.pyThis will show you:
- Image face detection examples
- Webcam detection demo
- Enhanced detection with quality filtering
- Benchmarking different methods
- Detection statistics
Edit config.json to customize:
- Detection parameters (thresholds, sizes)
- Display settings (colors, thickness)
- Quality filtering options
- Image enhancement settings
- Output preferences
python face_detector.py [OPTIONS]
Options:
--method {haar,dnn} Detection method (default: haar)
--image PATH Path to input image
--video PATH Path to input video file
--webcam Use webcam for live detection
--save-faces Save detected faces as separate images
--output-dir DIR Directory for saved faces (default: detected_faces)
-h, --help Show help messagefrom face_detector import FaceDetector
# Initialize detector
detector = FaceDetector(method='haar')
# Process an image
detector.process_image('path/to/image.jpg')from face_detector import FaceDetector
from face_utils import enhance_image, analyze_face_quality
# Initialize with face saving enabled
detector = FaceDetector(method='dnn', save_faces=True, output_dir='faces')
# Enhance image before detection
import cv2
image = cv2.imread('path/to/image.jpg')
enhanced = enhance_image(image, 'clahe')
# Detect faces and analyze quality
faces = detector.detect_faces(enhanced)
for face in faces:
quality = analyze_face_quality(enhanced, face)
print(f"Face quality score: {quality['overall_score']:.1f}")import cv2
from face_detector import FaceDetector
detector = FaceDetector(method='haar')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = detector.detect_faces(frame)
# Draw bounding boxes
result = detector.draw_faces(frame, faces)
# Display
cv2.imshow('Face Detection', result)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()- For real-time applications: Use Haar Cascade method
- For better accuracy: Use DNN method
- For faster processing: Reduce input image size
- For better detection: Use image enhancement features
- For quality control: Enable quality filtering
-
"Could not load image"
- Check if the image path is correct
- Ensure the image format is supported (jpg, png, bmp, etc.)
-
"Error loading Haar Cascade classifier"
- OpenCV installation might be incomplete
- Try reinstalling OpenCV:
pip install --upgrade opencv-python
-
"Error loading DNN model"
- Model files will be downloaded automatically on first run
- Ensure internet connection for downloading model files
-
Webcam not working
- Check if camera is connected and not used by other applications
- Try different camera indices (0, 1, 2, etc.)
-
Poor detection results
- Try different detection methods (haar vs dnn)
- Use image enhancement features
- Adjust detection parameters in config.json
-
Slow detection
- Use Haar Cascade instead of DNN for speed
- Reduce image resolution
- Skip frames in video processing
-
High memory usage
- Process images in smaller batches
- Disable face saving if not needed
- Reduce maximum image size in config
The program can analyze face quality based on:
- Sharpness (focus quality)
- Brightness (lighting conditions)
- Contrast (image clarity)
- Face size (resolution)
- Overall quality score
Available enhancement methods:
- Histogram equalization
- CLAHE (Contrast Limited Adaptive Histogram Equalization)
- Gamma correction
All detections are logged with:
- Timestamp
- Image/video path
- Detection method used
- Number of faces found
- Bounding box coordinates
Compare performance between methods:
- Processing speed (FPS)
- Detection accuracy
- Face count comparison
Feel free to contribute by:
- Adding new detection methods
- Improving existing algorithms
- Adding new features
- Fixing bugs
- Improving documentation
This project is open source and available under the MIT License.
- OpenCV team for the computer vision library
- Contributors to the Haar Cascade and DNN models
- Python community for the ecosystem