ma4389's picture
Update app.py
845d1c3 verified
import torch
import ultralytics
from ultralytics import YOLO
import cv2
import gradio as gr
# ---- FIX for PyTorch 2.6+ ----
# Allow YOLOv8's DetectionModel class to be loaded from checkpoint
torch.serialization.add_safe_globals([ultralytics.nn.tasks.DetectionModel])
# ---- Load trained YOLO model ----
model = YOLO("best.pt") # Make sure 'best.pt' is in the same folder
# ---- Prediction function ----
def predict(image):
# Run inference
results = model.predict(source=image, conf=0.25)
# Draw boxes on the image
result_image = results[0].plot()
# Convert BGR → RGB for Gradio
return cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)
# ---- Gradio Interface ----
iface = gr.Interface(
fn=predict,
inputs=[
gr.Image(type="filepath", label="Upload Traffic Scene"),
],
outputs=gr.Image(type="numpy", label="Detection Result"),
title="Traffic Light Detection",
description="Upload an image to detect traffic lights using YOLO."
)
if __name__ == "__main__":
iface.launch()