Smart Traffic Management System – Code Explanation
Introduction
This project is a Smart Traffic Management System built using Python, Flask, OpenCV, SQLAlchemy, and multithreading.
The system processes video feeds from multiple cameras, detects vehicle density, dynamically controls traffic signals, and logs traffic data into a database.
Project Flow
-
Video Input – Multiple cameras (or video files) provide live feeds.
-
Processing – Each frame is analyzed using OpenCV to count vehicles.
-
Signal Logic – Based on vehicle density, traffic lights are dynamically switched.
-
Database Logging – Vehicle counts are stored every minute in SQLite.
-
Web Dashboard – Flask renders live video, API endpoints, and a dashboard for monitoring.
Code Explanation
1. Importing Libraries
-
OpenCV (cv2) – Video frame processing.
-
Flask – Web server and API routes.
-
SQLAlchemy – Database ORM for storing traffic logs.
-
Threading – For handling video capture and logging simultaneously.
2. Flask + Database Setup
-
SQLite database is used to store traffic logs.
-
A VehicleLog model records lane number, vehicle count, and timestamp.
3. Camera Configuration
camera_sources = {
0: 'video1.mp4',
1: 'video2.mp4',
2: 'video3.mp4',
3: 'video4.mp4'
}
caps = {k: cv2.VideoCapture(v) for k, v in camera_sources.items()}
-
Multiple video sources are mapped (lanes).
-
Each lane is processed separately.
4. Vehicle Detection
-
Each frame is converted to grayscale, blurred, and thresholded.
-
Contours are detected to approximate vehicles.
-
Counts are filtered by size and aspect ratio.
5. Traffic Signal Control
-
Signals alternate between two groups of lanes:
-
Group 1 → Lanes 1 & 2
-
Group 2 → Lanes 3 & 4
-
-
The active group is set to GREEN, the other to RED.
-
Adaptive timing: if traffic density difference > 1.25%, extra green time is added.
6. Drawing Traffic Lights on Frames
-
Each frame shows a visual traffic light (red, yellow, green).
7. Logging Vehicle Data
-
Every minute, vehicle counts per lane are stored in the database.
8. Video Streaming
-
Streams real-time lane feeds to the browser.
9. API Endpoints
-
/api/signals → Returns signal status, remaining time, and vehicle counts.
-
/api/logs → Returns last 100 logs from the database.
-
/api/stats → Provides system-level statistics (total intersections, efficiency, avg wait time).
10. Dashboard
-
Renders a dashboard with traffic history logs.
Conclusion
This system integrates computer vision, real-time processing, adaptive signal control, database logging, and web APIs. It is scalable for multiple intersections and can be enhanced with advanced ML models like YOLO or DeepSORT for precise vehicle detection.
Comments
Post a Comment