An AI-powered web application for detecting traffic violations in two-wheeler vehicles using computer vision, multiple Roboflow models, and OCR technology. Optimized for Railway deployment with Tesseract-only OCR.
- Features
- Live Demo
- Detection Capabilities
- System Architecture
- Installation
- Usage
- API Models
- Configuration
- Deployment
- Project Structure
- Technologies Used
- Troubleshooting
- Contributing
- License
- ๐ช No Helmet Detection: Identifies riders without helmets
- ๐ฅ Triple Riding Detection: Detects more than 2 passengers on a two-wheeler
- ๐ฆ Red Light Violation: Identifies vehicles crossing during red signals
- ๐ License Plate Recognition: Automated number plate extraction using Tesseract OCR
- โฑ๏ธ Violation Cooldown System: 5-second cooldown to prevent duplicate detections
- ๐ฏ Multi-Model AI: Uses 4 specialized Roboflow models simultaneously
- ๐ธ Evidence Collection: Automatically saves violation images with annotations
- ๐พ SQLite Database: Persistent storage of all violations
- ๐ Analytics Dashboard: Real-time violation statistics and summaries
- ๐ฅ Video & Image Support: Process both videos and images
- Modern Web Interface: Clean, responsive Bootstrap 5 design
- Real-time Processing: Live updates during video analysis
- Violation Gallery: Browse all captured violations
- Downloadable Results: Download processed videos and evidence
- Mobile-Friendly: Works on all devices
- Videos: MP4, AVI, MOV, MKV, WEBM
- Images: JPG, JPEG, PNG
- Max Size: 500MB
- Identifies riders without helmets
- Uses specialized helmet detection model
- Confidence threshold: 0.3
- Detects more than 2 passengers on two-wheeler
- Class: "people" (more than 2 passengers)
- Confidence threshold: 0.3
- Detects vehicles crossing during red signals
- Traffic light model with class "1" for red light
- Combines with bike detection for accurate violation
- Haar Cascade detection for plate localization
- Tesseract OCR for text extraction
- Multiple enhancement techniques for accuracy
- Automatic plate formatting
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Web Browser โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Flask Web Server โ
โ (Port: Railway/3000) โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโดโโโโโโโโโโโ
โผ โผ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ SQLite โ โ Processing โ
โ Database โ โ Engine โ
โโโโโโโโโโโโโโโโ โโโโโโโโฌโโโโโโโโ
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ Roboflow โ โ License โ โ Evidence โ
โ Models โ โ Plate โ โ Storage โ
โ (4 Models) โ โ Detection โ โ โ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
Frame Input
โ
โโโโบ Two-Wheeler Detection (two-wheeler-aj3hv/2)
โ
โโโโบ Rider/Helmet Detection (two-person-ride/11)
โ
โโโโบ Triple Riding Detection (more-than-two-passengers/1)
โ
โโโโบ Traffic Light Detection (traffic-lights-ydbwt/1)
โ
โผ
Violation Analysis
โ
โโโโบ License Plate Extraction
โ
โโโโบ Tesseract OCR
โ
โโโโบ Evidence Generation
โ
โผ
Save to Database
- Python: 3.10.13
- Tesseract OCR: 4.0+ (required)
- Roboflow API Key: Required for model inference
- Operating System: Windows, Linux, or macOS
git clone https://github.com/kumarvishal01971/Traffic_violation_detection.git
cd Traffic_violation_detection# Windows
python -m venv venv
venv\Scripts\activate
# Linux/macOS
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtWindows:
- Download installer: https://github.com/UB-Mannheim/tesseract/wiki
- Install to:
C:\Program Files\Tesseract-OCR\ - Add to system PATH
- Update path in
app.pyif needed:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'Linux (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install tesseract-ocrmacOS:
brew install tesseract- Sign up at Roboflow
- Get your API key from workspace settings
- Update in
app.py:
def __init__(self, api_key: str = "YOUR_API_KEY_HERE"):mkdir uploads outputs violation_evidenceDownload haarcascade_russian_plate_number.xml and place in root directory for better plate detection.
flask==2.3.3
werkzeug==2.3.7
opencv-python-headless==4.8.1.78
numpy==1.26.4
pillow==10.1.0
inference-sdk==0.9.0
gunicorn==21.2.0- opencv-python-headless: Lightweight version without GUI (Railway compatible)
- inference-sdk: Roboflow API client for model inference
- gunicorn: Production-grade WSGI server for deployment
- No PyTorch/EasyOCR: Keeps deployment lightweight and fast
python web_app.pyAccess at: http://localhost:3000
- Go to Upload page
- Select video (MP4, AVI, MOV) or image (JPG, PNG)
- Click Upload
- Processing starts automatically
- View results when complete
- Add
demo_video.mp4touploads/folder - Click Run Demo on homepage
- View processed results
- Click View Violations on homepage
- Browse all detected violations
- Click on evidence images to enlarge
- Filter by violation type
# Process video
python app.py --video path/to/video.mp4 --out output.mp4
# Process image
python app.py --image path/to/image.jpg --out output.jpgself.models = {
'two_wheeler': 'two-wheeler-aj3hv/2',
'riders': 'two-person-ride/11',
'triple_riding': 'more-than-two-passengers/1',
'traffic_light': 'traffic-lights-ydbwt/1'
}| Model | Purpose | Classes | Confidence |
|---|---|---|---|
| two-wheeler-aj3hv/2 | Bike detection | bike, motorcycle | 0.5 |
| two-person-ride/11 | Helmet detection | helmet, no_helmet | 0.5 |
| more-than-two-passengers/1 | Triple riding | people | 0.5 |
| traffic-lights-ydbwt/1 | Traffic lights | 0 (green), 1 (red) | 0.5 |
# NO HELMET: "no_helmet" class detected
# TRIPLE RIDING: "people" class (>2 passengers)
# RED LIGHT: class "1" (red) + bike detected# In process_video() method
frame_skip = 3 # Process every 3rd frame
# Higher = faster, may miss violations
# Lower = slower, more accurateself.confidence_thresholds = {
'bike': 0.3, # Bike detection
'no_helmet': 0.3, # No helmet detection
'triple': 0.3, # Triple riding
'light': 0.3 # Traffic light
}# In __init__()
self.tracker = SimpleViolationTracker(cooldown_seconds=5.0)
# Prevents duplicate violations within 5 seconds# In web_app.py
app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # 500MB- Create runtime.txt: txtpython-3.10.13
- Configure Render Service: Service Settings:
Runtime: Python 3 Build Command:
bash pip install -r requirements.txt
Start Command:
bash gunicorn flask_app:app 3. Set Environment Variables: In Render Dashboard โ Environment, add: bashPYTHON_VERSION=3.10.13 ROBOFLOW_API_KEY=your_roboflow_api_key PYTHONUNBUFFERED=1 4. Deploy: bash# Push to GitHub git add . git commit -m "Deploy to Render" git push origin main
**Important Notes:**
- โ
Remove any `Dockerfile`, `Procfile`, `nixpacks.toml`, or `railway.toml` files
- โ
Render automatically assigns PORT (usually 10000)
- โ
Free tier includes: 750 hours/month, automatic SSL, custom domains
---
### Heroku Deployment (Alternative)
#### 1. **Create `Procfile`:**
web: gunicorn flask_app:app --timeout 120 2. Create runtime.txt: txtpython-3.10.13 3. Add Buildpack (if using Tesseract): bashheroku buildpacks:add --index 1 heroku/python 4. Set Environment Variables: bashheroku config:set ROBOFLOW_API_KEY=your_api_key heroku config:set PYTHONUNBUFFERED=1 5. Deploy: bashheroku login heroku create your-app-name git push heroku main
Docker Deployment Dockerfile: dockerfileFROM python:3.10-slim
RUN apt-get update && apt-get install -y
libglib2.0-0
libsm6
libxext6
libxrender-dev
libgomp1
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV PORT=10000 ENV PYTHONUNBUFFERED=1
EXPOSE 10000
CMD ["gunicorn", "flask_app:app", "--bind", "0.0.0.0:10000", "--workers", "2", "--timeout", "120"] Build and Run: bash# Build the image docker build -t traffic-violation-detection .
docker run -p 10000:10000
-e ROBOFLOW_API_KEY=your_api_key
traffic-violation-detection
Docker Compose (Optional):
yamlversion: '3.8'
services: web: build: . ports: - "10000:10000" environment: - ROBOFLOW_API_KEY=${ROBOFLOW_API_KEY} - PYTHONUNBUFFERED=1 volumes: - ./uploads:/app/uploads - ./outputs:/app/outputs - ./violation_evidence:/app/violation_evidence Run with Docker Compose: bashdocker-compose up --build
traffic-violation-detection/
โ
โโโ app.py # Core detection engine
โโโ flask_app.py # Flask web application
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
โ
โโโ templates/ # HTML templates
โ โโโ base.html # Base template
โ โโโ index.html # Homepage
โ โโโ upload.html # Upload page
โ โโโ result.html # Results page
โ โโโ violations.html # Violations gallery
โ โโโ demo.html # Demo page
โ
โโโ uploads/ # Uploaded files
โโโ outputs/ # Processed videos
โโโ violation_evidence/ # Evidence images
โ
โโโ violations.db # SQLite database
โ
โโโ railway.toml # Railway config (deployment)
โโโ nixpacks.toml # Nixpacks config (deployment)
โโโ Procfile # Heroku config (deployment)
- Flask 2.3.3 - Web framework
- OpenCV 4.8.1 - Computer vision (headless for deployment)
- NumPy 1.26.4 - Numerical computations
- Pillow 10.1.0 - Image processing
- Gunicorn 21.2.0 - WSGI HTTP server
- Roboflow Inference SDK 0.9.0 - Model inference
- Tesseract OCR - License plate text extraction
- 4 Custom Models - Specialized detection models
- Bootstrap 5 - UI framework
- JavaScript - Interactive features
- HTML5/CSS3 - Markup and styling
- SQLite3 - Lightweight embedded database
- No external DB required - Portable and simple
- Railway - Primary deployment platform
- Gunicorn - Production WSGI server
- Nixpacks - Smart build system
Solution:
# Install Tesseract
# Ubuntu/Debian
sudo apt-get install tesseract-ocr
# Windows - download installer and add to PATH
# macOS
brew install tesseract
# Update path in app.py if needed
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'Solution:
pip install inference-sdk==0.9.0Possible causes:
- Invalid API key
- No internet connection
- Roboflow service down
Solution:
# Check API key in app.py
api_key = "YOUR_VALID_API_KEY"
# Test connection
from inference_sdk import InferenceHTTPClient
client = InferenceHTTPClient(
api_url="https://serverless.roboflow.com",
api_key="YOUR_API_KEY"
)Possible causes:
- Low confidence threshold
- Video quality issues
- Wrong model IDs
Solutions:
# Lower confidence thresholds
self.confidence_thresholds = {
'bike': 0.2, # Try 0.2 instead of 0.3
'no_helmet': 0.2,
'triple': 0.2,
'light': 0.2
}
# Check model predictions in console
print(f"Predictions: {all_predictions}")Solution:
# Close all other connections to violations.db
# Or delete and recreate database
rm violations.db
python web_app.py # Will recreate databaseSolutions:
# Increase frame skip
frame_skip = 5 # Instead of 3
# Reduce video resolution before upload
# Use smaller videos for testingCommon fixes:
# Ensure nixpacks.toml exists with tesseract
# Check logs: railway logs
# Verify environment variables are set
# Check buildpack orderCREATE TABLE violations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
plate_number TEXT,
violation_type TEXT,
confidence REAL,
details TEXT,
evidence_file TEXT,
video_source TEXT
)- Add model to
app.py:
self.models = {
# ... existing models
'new_violation': 'your-model-id/version'
}- Update detection logic:
def analyze_frame_simple(self, predictions, frame, frame_num):
# Add new detection logic
new_detections = [p for p in predictions if ...]
if new_detections:
violation = {
'type': 'NEW_VIOLATION_TYPE',
# ... rest of logic
}- Update UI in templates:
<!-- Add new violation type display -->Edit violation colors in app.py:
def save_evidence(self, frame, violation):
if v_type == 'NO_HELMET':
color = (0, 0, 255) # Red (BGR)
elif v_type == 'TRIPLE_RIDING':
color = (255, 0, 255) # Magenta
# Add your custom colorsContributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow PEP 8 style guide
- Add docstrings to functions
- Test with sample videos before committing
- Update README if adding features
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 Two-Wheeler Traffic Violation Detection
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Roboflow for the excellent model hosting and inference API
- Tesseract OCR for open-source text recognition
- OpenCV for computer vision capabilities
- Flask for the lightweight web framework
- Railway for seamless deployment platform
- Community contributors and testers
Project Maintainer: Kumar Vishal
- GitHub: @kumarvishal01971
- Repository: Traffic Violation Detection
- Real-time camera feed processing
- Multi-language OCR support
- Speed violation detection
- Email/SMS notifications
- Advanced analytics dashboard
- Mobile app integration
- Export reports to PDF
- Multi-camera support
- Cloud storage integration
- RESTful API for external integrations
- Processing Speed: ~15-20 seconds for 30-second video
- Detection Accuracy:
- No Helmet: ~85%
- Triple Riding: ~80%
- Red Light: ~90%
- Plate Recognition: ~75-80%
- Supported File Size: Up to 100MB
- Frame Skip: Every 3rd frame (configurable)
- API Response Time: ~500ms per frame
This project can be used for educational purposes. Please provide proper attribution.
If you find this project helpful, please โญ star the repository!
Made with โค๏ธ for Traffic Safety
Deploy Status: LIVE!!! Click here to view : https://traffic-violation-detection-ceo6.onrender.com/