Real-time vehicle detection + LSTM-based flow prediction that dynamically replaces fixed-timer signals with demand-driven green-time allocation.
Every city intersection you've waited at almost certainly uses a fixed-cycle timer β a preset schedule that rotates green phases regardless of how many vehicles are actually present.
Fixed Timer Reality:
North: 30s green β 2 cars pass (28s wasted)
South: 30s green β empty lane (30s wasted)
East: 30s green β 18 cars queue up (still only 8 cleared)
West: 30s green β 3 cars pass (27s wasted)
This causes three compounding problems:
| Problem | Impact |
|---|---|
| Wasted green time | Busy lanes starved while quiet ones are over-served |
| Queue snowballing | Uncleared vehicles from cycle N make cycle N+1 worse |
| No look-ahead | Timer can't anticipate the rush-hour surge 5 minutes away |
Studies consistently show that 20β50 % of urban intersection delay is attributable to static timing plans that haven't been updated in years. At directionally imbalanced intersections β where morning traffic floods northbound and evening traffic floods southbound β the mismatch is even worse.
This system replaces the timer with a closed-loop AI pipeline:
- Sense β YOLOv8 counts vehicles per lane from a live camera feed
- Predict β a 2-layer LSTM forecasts demand for the next 5 intervals
- Adapt β the signal controller allocates green time proportional to current queue + predicted demand, every cycle
Camera / Video File
β
βΌ
YOLOv8 Detector β filters COCO classes 2,3,5,7 (car/moto/bus/truck)
β per-lane vehicle count
βΌ
Traffic State Buffer β sliding window of last 10 time-steps
β
βΌ
LSTM Predictor β 2-layer LSTM β Dropout(0.2) β Linear
β predicted count next 5 steps
βΌ
Signal Controller β green_t = base + queue + Ξ±Β·prediction
β phase durations
βΌ
Simulation Display β Pygame top-down intersection + live panel
| File | Role |
|---|---|
detector.py |
YOLOv8 wrapper β ROI-filtered per-lane counts |
lstm_predictor.py |
TrafficLSTM model + TrafficPredictor inference wrapper |
signal_controller.py |
4-phase adaptive controller with emergency override |
simulation.py |
Pygame real-time intersection visualiser |
data_generator.py |
Synthetic rush-hour CSV generator |
train.py |
LSTM training loop β MSE, Adam, early stopping |
main.py |
Orchestration entry point (--simulate / --source) |
utils/roi_selector.py |
Interactive OpenCV lane-box drawing tool |
utils/metrics.py |
Cycle efficiency, avg wait, throughput logger |
| Layer | Technology |
|---|---|
| Language | Python 3.10+ |
| Object Detection | YOLOv8 (ultralytics) |
| Deep Learning | PyTorch 2.x + LSTM |
| Video Processing | OpenCV |
| Simulation UI | Pygame |
| Data | NumPy, Pandas |
| Config | YAML |
Input β LSTM(64, layers=2) β Dropout(0.2) β Linear(input_size Γ pred_steps)
β
reshape to (batch, 5, 4)
β
5 future vehicle counts
per lane (N / S / E / W)
- Window size: 10 time-steps (5 minutes of history at 30 s intervals)
- Loss: MSE
- Optimizer: Adam (lr = 0.001)
- Early stopping: patience = 10 epochs
green_time = clip(
base_green + current_queue + Ξ± Γ predicted_demand,
min = 10 s,
max = 90 s
)
Where Ξ± = 0.4 (prediction weight from config.yaml).
Each cycle the controller proportionally redistributes the total green budget (100 s) across all four phases. Lanes with zero vehicles are skipped entirely.
The LSTM trained to a validation MSE of 0.00405 β early stopping at epoch 45.
Simulation scenario: 24-hour directional intersection.
Morning rush (07β09): heavy N & E traffic.
Evening rush (17β19): heavy S & W traffic.
Fixed timer allocates equal 25 s per phase regardless of lane demand.
| Panel | Key Insight |
|---|---|
| Vehicles Queued (24 h) | Fixed queue balloons to 8,500 vehicles by evening rush; adaptive holds at 3,000 |
| Vehicles Cleared / Interval | Adaptive clears ~25 % more vehicles per cycle throughout the day |
| Key Metrics bar | Avg queue: 4,780 β 1,293 vehicles (β73 %); rush queue: 5,514 β 1,660 (β70 %) |
| LSTM Accuracy (Lane N) | Predicted vs actual vehicle count; MAE β 1.3 veh/step |
| MAE by Lane | All lanes within 1.3β1.7 vehicles β accurate enough to improve allocation |
| Predicted vs Actual scatter | Points hug the perfect-prediction diagonal across all four lanes |
| Lane Volume (24 h) | Clear directional surges β the exact imbalance fixed timers ignore |
| Wait Reduction % | 70β80 % reduction during both peak windows |
| Scorecard | Quantified summary of all metrics |
Avg queue depth 4780 veh β 1293 veh (β72.9 %)
Rush-hour queue 5514 veh β 1660 veh (β69.9 %)
Peak queue 8594 veh β 3049 veh (β64.5 %)
Throughput gain +24.9 %
LSTM prediction MAE 1.10 veh / step
During rush hour, lane N arrives 42 vehicles per cycle.
Fixed gives N just 25 s β 11 vehicles cleared β a deficit of 31 per cycle.
Adaptive recognises S & W are quiet, gives them minimum 10 s each, and redirects the saved 30 s to N β 24 vehicles cleared β cutting the per-cycle deficit by 50 %.
Fixed Timer: Adaptive Signal:
N: 25s (11 clear) N: 70s (32 clear) β busiest lane prioritised
S: 25s ( 4 clear) S: 10s ( 4 clear) β minimum slice for quiet lane
E: 25s (11 clear) E: 12s (17 clear) β proportional to demand
W: 25s ( 3 clear) W: 8s ( 3 clear) β minimum slice
βββββββββββββββββββ
Total: 29 veh Total: 56 veh (93 % more per cycle)
python -m venv venv
# Windows
venv\Scripts\activate
# Linux / macOS
source venv/bin/activatepip install -r requirements.txtpython data_generator.py --days 30Produces data/synthetic_traffic.csv β 86,400 rows of simulated 24-hour rush-hour patterns.
python train.py --epochs 100 --patience 10 --batch 256Saves models/traffic_lstm.pth and plots models/training_curve.png.
# Simulation-only mode (no camera required)
python main.py --simulate
# With a video file + detection overlay
python main.py --source data/sample_video.mp4 --show-feed
# Webcam
python main.py --source 0
# Loop a short test clip
python main.py --source data/sample_video.mp4 --loop --show-feedpython utils/roi_selector.py data/sample_video.mp4 data/rois.jsonDraws bounding boxes interactively on a paused frame. ROIs are loaded automatically by main.py.
python results_graphs.py
python make_flowchart.pytraffic_ai/
βββ main.py # Entry point
βββ config.yaml # All tuneable parameters
βββ requirements.txt
βββ detector.py # YOLOv8 vehicle detector
βββ lstm_predictor.py # LSTM model + inference
βββ signal_controller.py # Adaptive 4-phase controller
βββ simulation.py # Pygame intersection display
βββ data_generator.py # Synthetic traffic CSV
βββ train.py # LSTM training script
βββ results_graphs.py # Performance comparison charts
βββ make_flowchart.py # Architecture diagram
βββ models/
β βββ traffic_lstm.pth # Trained weights
β βββ training_curve.png
βββ data/
β βββ synthetic_traffic.csv
β βββ metrics_log.csv # Runtime metrics
βββ results/
β βββ traffic_ai_results.png
β βββ architecture_flowchart.png
βββ utils/
βββ roi_selector.py # Interactive ROI tool
βββ metrics.py # Efficiency / wait metrics
detection:
model: yolov8n.pt # swap for custom-trained weights
confidence: 0.4
vehicle_classes: [2,3,5,7] # COCO: car, motorcycle, bus, truck
lstm:
window_size: 10 # history steps fed to LSTM
hidden_size: 64
num_layers: 2
prediction_steps: 5 # how many future steps to forecast
controller:
min_green: 10 # seconds
max_green: 90
base_green: 20
prediction_weight: 0.4 # alpha in the timing formula
emergency_threshold: 20 # vehicles β immediate green extension
simulation:
fps: 30
width: 900
height: 700
vehicle_speed: 3| Key / Action | Effect |
|---|---|
ESC |
Quit |
| Close window | Quit |
| Right-hand panel | Live lane counts, LSTM predictions, phase timer, metrics |
| Metric | Description |
|---|---|
| Queue depth | Vehicles currently waiting per phase |
| Throughput | Vehicles cleared per interval |
| Green utilisation | % of green time with vehicles present |
| Prediction MAE | LSTM mean absolute error vs actual counts |
| Cycle efficiency | Ratio of productive green time to total cycle |
All metrics are logged to data/metrics_log.csv at configurable intervals.
- Simulation uses synthetic traffic β performance figures reflect modelled demand, not a calibrated real-world intersection. Real deployment requires training on actual traffic counts.
- YOLOv8n is fast but light β for dense multi-lane scenarios,
yolov8mor a fine-tuned custom model would improve detection recall. - 4-phase only β the controller assumes a simple N/S/E/W split. Dual-turn phases, pedestrian crossings, and bus priority signals are not yet modelled.
- Single intersection β a production system would coordinate across a network of signals using shared predictions.
MIT


