Skip to content

A Python-based computer vision system that detects vehicles violating red traffic lights using video streams: the system monitors traffic signal status, identifies vehicles crossing during a red phase, and flags those as violations aimed at enhancing intersection safety and automated traffic monitoring.

License

Notifications You must be signed in to change notification settings

HassanRasheed91/Red-Light-Violation-Detection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿšฆ Red Light Violation Detection System

๐Ÿš— An intelligent transportation system that automatically detects and tracks vehicles violating red traffic lights using YOLOv12, ByteTrack, and advanced computer vision techniques for enhanced intersection safety.

Python YOLOv12 ByteTrack OpenCV License


๐Ÿ“‹ Table of Contents


๐ŸŽฏ Overview

This Red Light Violation Detection System is an AI-powered traffic monitoring solution that processes video streams from traffic cameras to automatically detect vehicles running red lights. By combining state-of-the-art object detection (YOLOv12), multi-object tracking (ByteTrack), and robust color analysis (HSV color space), the system provides accurate real-time violation detection for automated traffic enforcement and intersection safety monitoring.

๐Ÿšจ Problem Statement

Traditional traffic monitoring requires manual review of hours of footage, making it time-consuming and prone to human error. This system automates the entire process, providing:

  • โšก Real-time Detection - Instant violation identification
  • ๐ŸŽฏ High Accuracy - Advanced AI models ensure reliable results
  • ๐Ÿ“Š Automated Monitoring - 24/7 surveillance without human intervention
  • ๐Ÿ’ฐ Cost Effective - Reduces manual labor and improves efficiency

โœจ Key Features

๐Ÿš— Vehicle Detection & Tracking

  • YOLOv12 for high-accuracy vehicle detection
  • ByteTrack (ECCV 2022) for robust multi-object tracking
  • Maintains consistent object IDs through occlusions
  • Two-stage association framework (high/low confidence detections)

๐Ÿšฆ Traffic Light Analysis

  • HSV color space analysis for robust light state classification
  • Multiple ROI support - Monitor multiple traffic lights simultaneously
  • CLAHE enhancement on V channel for better contrast
  • Morphological operations for noise reduction
  • Brightness-weighted voting for accurate color detection

๐ŸŽฏ Violation Detection Logic

  • Geometric line-crossing algorithm with precise center tracking
  • Violation triggered when vehicle crosses line during red light
  • Persistent highlighting - Violating vehicles stay marked in red
  • Label "VIOLATION" displayed throughout the video

๐ŸŽจ Interactive Setup

  • Visual ROI definition interface
  • Draw violation line with mouse clicks
  • Add multiple traffic light regions of interest
  • Real-time preview and adjustment
  • Undo/clear functionality

๐Ÿ“น Video Processing

  • Processes any video format supported by OpenCV
  • Automatic video output and display
  • Frame-by-frame analysis with tracking history
  • Efficient processing with optimized algorithms

๐Ÿ—๏ธ System Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                        INPUT VIDEO STREAM                        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚   YOLOv12 Vehicle Detection   โ”‚
                โ”‚   โ€ข High-accuracy detection   โ”‚
                โ”‚   โ€ข Bounding box extraction   โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚   ByteTrack Multi-Tracking    โ”‚
                โ”‚   โ€ข Consistent ID assignment  โ”‚
                โ”‚   โ€ข Occlusion handling        โ”‚
                โ”‚   โ€ข Center point tracking     โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚   HSV Color Analysis (ROI)    โ”‚
                โ”‚   โ€ข Red light detection       โ”‚
                โ”‚   โ€ข CLAHE enhancement         โ”‚
                โ”‚   โ€ข Morphological cleanup     โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚  Line-Crossing Algorithm      โ”‚
                โ”‚   โ€ข Center point trajectory   โ”‚
                โ”‚   โ€ข Geometric intersection    โ”‚
                โ”‚   โ€ข Violation flagging        โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚    Violation Recording        โ”‚
                โ”‚   โ€ข Visual annotation         โ”‚
                โ”‚   โ€ข Red box highlighting      โ”‚
                โ”‚   โ€ข "VIOLATION" label         โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚      OUTPUT VIDEO             โ”‚
                โ”‚   โ€ข Annotated frames          โ”‚
                โ”‚   โ€ข Auto-save & display       โ”‚
                โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ› ๏ธ Technologies Used

