Skip to content

Elsaraf1/car-counting-project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Car Counting System πŸš—

A YOLOv8-based computer vision system for counting cars in traffic using deep learning.

πŸ“‹ Overview

This project implements an automated car counting system for traffic analysis using the YOLOv8 object detection model. It can process both images and videos to detect and count vehicles in real-time.

NEW: Smart Traffic Light Controller - An intelligent traffic management system that dynamically adjusts green light durations based on real-time traffic density.

✨ Features

Car Counting System

  • Real-time car detection and counting
  • Video processing with frame-by-frame analysis
  • GPU-accelerated training and inference (CUDA 13.0)
  • Comprehensive visualization of results
  • Jupyter notebook with complete workflow

Smart Traffic Light Controller 🚦

  • 4-way intersection management (North, South, East, West)
  • Dynamic timing calculation based on car count
  • Priority-based sequencing (most congested direction first)
  • Automatic green/yellow light control
  • Real-time or video-based testing

πŸ› οΈ Installation

Prerequisites

  • Python 3.10+
  • NVIDIA GPU with CUDA 13.0 (recommended)
  • Anaconda or Miniconda
  • Windows OS

Setup Environment

# Clone the repository
git clone https://github.com/Elsaraf1/car-counting-project.git
cd car-counting-project

# Create conda environment
conda create -n car_counting python=3.10 -y
conda activate car_counting

# Install PyTorch with CUDA support
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

# Install other dependencies
pip install -r requirements.txt

# Create Jupyter kernel
python -m ipykernel install --user --name=car_counting --display-name="Python (car_counting)"

πŸ“Š Dataset

This project uses the Car Counting Dataset from Roboflow.

To download the dataset:

  1. Create a free account at Roboflow
  2. Get your API key from Settings β†’ API Keys
  3. Use the download function in the Jupyter notebook

πŸš€ Usage

Option 1: Car Counting (Jupyter Notebook)

conda activate car_counting
jupyter lab
# Open: notebooks/car_counting_main.ipynb

Option 2: Smart Traffic Light System (Production)

Quick Start - Video Mode

# Place test videos in test_videos/ folder
# Then run:
python main.py

For Development/Testing

jupyter lab
# Open: notebooks/smart_traffic_light.ipynb

Training Your Own Model

from ultralytics import YOLO

# Load pretrained YOLOv8 model
model = YOLO('yolov8n.pt')

# Train on car counting dataset
model.train(
    data='path/to/data.yaml',
    epochs=50,
    imgsz=640,
    batch=16,
    device=0  # Use GPU
)

Inference Example

# Load trained model
model = YOLO('path/to/best.pt')

# Count cars in image
results = model('test_image.jpg')
car_count = len(results[0].boxes)
print(f"Cars detected: {car_count}")

🚦 Smart Traffic Light System

How It Works

  1. Counts cars in all 4 directions using YOLO
  2. Calculates timing: Green time = Cars Γ— 2 seconds
  3. Prioritizes: Most congested direction goes first
  4. Executes sequence: Green β†’ Yellow β†’ Next direction

Formula

Green Light Time = Number of Cars Γ— 2 seconds
Yellow Light Time = max(Green Time Γ— 1%, 3 seconds)
Priority = Most cars β†’ Least cars

Example Output

πŸ“Έ Counting cars in all directions...
  North: 15 cars
  South: 5 cars
  East: 25 cars (MOST)
  West: 8 cars

πŸ“Š Calculated Timings:
  East: 50s green + 3s yellow = 53s total
  North: 30s green + 3s yellow = 33s total
  West: 16s green + 3s yellow = 19s total
  South: 10s green + 3s yellow = 13s total

🚦 Priority Order: East β†’ North β†’ West β†’ South

πŸ“ˆ Model Performance

  • Architecture: YOLOv8 Nano
  • Training Time: ~2-3 hours (50 epochs on GPU)
  • Inference Speed: 30-60 FPS with GPU
  • Expected mAP@50: ~0.85-0.90

πŸ—οΈ Project Structure

car-counting-project/
β”œβ”€β”€ notebooks/
β”‚   β”œβ”€β”€ car_counting_main.ipynb       # Car counting training & inference
β”‚   └── smart_traffic_light.ipynb     # Traffic light system (development)
β”œβ”€β”€ smart_traffic/                     # Traffic light module
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py                      # Configuration settings
β”‚   β”œβ”€β”€ car_counter.py                 # Car detection & counting
β”‚   β”œβ”€β”€ traffic_calculator.py          # Timing calculations
β”‚   └── light_controller.py            # Main controller
β”œβ”€β”€ test_videos/                       # Test videos for 4 directions
β”œβ”€β”€ data/                              # Dataset (not tracked in git)
β”œβ”€β”€ models/                            # Trained models (not tracked)
β”œβ”€β”€ results/                           # Output results
β”œβ”€β”€ main.py                            # Production script for traffic light
β”œβ”€β”€ requirements.txt                   # Python dependencies
β”œβ”€β”€ .gitignore                         # Git ignore rules
└── README.md                          # This file

πŸ’‘ Smart Traffic Light Features

Current Features

  • βœ… 4-way intersection support
  • βœ… Dynamic timing based on traffic density
  • βœ… Priority-based sequencing
  • βœ… Configurable parameters
  • βœ… Video and camera mode support

Potential Enhancements

  • Emergency vehicle priority override
  • Pedestrian crossing detection
  • Weather-based timing adjustments
  • Historical traffic pattern learning
  • Web-based dashboard
  • Hardware integration (Arduino, Raspberry Pi)

🎯 Use Cases

Car Counting System

  • Traffic flow monitoring
  • Parking lot occupancy detection
  • Highway congestion analysis
  • Transportation research

Smart Traffic Light

  • Intelligent intersection management
  • Reducing traffic congestion
  • Emergency vehicle routing
  • Smart city infrastructure
  • Traffic optimization research

πŸ”§ Configuration

Edit smart_traffic/config.py to customize:

TIME_PER_CAR = 2          # Seconds each car needs
YELLOW_RATIO = 0.01       # Yellow time = 1% of green
MIN_YELLOW_TIME = 3       # Minimum yellow (safety)
MAX_GREEN_TIME = 120      # Maximum green time
CONFIDENCE_THRESHOLD = 0.5 # YOLO detection confidence

πŸ› Troubleshooting

GPU Not Detected

python -c "import torch; print(torch.cuda.is_available())"

Out of Memory Error

Reduce batch size:

model.train(data='data.yaml', batch=8)  # or batch=4

Missing Test Videos

Place videos in test_videos/ folder:

  • north.mp4
  • south.mp4
  • east.mp4
  • west.mp4

🀝 Contributing

Contributions, issues, and feature requests are welcome!

πŸ“ License

This project is open source and available under the MIT License.

πŸ™ Acknowledgments

  • Ultralytics YOLOv8 - Object detection framework
  • Roboflow - Dataset hosting and management
  • Computer Vision community for inspiration and support

πŸ“§ Contact

GitHub: @Elsaraf1

Project Link: https://github.com/Elsaraf1/car-counting-project


⭐ If you find this project helpful, please consider giving it a star!

🚦 NEW: Check out the Smart Traffic Light Controller for intelligent intersection management!

About

YOLOv8-based car counting system for traffic analysis

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors