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.
- 🚀 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
- 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
- Python 3.8 or higher
- pip (Python package manager)
cd ~/Downloads/face-detection-apipython3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activatepip install -r requirements.txtCopy the example environment file and configure as needed:
cp .env.example .envEdit .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=*Important: YOLOv8 base models are trained for general object detection. For face detection, you have three options:
Run the setup script to automatically download the model:
python setup_model.pyThis 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.
The model will be automatically downloaded when you first run the API. No manual setup needed:
python -m app.mainThe default model (yolov8n.pt) will be downloaded automatically on first use.
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.
python -m app.mainOr using uvicorn directly:
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reloaduvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4The API will be available at:
- API: http://localhost:8000
- Interactive Docs: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
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 facesbbox: Bounding box coordinates[x1, y1, x2, y2]confidence: Detection confidence score (0.0 to 1.0)width: Width of the detected face in pixelsheight: Height of the detected face in pixels
count: Total number of faces detectedprocessing_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));Endpoint: GET /api/v1/health
Description: Check if the API is running and healthy.
Response:
{
"status": "healthy",
"message": "Face Detection API is running"
}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"
}The API returns appropriate HTTP status codes:
200 OK- Successful detection400 Bad Request- Invalid image format, file too large, or validation error500 Internal Server Error- Server-side error during processing
Error Response Format:
{
"detail": "Error message describing what went wrong"
}| 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) |
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
# Install test dependencies
pip install pytest pytest-asyncio httpx
# Run tests
pytest# Install linting tools
pip install black flake8 mypy
# Format code
black app/
# Lint code
flake8 app/
# Type checking
mypy app/-
Model Selection: Use smaller models (yolov8n, yolov8s) for faster inference, larger models (yolov8m, yolov8l, yolov8x) for better accuracy.
-
Confidence Threshold: Adjust
CONFIDENCE_THRESHOLDto balance false positives and false negatives. -
Image Size: Larger images take more time to process. Consider resizing images before upload for faster processing.
-
GPU Acceleration: For better performance, use GPU-accelerated YOLOv8. Install PyTorch with CUDA support.
If you get an error about the model file not being found:
- Ensure the model file exists at the path specified in
MODEL_PATH - For first-time use, YOLOv8 will download the base model automatically
- For face detection, download a face-specific YOLOv8 model
If you encounter import errors:
- Ensure the virtual environment is activated
- Reinstall dependencies:
pip install -r requirements.txt - Check Python version:
python --version(should be 3.8+)
If you experience memory issues:
- Use a smaller YOLOv8 model (yolov8n instead of yolov8x)
- Reduce
MAX_IMAGE_SIZE_MBin.env - Process images in smaller batches
This project is open source and available for use.
Contributions are welcome! Please feel free to submit a Pull Request.
For issues and questions, please open an issue on the project repository.