Technology Purpose Version
๐Ÿ Python Core programming language 3.8+
๐ŸŽฏ YOLOv12 State-of-the-art object detection Latest
๐Ÿ” ByteTrack Multi-object tracking (ECCV 2022) Latest
๐Ÿ“ท OpenCV Computer vision & video processing 4.5+
๐ŸŽจ NumPy Numerical computations Latest
๐Ÿ–ผ๏ธ PIL Image processing utilities Latest
โš™๏ธ Ultralytics YOLO implementation framework Latest

๐Ÿ’ป Installation

๐Ÿ“‹ Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • Git

๐Ÿš€ Quick Setup

1๏ธโƒฃ Clone the Repository

git clone https://github.com/HassanRasheed91/Red-Light-Violation-Detection.git
cd Red-Light-Violation-Detection

2๏ธโƒฃ Download YOLOv12 Weights

Download the pre-trained YOLOv12 model weights:

๐Ÿ”— Download yolo12l.pt

Place yolo12l.pt in the project root directory (next to main.py).

3๏ธโƒฃ Create Virtual Environment

For Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1

For Linux/macOS:

python3 -m venv .venv
source .venv/bin/activate

To deactivate later:

deactivate

4๏ธโƒฃ Install Dependencies

pip install -r requirements.txt

๐Ÿ“ฆ Dependencies

opencv-python>=4.5.0
numpy>=1.21.0
ultralytics>=8.0.0
pillow>=9.0.0
pyyaml>=6.0

๐ŸŽฎ Usage

๐ŸŽฌ Step-by-Step Workflow

1๏ธโƒฃ Configure Input Video

Open main.py and set your input video path:

VIDEO_IN = "input/traffic_video.mp4"  # Change to your video path

2๏ธโƒฃ Run the Application

python main.py

3๏ธโƒฃ Setup Interface (Interactive)

A setup window will appear with the first frame:

๐Ÿ”ด Draw Violation Line (Press L):

  • Press L key
  • Click start point of the line
  • Click end point of the line
  • A red line appears showing the violation boundary

๐ŸŸข Add Traffic Light ROI (Press R):

  • Press R key
  • Click top-left corner of traffic light region
  • Click bottom-right corner to complete ROI
  • A green box appears around the traffic light
  • Repeat R to add more traffic lights

Additional Controls:

  • U - Undo last ROI (or line if no ROI exists)
  • C - Clear all ROIs
  • SPACE - Start processing (requires at least 1 line and 1 ROI)
  • Q / Esc - Quit

4๏ธโƒฃ Processing

  • Press SPACE to begin processing
  • Progress shown in terminal
  • Violations detected and highlighted in real-time

5๏ธโƒฃ Output

  • Processed video saved as output_violations.mp4
  • Video automatically opens after processing
  • All violations highlighted with red boxes and "VIOLATION" labels

๐Ÿง  How It Works

๐Ÿš— 1. Vehicle Detection (YOLOv12)

The system uses YOLOv12, the latest evolution of the YOLO series, for real-time vehicle detection:

  • High Accuracy: Detects vehicles with bounding boxes
  • Real-time Performance: Processes frames efficiently
  • Multiple Vehicle Types: Cars, trucks, motorcycles, buses

๐Ÿ” 2. Multi-Object Tracking (ByteTrack)

ByteTrack (ECCV 2022) maintains consistent vehicle identities:

  • Two-Stage Association:
    • High confidence detections matched first
    • Low confidence detections recovered in second stage
  • Occlusion Handling: Tracks vehicles even when temporarily hidden
  • Center Point Tracking: Monitors vehicle trajectory precisely

๐ŸŽจ 3. Traffic Light State Detection (HSV Analysis)

Robust color detection for traffic light status:

Preprocessing Pipeline:

Original ROI โ†’ Downscaling (speed) โ†’ CLAHE on V channel 
           โ†’ Morphological Opening โ†’ Morphological Closing
           โ†’ HSV Masking (Red/Yellow/Green) โ†’ Brightness-Weighted Voting
           โ†’ Light State (RED/YELLOW/GREEN/UNKNOWN)

Key Techniques:

  • HSV Color Space: More robust than RGB for color detection
  • CLAHE: Contrast-Limited Adaptive Histogram Equalization
  • Morphological Operations: Remove noise and clean masks
  • Brightness Weighting: Prioritize brighter pixels in voting

Color Ranges (HSV):

Light Hue Range Saturation Value
๐Ÿ”ด Red 0-10, 160-180 100-255 100-255
๐ŸŸก Yellow 15-35 100-255 100-255
๐ŸŸข Green 40-90 50-255 50-255

Global State Logic:

  • If ANY ROI shows RED โ†’ Global state = RED
  • Otherwise โ†’ First non-red state from ROIs

โš–๏ธ 4. Violation Detection Algorithm

Line-Crossing Detection:

# Geometric intersection check
def crosses_line(prev_center, curr_center, line_start, line_end):
    # Check if trajectory segment intersects violation line
    # Returns True if vehicle crossed the line

Violation Conditions:

  1. โœ… Vehicle center crosses the violation line
  2. โœ… At least ONE traffic light ROI shows RED
  3. โœ… Vehicle ID not already marked as violating

Once Violated:

  • Vehicle ID added to violation set
  • Bounding box color changed to RED permanently
  • "VIOLATION" label displayed throughout video
  • Tracking continues until vehicle leaves frame

๐Ÿ“น 5. Output Generation

  • Each frame annotated with:
    • ๐ŸŸฆ Normal vehicles (blue boxes)
    • ๐ŸŸฅ Violating vehicles (red boxes + "VIOLATION" label)
    • ๐ŸŸข Traffic light ROIs (green boxes)
    • ๐Ÿ”ด Violation line (red line)
    • Current traffic light state
  • Final video saved and auto-played

๐Ÿ“ Project Structure

Red-Light-Violation-Detection/
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ main.py                    # Main application script
โ”œโ”€โ”€ ๐Ÿ“„ requirements.txt           # Python dependencies
โ”œโ”€โ”€ ๐Ÿ“„ bytetrack.yaml            # ByteTrack tracker configuration
โ”œโ”€โ”€ ๐Ÿ“„ yolo12l.pt                # YOLOv12 weights (download separately)
โ”œโ”€โ”€ ๐Ÿ“„ README.md                 # Project documentation
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ input/                    # Input videos directory
โ”‚   โ””โ”€โ”€ ๐Ÿ“น traffic_video.mp4
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ output/                   # Processed videos output
โ”‚   โ””โ”€โ”€ ๐Ÿ“น output_violations.mp4
โ”‚
โ””โ”€โ”€ ๐Ÿ“ .venv/                    # Virtual environment (created during setup)

๐ŸŽฎ Interactive Controls

Key Action Description
L ๐Ÿ“ Draw Line Click two points to define violation boundary
R ๐ŸŸข Add ROI Click two corners to add traffic light region
U โ†ฉ๏ธ Undo Remove last ROI (or line if no ROI)
C ๐Ÿ—‘๏ธ Clear All Remove all ROIs
SPACE โ–ถ๏ธ Start Processing Begin violation detection (needs 1+ line & ROI)
Q / Esc โŒ Quit Exit application

โš™๏ธ Configuration

๐ŸŽ›๏ธ Adjustable Parameters

Edit these in main.py to customize behavior:

Video Settings

VIDEO_IN = "input/your_video.mp4"      # Input video path
VIDEO_OUT = "output_violations.mp4"     # Output video path

Detection Confidence

# In YOLO initialization
conf_threshold = 0.5    # Detection confidence (0.0-1.0)

ByteTrack Parameters (in bytetrack.yaml)

tracker_type: bytetrack
track_high_thresh: 0.6      # High confidence threshold
track_low_thresh: 0.1       # Low confidence threshold
new_track_thresh: 0.7       # New track threshold
track_buffer: 30            # Frames to keep lost tracks
match_thresh: 0.8           # Matching threshold

HSV Color Ranges

# In color detection function
# Red range
red_lower1 = (0, 100, 100)
red_upper1 = (10, 255, 255)
red_lower2 = (160, 100, 100)
red_upper2 = (180, 255, 255)

# Yellow range
yellow_lower = (15, 100, 100)
yellow_upper = (35, 255, 255)

# Green range
green_lower = (40, 50, 50)
green_upper = (90, 255, 255)

CLAHE Settings

clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))

๐Ÿ“ˆ Performance

โšก System Requirements

Component Minimum Recommended
๐Ÿ–ฅ๏ธ CPU Intel i5 / AMD Ryzen 5 Intel i7 / AMD Ryzen 7
๐Ÿ’พ RAM 8 GB 16 GB
๐ŸŽฎ GPU Not required NVIDIA GTX 1060+ (for faster processing)
๐Ÿ’ฝ Storage 5 GB free space 10 GB SSD

๐Ÿ“Š Performance Metrics

Metric Value
Detection Accuracy ~95% (YOLOv12)
Tracking Accuracy ~90% (ByteTrack)
Processing Speed 15-30 FPS (CPU), 60+ FPS (GPU)
False Positive Rate <5%
Color Detection Accuracy ~92% (robust HSV)

๐ŸŽฏ Tested Scenarios

โœ… Multiple vehicles simultaneously
โœ… Varying lighting conditions (day/night)
โœ… Different camera angles
โœ… Partial occlusions
โœ… Different traffic light designs
โœ… Various weather conditions


๐Ÿš€ Future Enhancements

๐Ÿ”ฎ Planned Features

  • ๐Ÿ“น Live Camera Stream Support - Real-time processing from IP cameras
  • ๐Ÿ—„๏ธ Database Integration - Store violations with timestamps and images
  • ๐Ÿ“ง Automated Alerts - Email/SMS notifications for violations
  • ๐Ÿ“Š Analytics Dashboard - Traffic statistics and violation trends
  • ๐ŸŒ Web Interface - Remote monitoring and configuration
  • ๐Ÿš— License Plate Recognition - Automated vehicle identification
  • ๐Ÿ”Š Audio Alerts - Real-time violation announcements
  • ๐Ÿ“ฑ Mobile App - Monitor violations on smartphone
  • โ˜๏ธ Cloud Integration - Upload violations to cloud storage
  • ๐Ÿค– AI Model Fine-tuning - Custom training for specific intersections

๐Ÿ’ก Possible Improvements

  • Advanced Tracking: DeepSORT or StrongSORT for better re-identification
  • Multi-Camera Fusion: Combine multiple camera angles
  • Night Vision Enhancement: Better performance in low-light conditions
  • Weather Adaptation: Automatic adjustments for rain, fog, snow
  • Speed Detection: Estimate vehicle speed for additional violations
  • Pedestrian Detection: Detect pedestrian crossings during red lights

๐Ÿ”ง Troubleshooting

โ— Common Issues & Solutions

1. YOLOv12 Model Not Found

Error: FileNotFoundError: yolo12l.pt not found

โœ… Solution:

  • Download yolo12l.pt from Ultralytics releases
  • Place it in project root directory
  • Verify file name matches exactly

2. OpenCV Import Error

Error: ModuleNotFoundError: No module named 'cv2'

โœ… Solution:

pip install opencv-python
# or
pip install opencv-contrib-python  # For additional features

3. Video Won't Open

Error: Video file not loading

โœ… Solution:

  • Check video path in VIDEO_IN
  • Ensure video format supported (mp4, avi, mov)
  • Try converting video to mp4 format
  • Check video is not corrupted

4. Low Frame Rate

Issue: Slow processing speed

โœ… Solution:

  • Reduce video resolution
  • Use GPU if available
  • Lower confidence threshold
  • Process every Nth frame only

5. Incorrect Light Detection

Issue: Traffic light color not detected correctly

โœ… Solution:

  • Adjust HSV color ranges in code
  • Ensure ROI only contains traffic light
  • Check lighting conditions in video
  • Increase CLAHE clip limit

6. ByteTrack Configuration

Issue: Poor tracking performance

โœ… Solution:

  • Adjust thresholds in bytetrack.yaml
  • Increase track_buffer for longer occlusions
  • Lower match_thresh for better matching
  • Tune confidence thresholds

๐Ÿค Contributing

Contributions are welcome! Here's how you can help:

๐Ÿ“ How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

๐Ÿ› Bug Reports

Found a bug? Please open an issue with:

  • Clear description of the problem
  • Steps to reproduce
  • Expected vs actual behavior
  • Screenshots/videos if applicable

๐Ÿ’ก Feature Requests

Have an idea? Open an issue with:

  • Detailed description of the feature
  • Use case and benefits
  • Possible implementation approach

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments

  • YOLOv12 - Ultralytics team for state-of-the-art object detection
  • ByteTrack - Zhang et al. for robust multi-object tracking (ECCV 2022)
  • OpenCV - Open Source Computer Vision Library
  • Inspiration from traffic monitoring and intelligent transportation systems research

๐Ÿ“ฌ Contact

Hassan Rasheed
๐Ÿ“ง Email: 221980038@gift.edu.pk
๐Ÿ’ผ LinkedIn: hassan-rasheed-datascience
๐Ÿ™ GitHub: HassanRasheed91


๐ŸŒŸ Show Your Support

If you find this project helpful, please consider:

โญ Starring this repository
๐Ÿ”„ Sharing with others
๐Ÿ› Reporting issues
๐Ÿ’ก Suggesting improvements


Made with โค๏ธ By Hassan Rasheed

About

A Python-based computer vision system that detects vehicles violating red traffic lights using video streams: the system monitors traffic signal status, identifies vehicles crossing during a red phase, and flags those as violations aimed at enhancing intersection safety and automated traffic monitoring.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages