Skip to content

dhruvac29/face-detection-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Real-Time Face Detection API

A production-ready RESTful API for real-time face detection using FastAPI and YOLOv8. This API accepts image uploads and returns detected faces with bounding boxes, confidence scores, and processing metrics.

Features

  • 🚀 Fast and efficient face detection using YOLOv8
  • 📸 Support for JPEG and PNG image formats
  • 📊 Detailed detection results with bounding boxes and confidence scores
  • 🔒 Input validation and error handling
  • 📖 Interactive API documentation (Swagger UI)
  • ⚡ High-performance async processing
  • 🎯 Configurable confidence thresholds

Technology Stack

  • FastAPI - Modern, fast web framework for building APIs
  • YOLOv8 - State-of-the-art object detection model
  • OpenCV - Image processing and computer vision
  • Uvicorn - ASGI server for FastAPI
  • Pydantic - Data validation using Python type annotations

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)

Installation

1. Clone or navigate to the project directory

cd ~/Downloads/face-detection-api

2. Create a virtual environment (recommended)

python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install dependencies

pip install -r requirements.txt

4. Set up environment variables (optional)

Copy the example environment file and configure as needed:

cp .env.example .env

Edit .env file with your configuration:

API_HOST=0.0.0.0
API_PORT=8000
API_RELOAD=true
MODEL_PATH=yolov8n.pt
CONFIDENCE_THRESHOLD=0.5
MAX_IMAGE_SIZE_MB=10
ALLOWED_ORIGINS=*

5. Download YOLOv8 Model

Important: YOLOv8 base models are trained for general object detection. For face detection, you have three options:

Option A: Use Setup Script (Recommended)

Run the setup script to automatically download the model:

python setup_model.py

This will download yolov8n.pt (nano model - fastest, ~6MB) by default. To download a different model:

# Download different model sizes
python setup_model.py --model yolov8s.pt  # Small (faster)
python setup_model.py --model yolov8m.pt  # Medium (balanced)
python setup_model.py --model yolov8l.pt  # Large (more accurate)
python setup_model.py --model yolov8x.pt  # Extra Large (most accurate)

The script will download the model and make it ready for use. Models are cached by Ultralytics, so subsequent runs are faster.

Option B: Automatic Download on First Run

The model will be automatically downloaded when you first run the API. No manual setup needed:

python -m app.main

The default model (yolov8n.pt) will be downloaded automatically on first use.

Option C: Use a Pre-trained Face Detection Model

For better face detection accuracy, download a YOLOv8 model trained specifically for face detection:

  • Roboflow Universe - Search for "face detection YOLOv8"
  • Kaggle - Search for YOLOv8 face detection models
  • Train your own model on a face detection dataset

Place the model file (.pt format) in the project root and update MODEL_PATH in .env.

Note: Base YOLOv8 models can detect some faces but are not optimized for face detection. For production use, consider using a face-specific model from Option C.

Running the API

Development Mode

python -m app.main

Or using uvicorn directly:

uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

Production Mode

uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

The API will be available at:

API Endpoints

1. Detect Faces

Endpoint: POST /api/v1/detect

Description: Upload an image and get face detection results.

Request:

  • Method: POST
  • Content-Type: multipart/form-data
  • Body: Image file (JPEG or PNG)

Response:

{
  "faces": [
    {
      "bbox": [100, 150, 250, 300],
      "confidence": 0.95,
      "width": 150.0,
      "height": 150.0
    }
  ],
  "count": 1,
  "processing_time": 0.125
}

Response Fields:

  • faces: Array of detected faces
    • bbox: Bounding box coordinates [x1, y1, x2, y2]
    • confidence: Detection confidence score (0.0 to 1.0)
    • width: Width of the detected face in pixels
    • height: Height of the detected face in pixels
  • count: Total number of faces detected
  • processing_time: Time taken for detection in seconds

Example using cURL:

curl -X POST "http://localhost:8000/api/v1/detect" \
  -H "accept: application/json" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@path/to/your/image.jpg"

Example using Python:

import requests

url = "http://localhost:8000/api/v1/detect"
files = {"file": open("path/to/image.jpg", "rb")}
response = requests.post(url, files=files)
print(response.json())

Example using JavaScript (fetch):

const formData = new FormData();
formData.append("file", fileInput.files[0]);

fetch("http://localhost:8000/api/v1/detect", {
  method: "POST",
  body: formData,
})
  .then((response) => response.json())
  .then((data) => console.log(data));

2. Health Check

Endpoint: GET /api/v1/health

Description: Check if the API is running and healthy.

Response:

{
  "status": "healthy",
  "message": "Face Detection API is running"
}

3. Root Endpoint

Endpoint: GET /

Description: Get API information and available endpoints.

Response:

{
  "message": "Real-Time Face Detection API",
  "version": "1.0.0",
  "docs": "/docs",
  "health": "/api/v1/health"
}

Error Handling

The API returns appropriate HTTP status codes:

  • 200 OK - Successful detection
  • 400 Bad Request - Invalid image format, file too large, or validation error
  • 500 Internal Server Error - Server-side error during processing

Error Response Format:

{
  "detail": "Error message describing what went wrong"
}

Configuration

Environment Variables

Variable Default Description
API_HOST 0.0.0.0 Host to bind the server
API_PORT 8000 Port to run the server
API_RELOAD true Enable auto-reload in development
MODEL_PATH yolov8n.pt Path to YOLOv8 model file
CONFIDENCE_THRESHOLD 0.5 Minimum confidence for detections (0.0-1.0)
MAX_IMAGE_SIZE_MB 10 Maximum image file size in MB
ALLOWED_ORIGINS * CORS allowed origins (comma-separated)

Project Structure

face-detection-api/
├── app/
│   ├── __init__.py
│   ├── main.py                 # FastAPI application entry point
│   ├── models/
│   │   ├── __init__.py
│   │   └── detection.py        # Pydantic models for request/response
│   ├── services/
│   │   ├── __init__.py
│   │   └── face_detector.py    # YOLOv8 face detection service
│   ├── utils/
│   │   ├── __init__.py
│   │   └── image_processor.py  # Image processing utilities
│   └── routes/
│       ├── __init__.py
│       └── detection.py        # API routes
├── requirements.txt            # Python dependencies
├── .env.example               # Environment variables template
├── .gitignore
└── README.md                  # This file

Development

Running Tests

# Install test dependencies
pip install pytest pytest-asyncio httpx

# Run tests
pytest

Code Quality

# Install linting tools
pip install black flake8 mypy

# Format code
black app/

# Lint code
flake8 app/

# Type checking
mypy app/

Performance Tips

  1. Model Selection: Use smaller models (yolov8n, yolov8s) for faster inference, larger models (yolov8m, yolov8l, yolov8x) for better accuracy.

  2. Confidence Threshold: Adjust CONFIDENCE_THRESHOLD to balance false positives and false negatives.

  3. Image Size: Larger images take more time to process. Consider resizing images before upload for faster processing.

  4. GPU Acceleration: For better performance, use GPU-accelerated YOLOv8. Install PyTorch with CUDA support.

Troubleshooting

Model Not Found Error

If you get an error about the model file not being found:

  1. Ensure the model file exists at the path specified in MODEL_PATH
  2. For first-time use, YOLOv8 will download the base model automatically
  3. For face detection, download a face-specific YOLOv8 model

Import Errors

If you encounter import errors:

  1. Ensure the virtual environment is activated
  2. Reinstall dependencies: pip install -r requirements.txt
  3. Check Python version: python --version (should be 3.8+)

Memory Issues

If you experience memory issues:

  1. Use a smaller YOLOv8 model (yolov8n instead of yolov8x)
  2. Reduce MAX_IMAGE_SIZE_MB in .env
  3. Process images in smaller batches

License

This project is open source and available for use.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions, please open an issue on the project repository.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages