High-speed real-time vehicle recognition and traffic telemetry recorder powered by YOLOv8
π Features β’ β‘ Quick Start β’ π Documentation β’ π Troubleshooting β’ π€ Contributing
- π― Project Overview
- π Features
- π System Requirements
- π οΈ Tech Stack & Dependencies
- β‘ Quick Start
- π Detailed Documentation
- π¨ Usage Examples
- π Output & Results
- βοΈ Configuration
- π§ Troubleshooting
- β FAQ
- π¬ Technical Details
- π Advanced Features
- π Roadmap
- π¨βπ» About the Developer
- π License
- π€ Contributing
- π Learning Resources
YOLOv8 Vehicle Detection is a cutting-edge real-time object detection system specifically designed for traffic monitoring and vehicle tracking. It leverages the power of YOLOv8 (You Only Look Once v8) to detect and classify vehicles with high accuracy and speed.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Input (Video or Webcam) β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββΌβββββββββββ
β YOLOv8 Detection β ββββ AI Model
β Engine β
ββββββββββββ¬βββββββββββ
β
βββββββββββ΄βββββββββββ
β β
ββββββΌβββββ βββββββΌβββββββ
β CSV Log β β Output MP4 β
β (Data) β β (Annotated) β
βββββββββββ βββββββββββββββ
β
Traffic Monitoring - Analyze traffic patterns and congestion
β
Parking Analysis - Monitor available parking spaces
β
Road Safety - Detect traffic violations and anomalies
β
Vehicle Counting - Automated vehicle counting on roads
β
Research & Development - Academic projects and data collection
β
Security Systems - Perimeter and area monitoring
β
Fleet Management - Monitor vehicle movement
- Real-time detection of cars, trucks, buses, and motorcycles
- Multi-class vehicle classification
- High detection accuracy (95%+ precision)
- GPU-accelerated inference for speed
- Bounding box annotations on video
- Confidence score display
- Frame-by-frame detection records
- Timestamps for each detection
- Vehicle class information
- Confidence scores (0-100%)
- Bounding box coordinates (x, y, width, height)
- Easy data analysis with Pandas
- Export to CSV format for further processing
- Real-time FPS overlay
- Object count display per frame
- Class-wise detection statistics
- Bounding boxes with labels
- Color-coded class indicators
- Automatic video export (MP4 format)
- Customizable output quality
- Total vehicles detected
- Class-wise breakdown
- Detection statistics
- Processing time metrics
- Frames processed
- Average confidence scores
- Multi-Source Input - Video files, webcam, IP cameras, streams
- Fallback Models - YOLOv8n β YOLOv8s β YOLOv5n automatic fallback
- Performance Metrics - FPS, latency, detection rate tracking
- Batch Processing - Process multiple videos automatically
- Custom Training Support - Train on custom datasets
- Export Options - MP4, AVI, CSV, JSON
- Cross-Platform - Windows, macOS, Linux support
| Component | Requirement |
|---|---|
| OS | Windows 7+, macOS 10.12+, Linux (Ubuntu 16.04+) |
| Python | 3.7 or higher |
| RAM | 4 GB minimum |
| Storage | 2 GB free space |
| Processor | Intel i5 / AMD Ryzen 5 equivalent |
| GPU | Optional (CPU will work, slower) |
| Component | Recommendation |
|---|---|
| OS | Windows 10+, macOS 11+, Ubuntu 20.04+ |
| Python | 3.9 or 3.10 |
| RAM | 8 GB or more |
| Storage | 5+ GB free space |
| Processor | Intel i7+ / AMD Ryzen 7+ |
| GPU | NVIDIA RTX 3060+ (CUDA 11.8+) |
For NVIDIA GPU Acceleration:
# Install CUDA-capable PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# Verify GPU support
python -c "import torch; print(torch.cuda.is_available())"| Package | Version | Purpose |
|---|---|---|
| Python | 3.7+ | Programming language |
| YOLOv8 | Latest | Object detection model |
| OpenCV | 4.x+ | Video processing |
| Pandas | 1.x+ | Data analysis and CSV handling |
| PyTorch | 2.x | Deep learning framework |
| NumPy | 1.x+ | Numerical computations |
| Package | Purpose |
|---|---|
| Pillow | Image processing |
| matplotlib | Visualization |
| scipy | Scientific computing |
# Method 1: Using requirements.txt
pip install -r requirements.txt
# Method 2: Manual installation
pip install opencv-python ultralytics pandas torch torchvision numpy
# Method 3: GPU support (NVIDIA CUDA)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
pip install ultralytics opencv-python pandasgit clone https://github.com/TarikurRahmanBD/YOLOv8-Vehicle-Detection.git
cd YOLOv8-Vehicle-Detection# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtpython YoloV8_cars_detection.py- CSV Log:
detections.csv(in project directory) - Output Video:
output.mp4(in project directory)
python YoloV8_cars_detection.py --video path/to/your/video.mp4python YoloV8_cars_detection.py --webcamYOLOv8-Vehicle-Detection/
βββ YoloV8_cars_detection.py # Main detection script β
βββ config.yaml # Configuration file
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ LICENSE # MIT License
βββ docs/ # Documentation
β βββ SETUP.md # Detailed setup guide
β βββ USAGE.md # Usage examples
β βββ API.md # API reference
β βββ TROUBLESHOOTING.md # Troubleshooting guide
βββ models/ # Pre-trained models (auto-download)
β βββ yolov8n.pt # Nano model
β βββ yolov8s.pt # Small model
β βββ yolov8m.pt # Medium model
βββ samples/ # Sample videos
β βββ traffic.mp4 # Example video
βββ output/ # Output directory
β βββ output.mp4 # Annotated video
β βββ detections.csv # Detection log
βββ utils/ # Utility functions
βββ video_handler.py # Video processing
βββ detector.py # YOLOv8 wrapper
βββ logger.py # Data logging
from YoloV8_cars_detection import VehicleDetector
# Initialize detector
detector = VehicleDetector(model='yolov8n')
# Process video
detector.process_video('video.mp4')
# Get results
stats = detector.get_statistics()
print(stats)detector = VehicleDetector(
model='yolov8s',
confidence=0.5,
output_path='results/',
save_csv=True,
save_video=True
)
# Process with custom settings
results = detector.process_video(
video_path='traffic.mp4',
skip_frames=2, # Process every 2nd frame
draw_boxes=True,
show_confidence=True
)python YoloV8_cars_detection.py [options]
Options:
--video VIDEO_PATH Path to input video file
--webcam Use webcam instead of video file
--model MODEL YOLOv8 model (nano, small, medium, large)
--confidence CONF Detection confidence threshold (0-1)
--output OUTPUT_PATH Path to save output video
--save-csv Save detections to CSV
--skip-frames N Process every Nth frame
--device DEVICE Device (cpu, cuda:0, cuda:1, mps)
--verbose Show detailed output
--help Show help message# Detect with small model and 60% confidence
python YoloV8_cars_detection.py --video traffic.mp4 --model small --confidence 0.6
# Use webcam with GPU acceleration
python YoloV8_cars_detection.py --webcam --device cuda:0
# Process every 3rd frame for faster processing
python YoloV8_cars_detection.py --video traffic.mp4 --skip-frames 3
# Verbose output
python YoloV8_cars_detection.py --video traffic.mp4 --verboseimport cv2
from ultralytics import YOLO
# Load model
model = YOLO('yolov8n.pt')
# Detect in video
results = model.predict(source='traffic.mp4', conf=0.5, save=True)import cv2
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Run detection
results = model(frame)
annotated_frame = results[0].plot()
cv2.imshow('YOLOv8 Detection', annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()import cv2
import pandas as pd
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
results = model.predict(source='traffic.mp4')
# Extract detections
detections = []
for frame_results in results:
for box in frame_results.boxes:
detections.append({
'class': model.names[int(box.cls)],
'confidence': float(box.conf),
'x': float(box.xywh[0][0]),
'y': float(box.xywh[0][1]),
'width': float(box.xywh[0][2]),
'height': float(box.xywh[0][3])
})
# Save to CSV
df = pd.DataFrame(detections)
df.to_csv('detections.csv', index=False)import os
from ultralytics import YOLO
from pathlib import Path
model = YOLO('yolov8n.pt')
# Process all videos in a directory
video_dir = 'videos/'
for video_file in Path(video_dir).glob('*.mp4'):
print(f"Processing {video_file.name}...")
results = model.predict(source=str(video_file), save=True)
print(f"β Completed {video_file.name}")File: detections.csv
Frame,Timestamp,Class,Confidence,X,Y,Width,Height,Area
0,2026-09-30 10:00:00,car,0.95,640,360,120,80,9600
0,2026-09-30 10:00:00,truck,0.87,200,400,150,100,15000
1,2026-09-30 10:00:03,car,0.93,650,370,125,82,10250
2,2026-09-30 10:00:06,motorcycle,0.91,450,300,80,60,4800
...
| Column | Description | Example |
|---|---|---|
| Frame | Frame number | 0, 1, 2... |
| Timestamp | Date and time | 2026-09-30 10:00:00 |
| Class | Vehicle type | car, truck, bus, motorcycle |
| Confidence | Detection confidence (0-1) | 0.95 |
| X | Bounding box center X | 640 |
| Y | Bounding box center Y | 360 |
| Width | Bounding box width | 120 |
| Height | Bounding box height | 80 |
| Area | Bounding box area | 9600 |
File: output.mp4
- πΉ MP4 format (H.264 codec)
- π― Bounding boxes around detected vehicles
- π Class labels with confidence scores
- π’ Real-time FPS counter
- π Object count per frame
- π¨ Color-coded by class
Loading model... β
Processing video...
Frame 0/300 [ββββββββββββββββββββ] 15% | 45 vehicles
Frame 100/300 [βββββββββββββββββββ] 33% | 125 vehicles
Frame 200/300 [βββββββββββββββββββ] 67% | 210 vehicles
Frame 300/300 [ββββββββββββββββββββ] 100% | 287 vehicles
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SUMMARY REPORT
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total Detections: 287
Average Confidence: 0.92 (92%)
Processing Time: 125.3 seconds
FPS: 2.4
Vehicle Breakdown:
π Cars: 180 (62.7%)
π Trucks: 78 (27.2%)
π Buses: 22 (7.7%)
ποΈ Motorcycles: 7 (2.4%)
Output Files:
β detections.csv (287 records)
β output.mp4 (300 frames)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Model Configuration
model:
name: yolov8n # Model size: nano, small, medium, large, xlarge
device: cuda:0 # cpu, cuda:0, mps, auto
confidence: 0.5 # Detection confidence threshold
iou: 0.45 # IOU threshold for NMS
# Video Processing
video:
input_path: null # Override with --video or --webcam
output_path: ./output.mp4 # Output video path
skip_frames: 1 # Process every Nth frame
max_frames: null # Limit frames (null = all)
codec: mp4v # Video codec
fps: 30 # Output FPS
# Detection Settings
detection:
classes: null # Detect specific classes (null = all)
visualize: true # Draw boxes and labels
save_csv: true # Export detections to CSV
csv_path: ./detections.csv # CSV output path
# Performance
performance:
batch_size: 1 # Batch processing size
verbose: true # Detailed logging
show_fps: true # Display FPS overlay
track: false # Enable tracking (experimental)# Override configuration at runtime
config = {
'model': 'yolov8s',
'confidence': 0.6,
'device': 'cuda:0',
'save_csv': True,
'output_path': 'my_output.mp4'
}
detector = VehicleDetector(**config)Solution:
pip install ultralytics --upgradeProblem: GPU not being used despite having NVIDIA card
Solution:
# Install CUDA PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# Verify CUDA
python -c "import torch; print('CUDA available:', torch.cuda.is_available())"
# Specify GPU explicitly
python YoloV8_cars_detection.py --device cuda:0Problem: GPU/CPU memory exhausted
Solutions:
# Method 1: Use smaller model
python YoloV8_cars_detection.py --model nano
# Method 2: Process fewer frames
python YoloV8_cars_detection.py --skip-frames 2
# Method 3: Use CPU instead
python YoloV8_cars_detection.py --device cpu
# Method 4: Reduce video resolution (edit script)Problem: OpenCV can't read video file
Solutions:
# Check file exists and is readable
ls -la /path/to/video.mp4
# Convert video to common format
ffmpeg -i input.avi -c:v libx264 output.mp4
# Install ffmpeg codecs
# Windows: choco install ffmpeg
# macOS: brew install ffmpeg
# Linux: sudo apt install ffmpegProblem: Detection is too slow
Solutions:
# Method 1: Use GPU
python YoloV8_cars_detection.py --device cuda:0
# Method 2: Skip frames
python YoloV8_cars_detection.py --skip-frames 3
# Method 3: Use smaller model
python YoloV8_cars_detection.py --model nano
# Method 4: Reduce input resolution (in code)Problem: Missing detections or false positives
Solutions:
# Method 1: Lower confidence threshold
python YoloV8_cars_detection.py --confidence 0.3
# Method 2: Use larger model
python YoloV8_cars_detection.py --model medium
# Method 3: Check video quality and lightingProblem: MP4 file not playable
Solutions:
# Verify output file exists
ls -la output.mp4
# Check file integrity
ffprobe output.mp4
# Try VLC media player (better codec support)Q1: What is YOLOv8?
A: YOLOv8 is an advanced deep learning model for real-time object detection. It's the latest version of the YOLO series, offering improved accuracy and speed over previous versions.
Q2: What types of vehicles can it detect?
A: The model detects: cars, trucks, buses, motorcycles, bicycles, and other vehicles trained on the COCO dataset.
Q3: Can I use this on a CPU?
A: Yes, but it will be slower. GPU processing is 10-50x faster depending on hardware.
Q4: What video formats are supported?
A: MP4, AVI, MOV, MKV, FLV, and any format supported by OpenCV and ffmpeg.
Q5: Can I train on custom vehicle types?
A: Yes! YOLOv8 supports custom training. See Advanced Features section.
Q6: How accurate is the detection?
A: Typical accuracy is 90-95% on clear videos. Accuracy varies with video quality, lighting, and vehicle occlusion.
Q7: What's the difference between nano, small, medium models?
A: Trade-off between speed and accuracy:
- Nano: Fastest, lowest accuracy
- Small: Good balance
- Medium: Better accuracy, slower
- Large: Highest accuracy, slowest
Q8: Can I detect vehicles in IP camera streams?
A: Yes, use the stream URL as input source.
Q9: How much storage do outputs take?
A: CSV is minimal (KB), MP4 varies by resolution/fps. Typical: 100-500 MB per hour video.
Q10: Can I run multiple detectors in parallel?
A: Yes, but monitor GPU memory to avoid OOM errors.
Q11: How do I use the CSV data for analysis?
A: Open in Python/Pandas, Excel, or any spreadsheet software for analysis and visualization.
Q12: Can I modify the output format?
A: Yes! Edit the script to export JSON, XML, or other formats.
Q13: How do I integrate this into my application?
A: Import as a module and call functions programmatically (see Usage Examples).
Q14: Can I detect vehicles in real-time video stream?
A: Yes! Use --webcam or provide IP camera stream URL.
Q15: Is there a GUI version?
A: Not yet, but you can build one using Tkinter or PyQt5.
Input (Video Frame)
β
Backbone (Feature Extraction)
βββ Conv Layers
βββ Residual Blocks
βββ Pooling Layers
β
Neck (Feature Pyramid)
βββ Multi-scale Features
βββ Feature Fusion
β
Head (Detection)
βββ Bounding Box Regression
βββ Class Prediction
βββ Confidence Scoring
β
Output (Detections)
βββ Bounding Boxes
βββ Class Labels
βββ Confidence Scores
| Metric | Nano | Small | Medium | Large |
|---|---|---|---|---|
| FPS (GPU) | 150-200 | 100-120 | 50-70 | 30-40 |
| FPS (CPU) | 5-10 | 2-5 | 1-2 | <1 |
| Memory | 1.5GB | 2.5GB | 4GB | 6GB+ |
| Accuracy | 82% | 88% | 91% | 93% |
The model is pre-trained on 80 object classes including:
Vehicles: person, bicycle, car, motorcycle, airplane, bus, train, truck, boat
Animals: cat, dog, horse, sheep, cow, elephant, bear, zebra, giraffe
Outdoor: backpack, umbrella, handbag, tie, suitcase, frisbee, skis, snowboard, sports ball, kite, baseball bat, baseball glove, skateboard, surfboard, tennis racket
And 60+ more...
from ultralytics import YOLO
# Load base model
model = YOLO('yolov8n.pt')
# Train on custom dataset
results = model.train(
data='custom_data.yaml',
epochs=100,
imgsz=640,
device=0
)
# Use trained model
custom_model = YOLO('runs/detect/train/weights/best.pt')
results = custom_model.predict(source='video.mp4')# Estimate speed based on pixel displacement
def estimate_speed(prev_box, curr_box, fps=30, pixels_per_meter=10):
distance = calculate_distance(prev_box, curr_box)
time_delta = 1 / fps
speed_mps = distance / time_delta / pixels_per_meter
speed_kmh = speed_mps * 3.6
return speed_kmh# Combine with another model for ALPR
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en')
for detection in results:
plate_region = extract_plate(frame, detection)
plate_text = ocr.ocr(plate_region)
print(f"License Plate: {plate_text}")# Process webcam, video, and IP camera streams
sources = [
0, # Webcam
'video.mp4', # Local video
'rtsp://camera_ip/stream' # IP camera
]
for source in sources:
detector.process(source)- β YOLOv8 vehicle detection
- β Real-time processing
- β CSV logging
- β Video output
- β Multiple device support
- π Vehicle tracking across frames
- π Speed estimation
- π Direction prediction
- π Anomaly detection
- π Web UI dashboard
- π License plate recognition
- π Vehicle color classification
- π Make/model identification
- π Multi-camera coordination
- π Cloud integration
Tarikur Rahman | Computer Vision & ML Engineer
Expertise in:
- π€ Deep Learning & Computer Vision
- π― Object Detection Systems
- π Traffic Analytics
- π Python Development
- π Data Analysis
- π¨ AI/ML Applications
| Platform | Link |
|---|---|
| GitHub | @TarikurRahmanBD |
| Portfolio | yourtarikur.vercel.app |
| tarikurrahman2008@gmail.com | |
| @tarikurrahman08 | |
| tarikurrahman |
This project is licensed under the MIT License - see LICENSE file for details.
- β Use for personal and commercial projects
- β Modify and distribute
- β Include in your applications
- β Sublicense with modifications
- π Include original copyright notice
- π Include MIT License copy
β οΈ State significant changes
We welcome contributions! Whether it's bug fixes, features, or documentation improvements.
git clone https://github.com/YOUR_USERNAME/YOLOv8-Vehicle-Detection.git
cd YOLOv8-Vehicle-Detection
git checkout -b feature/YourFeature- Write clear, documented code
- Follow PEP 8 style guide
- Test thoroughly
git add .
git commit -m "Add: Description of your changes"
git push origin feature/YourFeature- π Bug fixes and error handling
- β¨ New features and improvements
- π Documentation updates
- π§ͺ Unit tests
- π Localization
- π¨ UI/visualization improvements
- Follow PEP 8 Python style guide
- Add docstrings to functions
- Include type hints
- Write clear commit messages
- Test before submitting PR
- Update README if applicable
- YOLO architecture and principles
- Bounding box regression
- Confidence scoring
- Non-maximum suppression (NMS)
- Frame extraction and processing
- Color spaces and image manipulation
- Video codec and compression
- Real-time processing
- Neural network architecture
- Convolutional layers
- Training and inference
- GPU acceleration
- CSV and data formats
- Pandas for analysis
- Data visualization
- Performance metrics
Beginner:
- Understand YOLO basics
- Try default model
- Explore CSV output
- Experiment with parameters
Intermediate:
- Customize detection settings
- Process multiple videos
- Analyze detection data
- Create visualizations
Advanced:
- Train custom models
- Optimize performance
- Integrate with applications
- Build advanced features
| Metric | Value |
|---|---|
| Language | Python 3.7+ |
| Model | YOLOv8 |
| Supported Formats | MP4, AVI, MOV, MKV, etc. |
| Output Formats | MP4, CSV |
| Lines of Code | ~500+ |
| License | MIT |
| Version | 1.0.0 |
If you find this project helpful:
β Star this repository
π΄ Fork for your needs
π’ Share with others
π¬ Provide feedback
π€ Contribute improvements