Skip to content

Face Detection Program – A Python tool using OpenCV to detect faces in images, videos, and live webcam streams. Supports Haar Cascade (fast) and DNN (accurate) methods, with features like real-time detection, face extraction, image enhancement, quality analysis, and benchmarking.

Notifications You must be signed in to change notification settings

Bhuvan-rdj/Face-Detection-Project-

Repository files navigation

Face Detection Program

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.

Features

  • 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

Installation

  1. Clone or download this repository
  2. Install dependencies:
    pip install -r requirements.txt

Requirements

  • Python 3.7 or higher
  • OpenCV 4.8.0 or higher
  • NumPy 1.21.0 or higher

Optional Dependencies

For enhanced features, you can install:

# For facial landmark detection
pip install dlib

# For visualization and analysis
pip install matplotlib pillow

Quick Start

Basic Usage

  1. Detect faces in an image:

    python face_detector.py --image path/to/your/image.jpg
  2. Use webcam for real-time detection:

    python face_detector.py --webcam
  3. Process a video file:

    python face_detector.py --video path/to/your/video.mp4

Advanced Usage

  1. Use DNN method for higher accuracy:

    python face_detector.py --method dnn --image path/to/image.jpg
  2. Save detected faces as separate images:

    python face_detector.py --image path/to/image.jpg --save-faces
  3. Specify output directory:

    python face_detector.py --image path/to/image.jpg --save-faces --output-dir my_detected_faces

Detection Methods

1. Haar Cascade (Default)

  • Pros: Fast, lightweight, good for real-time applications
  • Cons: Less accurate, may have false positives
  • Best for: Real-time webcam detection, resource-constrained environments

2. Deep Neural Network (DNN)

  • Pros: Higher accuracy, better handling of various face orientations
  • Cons: Slower, requires model files download
  • Best for: High-accuracy applications, batch processing

Program Structure

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

Examples and Demonstrations

Run the example script to see different capabilities:

python example_usage.py

This will show you:

  1. Image face detection examples
  2. Webcam detection demo
  3. Enhanced detection with quality filtering
  4. Benchmarking different methods
  5. Detection statistics

Configuration

Edit config.json to customize:

  • Detection parameters (thresholds, sizes)
  • Display settings (colors, thickness)
  • Quality filtering options
  • Image enhancement settings
  • Output preferences

Command Line Options

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 message

Usage Examples

Basic Image Detection

from face_detector import FaceDetector

# Initialize detector
detector = FaceDetector(method='haar')

# Process an image
detector.process_image('path/to/image.jpg')

Advanced Features

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}")

Real-time Webcam with Custom Processing

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()

Performance Tips

  1. For real-time applications: Use Haar Cascade method
  2. For better accuracy: Use DNN method
  3. For faster processing: Reduce input image size
  4. For better detection: Use image enhancement features
  5. For quality control: Enable quality filtering

Troubleshooting

Common Issues

  1. "Could not load image"

    • Check if the image path is correct
    • Ensure the image format is supported (jpg, png, bmp, etc.)
  2. "Error loading Haar Cascade classifier"

    • OpenCV installation might be incomplete
    • Try reinstalling OpenCV: pip install --upgrade opencv-python
  3. "Error loading DNN model"

    • Model files will be downloaded automatically on first run
    • Ensure internet connection for downloading model files
  4. Webcam not working

    • Check if camera is connected and not used by other applications
    • Try different camera indices (0, 1, 2, etc.)
  5. Poor detection results

    • Try different detection methods (haar vs dnn)
    • Use image enhancement features
    • Adjust detection parameters in config.json

Performance Issues

  1. Slow detection

    • Use Haar Cascade instead of DNN for speed
    • Reduce image resolution
    • Skip frames in video processing
  2. High memory usage

    • Process images in smaller batches
    • Disable face saving if not needed
    • Reduce maximum image size in config

Advanced Features

Quality Analysis

The program can analyze face quality based on:

  • Sharpness (focus quality)
  • Brightness (lighting conditions)
  • Contrast (image clarity)
  • Face size (resolution)
  • Overall quality score

Image Enhancement

Available enhancement methods:

  • Histogram equalization
  • CLAHE (Contrast Limited Adaptive Histogram Equalization)
  • Gamma correction

Detection Logging

All detections are logged with:

  • Timestamp
  • Image/video path
  • Detection method used
  • Number of faces found
  • Bounding box coordinates

Benchmarking

Compare performance between methods:

  • Processing speed (FPS)
  • Detection accuracy
  • Face count comparison

Contributing

Feel free to contribute by:

  1. Adding new detection methods
  2. Improving existing algorithms
  3. Adding new features
  4. Fixing bugs
  5. Improving documentation

License

This project is open source and available under the MIT License.

Acknowledgments

  • OpenCV team for the computer vision library
  • Contributors to the Haar Cascade and DNN models
  • Python community for the ecosystem

About

Face Detection Program – A Python tool using OpenCV to detect faces in images, videos, and live webcam streams. Supports Haar Cascade (fast) and DNN (accurate) methods, with features like real-time detection, face extraction, image enhancement, quality analysis, and benchmarking.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages