TrafficAI is an automated traffic monitoring system that uses Computer Vision (YOLOv8 + OpenCV) to detect traffic violations from CCTV footage. It identifies red-light runners, overspeeding vehicles, and lane violations, providing a dashboard for officers to review evidence.
- Vehicle Detection: Real-time detection of cars, trucks, motorcycles, and buses using specialized YOLOv8 models.
- Violation Monitoring:
- Red Light Violation: Detects vehicles crossing stop lines during red signals.
- Speeding Violation: Calculates vehicle speed (km/h) and flags violations > 60 km/h.
- Lane Discipline: Monitors improper lane changes (beta).
- Advanced ANPR: Hybrid Optical Character Recognition using PaddleOCR (primary) and EasyOCR (fallback) for high-accuracy license plate detection.
- Modern Dashboard:
- Real-time statistics and analytics.
- Detailed violation reports with video evidence playback.
- Advanced filtering (Date, Violation Type, License Plate).
- False positive management.
- Live Stream: Low-latency video processing feed with modern, responsive UI.
-
Backend: Python 3.10+, Flask 3.0
-
AI/ML: PyTorch, Ultralytics YOLOv8, OpenCV
-
OCR: PaddleOCR, EasyOCR
-
Database: SQLite (SQLAlchemy ORM) with Flask-Migrate for migrations
-
Frontend: HTML5, Tailwind CSS v4 (via PostCSS)
-
Testing: pytest
- Python 3.10 or higher
- Node.js v18+ (for frontend build)
- pnpm (recommended) or npm
- Git
- (Optional) CUDA-capable GPU for faster processing
- Python 3.10+: Download from python.org
- Visual C++ Build Tools (for PyTorch): Download from Microsoft C++ Build Tools
sudo apt-get update
sudo apt-get install python3.10 python3.10-venv git libgl1-mesa-glxbrew install python@3.10Get the project running in minutes using our automated setup scripts. These scripts handle everything:
- Creating a Python virtual environment.
- Installing backend dependencies.
- Installing frontend dependencies (Tailwind CSS v4).
- Building static assets.
git clone https://github.com/OdigweIfe/Live-Traffic-Detection-project.git
cd TrafficAI
.\setup.ps1
flask rungit clone https://github.com/OdigweIfe/Live-Traffic-Detection-project.git
cd TrafficAI
chmod +x setup.sh && ./setup.sh
source venv/bin/activate
flask runIf you prefer to set up manually:
git clone https://github.com/OdigweIfe/Live-Traffic-Detection-project.git
cd TrafficAI# Windows
python -m venv venv
.\venv\Scripts\activate
# Linux/Mac
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtNote: For GPU support with PyTorch, visit pytorch.org to install the CUDA version.
The project uses Tailwind CSS v4. You need to install dependencies and build the styles.
# Install dependencies (pnpm recommended)
pnpm install
# OR
npm install
# Build CSS
pnpm run build:css
# OR
npm run build:cssTo enable GPU acceleration (recommended for real-time processing), you must install the CUDA-enabled version of PyTorch. This supports both CPU and GPU modes.
-
Install PyTorch (CUDA 12.1):
# Uninstall default CPU version first pip uninstall torch torchvision torchaudio # Install GPU version pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
-
PaddleOCR GPU (Optional): For faster license plate recognition, you can install the GPU-optimized version of PaddlePaddle.
Note: Our automated setup scripts (
setup.ps1orsetup.sh) will automatically detect your NVIDIA GPU and offer to install this for you.To install manually:
pip uninstall paddlepaddle pip install paddlepaddle-gpu
(Note: Check paddlepaddle.org.cn for specific CUDA version commands if needed)
-
Switching Modes: You can switch between CPU and GPU instantly by editing your
.envfile:USE_GPU=true # Force GPU # OR USE_GPU=false # Force CPU # OR USE_GPU=auto # Auto-detect (Default)
The application requires the following model files:
-
YOLOv8n.pt (vehicle detection) - Download from Ultralytics YOLOv8
- Place in:
models/yolov8n.pt - The app will attempt to download automatically on first run
- Place in:
-
license_plate_detector.pt (license plate detection)
- Source: Hugging Face (Custom trained model)
- Status: Included locally in
models/directory. No download required if cloning full repo. - Path:
models/license_plate_detector.pt
cp .env.example .envEdit .env and configure:
SECRET_KEY: Change for productionPADDLE_OCR_ENABLED: Enable PaddleOCR (true/false)USE_GPU: Set to"true","false", or"auto"(default)
flask db init
flask db migrate -m "Initial migration"
flask db upgradeOr use the setup script:
# Windows
.\setup.ps1
# Linux/Mac
chmod +x setup.sh && ./setup.shTrafficAI uses SQLite for data persistence. The database file is located at:
instance/trafficai.db
| Table | Description |
|---|---|
violations |
Stores all violation records including metadata, video paths, and timestamps. |
Key Columns:
id: Primary Keyviolation_type: Red Light, Speeding, etc.license_plate: Detected textspeed_kmh: Speed in km/hvideo_path: Path to evidence videoframe_number: Frame index of violation
When making changes to models:
flask db migrate -m "Description of changes"
flask db upgrade# Backup
copy instance\trafficai.db backups\trafficai_backup.db
# Restore
copy backups\trafficai_backup.db instance\trafficai.db# Using Flask
flask run
# Using run.py
python run.pyThe application will be available at http://127.0.0.1:5000
Access the dashboard at: http://127.0.0.1:5000/dashboard
- Navigate to the uploads page
- Select CCTV footage for processing
- The system will analyze the video and detect violations
pytest
pytest -v # Verbose output
pytest --cov=app # With coverage report| Variable | Description | Default |
|---|---|---|
SECRET_KEY |
Flask secret key | dev-secret-key |
DATABASE_URI |
Database connection | sqlite:///instance/trafficai.db |
FLASK_APP |
Flask application entry | run.py |
FLASK_ENV |
Flask environment | development |
USE_GPU |
Processing device (true/false/auto) | auto |
MAX_CONTENT_LENGTH |
Max upload size (bytes) | 104857600 |
UPLOAD_FOLDER |
Upload directory | app/static/uploads |
SPEED_LIMIT |
Speed limit threshold in km/h | 60.0 |
PIXELS_PER_METER |
Camera calibration value (pixels covering 1 meter) | 40.0 |
Region of Interest (ROI) configuration files are located in:
config/roi/traffic_video_modified.jsonconfig/roi/highway_cam_01.jsonconfig/roi/intersection_cam_01.json
Error: OCR model not loaded properly
Solution:
- Ensure paddlepaddle and paddleocr are installed:
pip install paddlepaddle paddleocr - For CPU only:
pip install paddlepaddle==3.0.0 paddleocr - Check GPU availability with
nvidia-smi
RuntimeError: CUDA out of memory
Solution:
- Set
USE_GPU=falsein.env - Reduce video batch size
- Use a smaller YOLO model
alembic.util.exc.CommandError: Can't locate revision identified by 'xyz'
Solution:
flask db stamp head
flask db migrate
flask db upgradeFileNotFoundError: models/yolov8n.pt not found
Solution:
- The model will download automatically on first run
- Manual download:
wget https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt
OSError: [Errno 98] Address already in use
Solution:
# Find and kill the process
# Windows
netstat -ano | findstr :5000
taskkill /PID <PID> /F
# Linux/Mac
lsof -i :5000
kill -9 <PID>Solution:
pip uninstall torch torchvision
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu- Ensure you have run
pnpm installandpnpm run build:css. - Check
app/static/css/output.cssexists. - If getting
Cannot find module, deletenode_modulesand re-runpnpm install.
- Check the Issues page
- Review the docs directory
- Run with debug mode:
FLASK_ENV=development flask run
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
- Follow PEP 8 style guide
- Write docstrings for all functions
- Add type hints where applicable
- Write tests for new features
- Update documentation as needed
- Ensure all tests pass
- Update documentation if needed
- Your PR will be reviewed by maintainers
- Once approved, your PR will be merged
This project is licensed under the MIT License - see the LICENSE file for details.
- Ultralytics for YOLOv8
- OpenCV for computer vision
- PaddleOCR for text recognition
- EasyOCR for deep learning OCR
TrafficAI/
├── app/
│ ├── __init__.py # App factory: Initializes Flask, DB, and Blueprints
│ ├── models.py # Database models: Defines Violation schema
│ ├── routes/ # Flask blueprints
│ │ ├── admin.py # Admin routes for system management
│ │ ├── dashboard.py # Main dashboard view logic
│ │ ├── upload.py # Video upload handling
│ │ ├── violations.py # Violation details and playback
│ │ └── summary.py # Statistics aggregation
│ ├── ai/ # Core AI Detection Modules
│ │ ├── detector.py # Object Detection: Loads YOLOv8 to find vehicles
│ │ ├── anpr.py # ANPR: Optical Character Recognition (PaddleOCR)
│ │ ├── red_light.py # Logic: Checks if vehicle crossed stop line
│ │ ├── speed.py # Logic: Calculates pixel-to-meter speed
│ │ └── lane.py # Logic: Monitors lane boundary crossings
│ ├── static/ # Static assets
│ ├── templates/ # Jinja2 HTML templates
│ └── utils/ # Helper functions
├── config/
│ └── roi_config.py # Defines Stop Lines and Zones for cameras
├── models/ # AI Model Files
│ ├── yolov8n.pt # Vehicle detection model (auto-downloaded)
│ └── license_plate_detector.pt # Custom Plate Detection Model (Local/HuggingFace)
├── requirements.txt # Project dependencies
├── run.py # Application entry point
├── setup.ps1 # One-click setup script (Windows)
├── setup.sh # One-click setup script (Linux/Mac)
└── README.md # Project documentation