|
import gradio as gr |
|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
from sort import Sort |
|
|
|
|
|
model = YOLO("yolov8x.pt") |
|
|
|
|
|
TRUCK_CLASS_ID = 7 |
|
|
|
|
|
tracker = Sort() |
|
|
|
def count_trucks(video_path): |
|
cap = cv2.VideoCapture(video_path) |
|
if not cap.isOpened(): |
|
return "Error: Unable to open video file." |
|
|
|
frame_count = 0 |
|
unique_truck_ids = set() |
|
frame_skip = 5 |
|
|
|
while True: |
|
ret, frame = cap.read() |
|
if not ret: |
|
break |
|
|
|
frame_count += 1 |
|
if frame_count % frame_skip != 0: |
|
continue |
|
|
|
|
|
results = model(frame, verbose=False) |
|
|
|
detections = [] |
|
for result in results: |
|
for box in result.boxes: |
|
class_id = int(box.cls.item()) |
|
confidence = float(box.conf.item()) |
|
x1, y1, x2, y2 = map(int, box.xyxy[0]) |
|
|
|
if class_id == TRUCK_CLASS_ID and confidence > 0.6: |
|
detections.append([x1, y1, x2, y2, confidence]) |
|
|
|
|
|
if len(detections) > 0: |
|
detections = np.array(detections) |
|
else: |
|
detections = np.empty((0, 5)) |
|
|
|
|
|
tracked_objects = tracker.update(detections) |
|
|
|
|
|
for obj in tracked_objects: |
|
truck_id = int(obj[4]) |
|
unique_truck_ids.add(truck_id) |
|
|
|
cap.release() |
|
|
|
return { |
|
"Total Unique Trucks in Video": len(unique_truck_ids) |
|
} |
|
|
|
|
|
def analyze_video(video_file): |
|
result = count_trucks(video_file) |
|
return "\n".join([f"{key}: {value}" for key, value in result.items()]) |
|
|
|
|
|
interface = gr.Interface( |
|
fn=analyze_video, |
|
inputs=gr.Video(label="Upload Video"), |
|
outputs=gr.Textbox(label="Truck Counting Results"), |
|
title="YOLOv8-based Truck Counter with Object Tracking", |
|
description="Upload a video to detect and count unique trucks using YOLOv8 and SORT tracker." |
|
) |
|
|
|
|
|
interface.launch() |
|
|