Skip to main content

Command Palette

Search for a command to run...

AI Traffic Detection System: Comprehensive Object Detection and Analysis Platform

Learn about YOLO's role in traffic monitoring advancements

Published
6 min read
AI Traffic Detection System: Comprehensive Object Detection and Analysis Platform
R

Tech enthusiast | MATLAB & Python lover | Exploring AI, ML, and deep learning. Sharing free code & tutorials to help others learn faster

Gambaran Umum Proyek

AI Traffic Detection System adalah kumpulan aplikasi canggih yang menggunakan model YOLO (You Only Look Once) dan teknologi Computer Vision untuk mendeteksi objek, kendaraan, serta membaca plat nomor secara real-time. Sistem ini dirancang untuk berbagai skenario mulai dari monitoring CCTV hingga analisis lalu lintas dengan visualisasi data.

# Teknologi Utama yang Digunakan
- YOLO (You Only Look Once) untuk object detection
- EasyOCR untuk Optical Character Recognition
- PyTorch untuk deep learning
- OpenCV untuk computer vision
- Matplotlib untuk visualisasi data

Arsitektur Sistem

Komponen Utama

  1. Object Detection - Mendeteksi kendaraan dan objek lainnya

  2. License Plate Recognition - Membaca plat nomor kendaraan

  3. Real-time Analytics - Analisis data lalu lintas

  4. Multi-source Support - Webcam, RTSP, HLS streams

Penjelasan Detail Setiap File

1. requirements.txt

pip install torch torchvision torchaudio
pip install opencv-python
pip install numpy
pip install easyocr
pip install transformers

Fungsi: File dependensi yang berisi semua library yang diperlukan

  • torch - Framework deep learning PyTorch

  • opencv-python - Computer vision operations

  • easyocr - Optical Character Recognition

  • transformers - Pre-trained models termasuk YOLO

2. objectDetectionTinyYOLO.py

Fungsi: Deteksi objek real-time dari webcam dengan YOLO-tiny

Fitur Utama:

  • Deteksi 80+ objek berbeda

  • Label dalam Bahasa Indonesia

  • Optimasi performa (6 FPS)

  • Resolusi adjustable

# Contoh penggunaan
def detect_from_webcam():
    cap = cv2.VideoCapture(0)  # Webcam default
    # Proses deteksi dengan YOLO-tiny

Cara Menjalankan:

python objectDetectionTinyYOLO.py

3. objectDetectionCCTV.py

Fungsi: Sistem monitoring CCTV dengan deteksi plat nomor

Fitur Utama:

  • Support RTSP streams

  • Deteksi kendaraan + plat nomor

  • Integrasi EasyOCR

  • Threshold konfidensi 85%

# Konfigurasi RTSP
detect_from_rtsp("rtsp://admin:admin@192.x.x.x:8554/Streaming/Channels/102")

Cara Menjalankan:

python objectDetectionCCTV.py

4. TrafficDetectionYOLOatcsCPU.py

Fungsi: Deteksi lalu lintas optimized untuk CPU

Fitur Utama:

  • Support HLS streams (m3u8)

  • Deteksi multiple object types

  • Optimized untuk performa CPU

  • Resolusi tinggi (1280x720)

# Optimasi untuk CPU
frame = cv2.resize(frame, (940, 560))  # Reduce resolution

Cara Menjalankan:

python TrafficDetectionYOLOatcsCPU.py

5. TrafficDetectionYoloGPU.py

Fungsi: Versi accelerated dengan GPU support

Fitur Utama:

  • Auto-detection GPU/CPU

  • Frame skipping untuk performa

  • Lower resolution processing

  • Real-time detection

# GPU Optimization
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny').to(device)

Cara Menjalankan:

python TrafficDetectionYoloGPU.py

6. TrafficDetectioinWithDataRealtime.py

Fungsi: Sistem analisis lalu lintas lengkap dengan data visualization

Fitur Utama:

  • Real-time data logging ke CSV

  • Live graphs dengan matplotlib

  • Performance metrics

  • Auto-folder creation untuk penyimpanan

# Data Analytics
plt.ion()  # Interactive mode
fig, (ax_graph, ax_table) = plt.subplots(2, 1, figsize=(10, 7))

Cara Menjalankan:

python TrafficDetectioinWithDataRealtime.py

Panduan Menjalankan Proyek

Prasyarat Sistem

Minimum Requirements:

  • OS: Windows 10/11, Ubuntu 18.04+, macOS 10.14+

  • Python: 3.8 atau lebih baru

  • RAM: 4GB (8GB recommended)

  • Storage: 2GB free space

  • GPU: NVIDIA dengan CUDA support

  • VRAM: 4GB+

  • CPU: Multi-core processor

Step-by-Step Installation

1. Setup Environment

# Clone atau download project files
# Pastikan Python dan pip sudah terinstall

# Buat virtual environment (optional)
python -m venv traffic_env
source traffic_env/bin/activate  # Linux/Mac
traffic_env\Scripts\activate    # Windows

2. Install Dependencies

# Menggunakan requirements.txt
pip install -r requirements.txt

# Atau install manual
pip install torch torchvision torchaudio opencv-python numpy easyocr transformers matplotlib pandas

3. Verifikasi Installation

# Test script sederhana
import torch
import cv2
import easyocr

print("PyTorch version:", torch.__version__)
print("CUDA available:", torch.cuda.is_available())
print("OpenCV version:", cv2.__version__)

Menjalankan Aplikasi Tertentu

Untuk Webcam Detection:

python objectDetectionTinyYOLO.py

Hotkeys:

  • q - Keluar dari aplikasi

  • Otomatis detect objek dalam frame

Untuk CCTV Monitoring:

python objectDetectionCCTV.py

Konfigurasi:

  • Edit RTSP URL di dalam file

  • Sesuaikan threshold deteksi

Untuk Traffic Analysis:

python TrafficDetectioinWithDataRealtime.py

Output:

  • File CSV di folder hasil_deteksi

  • Live graphs dan statistics

  • Real-time object counting

Konfigurasi Lanjutan

1. Menggunakan GPU

# Secara otomatis akan menggunakan GPU jika tersedia
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

2. Adjusting Detection Threshold

# Ubah nilai threshold (0.0 - 1.0)
results = image_processor.post_process_object_detection(
    outputs, threshold=0.8, target_sizes=target_sizes  # Ubah 0.8 sesuai kebutuhan
)

3. Customizing Stream Sources

# Webcam
cap = cv2.VideoCapture(0)  # 0 untuk default camera

# RTSP Stream
cap = cv2.VideoCapture("rtsp://username:password@ip:port/path")

# HLS Stream
cap = cv2.VideoCapture("http://example.com/stream.m3u8")

# Video File
cap = cv2.VideoCapture("video.mp4")

⚙️ Troubleshooting dan Optimasi

Masalah Umum dan Solusi

1. ModuleNotFoundError

# Jika ada library yang missing
pip install [library_name]
# atau
pip install -r requirements.txt --upgrade

2. Webcam Tidak Terdeteksi

# Coba camera index berbeda
cap = cv2.VideoCapture(0)  # Coba 1, 2, 3...
if not cap.isOpened():
    print("Camera tidak terbuka, coba index lain")

3. Performance Issues

# Reduce resolution
frame = cv2.resize(frame, (640, 480))

# Implement frame skipping
frame_skip = 3  # Process every 3rd frame

# Use smaller model
model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')

4. Memory Problems

# Clear cache regularly
torch.cuda.empty_cache()

# Use smaller batch sizes
inputs = image_processor(images=image, return_tensors="pt").to(device)

Optimasi Performa

Untuk CPU:

# Gunakan YOLO-tiny
# Kurangi resolusi
# Implement frame skipping
# Gunakan threading untuk I/O operations

Untuk GPU:

# Pastikan CUDA available
model.to(device)  # Pindah model ke GPU
inputs = inputs.to(device)  # Pindah input ke GPU

Output dan Analytics

Data yang Dihasilkan:

  1. Real-time Detection Logs

    • File CSV dengan timestamp

    • Count per object category

    • Confidence scores

  2. Visual Analytics

    • Live graphs object counts

    • Performance metrics

    • Traffic flow analysis

  3. Processed Media

    • Annotated video frames

    • License plate records

    • Detection snapshots

🔧 Customization dan Extensions

Menambah Object Categories:

label_translation = {
    'existing': 'terjemahan',
    'new_object': 'objek_baru'  # Tambahkan di sini
}

Modifikasi Detection Parameters:

# Confidence threshold
threshold = 0.7  # Lebih rendah = lebih banyak deteksi

# Non-maximum suppression
iou_threshold = 0.5  # Untuk overlap handling

Integration dengan Database:

# Contoh integration dengan SQLite
import sqlite3
conn = sqlite3.connect('traffic_data.db')
# Simpan detection results

Use Cases dan Aplikasi

1. Traffic Management

  • Monitoring kepadatan lalu lintas

  • Analisis pola traffic

  • Incident detection

2. Security Surveillance

  • License plate recognition

  • Suspicious activity detection

  • Perimeter monitoring

3. Smart City Applications

  • Traffic flow optimization

  • Parking management

  • Public safety monitoring

4. Research and Development

  • Computer vision research

  • Algorithm benchmarking

  • Dataset generation


Monitoring dan Maintenance

Performance Monitoring:

# Track FPS
start_time = time.time()
# Processing code
fps = 1 / (time.time() - start_time)
print(f"FPS: {fps:.2f}")

Resource Usage:

# Memory monitoring
if torch.cuda.is_available():
    print(f"GPU Memory: {torch.cuda.memory_allocated()/1024**3:.2f} GB")

Roadmap dan Pengembangan

Planned Features:

  1. Multi-camera Support - Synchronized monitoring

  2. Alert System - Automated notifications

  3. Cloud Integration - Remote monitoring

  4. Mobile App - On-the-go access

  5. Advanced Analytics - Predictive analysis

Optimization Goals:

  1. Real-time Performance - <100ms latency

  2. Accuracy Improvement - >95% detection rate

  3. Resource Efficiency - Lower CPU/GPU usage

  4. Scalability - Support for 100+ cameras

Dengan struktur yang terorganisir dan dokumentasi yang komprehensif, AI Traffic Detection System ini siap untuk deployment dalam berbagai skenario real-world, dari penelitian akademis hingga aplikasi industri skala penuh.


Contact Me to get FULL Program

📩Email