Skip to main content

Lesson 6 of 12

Traffic Counter

Build a traffic counter that uses background subtraction and YOLOv8 to count vehicles passing a virtual line in a video.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Traffic Counter System

Traffic Counter System
from ultralytics import YOLO
import cv2
import numpy as np
from collections import defaultdict

class TrafficCounter:
    """
    Counts vehicles crossing a virtual counting line in a video.
    Uses YOLOv8 for detection and centroid tracking.
    """

    VEHICLE_CLASSES = {"car", "truck", "bus", "motorbike", "bicycle"}

    def __init__(self, model_path="yolov8n.pt", confidence=0.4):
        self.model = YOLO(model_path)
        self.confidence = confidence
        self.counted_ids = set()
        self.counts = defaultdict(int)
        self.tracks = {}  # id → previous position

    def is_crossing_line(self, prev_y, curr_y, line_y):
        """Check if an object crossed the counting line between frames."""
        return (prev_y < line_y <= curr_y) or (curr_y < line_y <= prev_y)

    def count_traffic(self, video_path, output_path="counted.mp4",
                      line_position_pct=0.5, max_frames=None):
        """Count vehicles crossing a horizontal counting line."""
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            print(f"Cannot open: {video_path}")
            return

        fps   = cap.get(cv2.CAP_PROP_FPS) or 25
        w_vid = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        h_vid = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        # Counting line Y position
        line_y = int(h_vid * line_position_pct)

        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        writer = cv2.VideoWriter(output_path, fourcc, fps, (w_vid, h_vid))

        frame_count = 0
        while True:
            ret, frame = cap.read()
            if not ret or (max_frames and frame_count >= max_frames):
                break

            # Run YOLO with tracking
            results = self.model.track(
                frame, conf=self.confidence, persist=True, verbose=False
            )

            # Process detections
            if results[0].boxes.id is not None:
                for box, track_id, cls_id in zip(
                    results[0].boxes.xyxy,
                    results[0].boxes.id.int().tolist(),
                    results[0].boxes.cls.int().tolist()
                ):
                    cls_name = self.model.names[cls_id]
                    if cls_name not in self.VEHICLE_CLASSES:
                        continue

                    x1, y1, x2, y2 = map(int, box)
                    cy = (y1 + y2) // 2  # Centre y

                    # Check for line crossing
                    if track_id in self.tracks:
                        prev_cy = self.tracks[track_id]
                        if (self.is_crossing_line(prev_cy, cy, line_y)
                                and track_id not in self.counted_ids):
                            self.counts[cls_name] += 1
                            self.counted_ids.add(track_id)

                    self.tracks[track_id] = cy

                    # Draw box
                    colour = (0, 255, 0) if track_id in self.counted_ids else (255, 165, 0)
                    cv2.rectangle(frame, (x1, y1), (x2, y2), colour, 2)
                    cv2.putText(frame, f"{cls_name} #{track_id}", (x1, y1-5),
                               cv2.FONT_HERSHEY_SIMPLEX, 0.4, colour, 1)

            # Draw counting line and stats
            cv2.line(frame, (0, line_y), (w_vid, line_y), (0, 0, 255), 2)
            cv2.putText(frame, "COUNTING LINE", (10, line_y-5),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1)

            # Display counts
            total = sum(self.counts.values())
            cv2.putText(frame, f"Total vehicles: {total}", (10, 30),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2)
            y = 55
            for cls, count in sorted(self.counts.items()):
                cv2.putText(frame, f"  {cls}: {count}", (10, y),
                           cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,255), 1)
                y += 22

            writer.write(frame)
            frame_count += 1

        cap.release()
        writer.release()

        print(f"\n=== Traffic Count Results ===")
        print(f"Frames processed: {frame_count}")
        for cls, count in sorted(self.counts.items()):
            print(f"  {cls:12s}: {count}")
        print(f"  {'TOTAL':12s}: {sum(self.counts.values())}")
        print(f"Saved: {output_path}")

counter = TrafficCounter(confidence=0.4)
counter.count_traffic("traffic_video.mp4", line_position_pct=0.5, max_frames=600)
Diagram
Loading diagram…

Machine Learning follows a structured pipeline from data to deployment

Topics in This Module

0/12 done