Spaces:
Runtime error
Runtime error
import gradio as gr | |
import torch | |
import cv2 | |
import numpy as np | |
from PIL import Image | |
# Load the YOLOv8 model | |
model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', force_reload=True) # Adjust to yolov8 if needed | |
def process_image(image): | |
results = model(image) | |
return results.render()[0] # Returns an image with boxes drawn | |
def process_video(video): | |
cap = cv2.VideoCapture(video) | |
frames = [] | |
while(cap.isOpened()): | |
ret, frame = cap.read() | |
if not ret: | |
break | |
results = model(frame) | |
frames.append(results.render()[0]) | |
cap.release() | |
# Convert frames back to a video format | |
height, width, layers = frames[0].shape | |
video_out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height)) | |
for frame in frames: | |
video_out.write(frame) | |
video_out.release() | |
return 'output.mp4' | |
# Create Gradio interface | |
image_input = gr.inputs.Image(type="numpy", label="Upload an image") | |
video_input = gr.inputs.Video(type="mp4", label="Upload a video") | |
image_output = gr.outputs.Image(type="numpy", label="Detected image") | |
video_output = gr.outputs.Video(type="mp4", label="Detected video") | |
iface = gr.Interface(fn={'image': process_image, 'video': process_video}, | |
inputs=[image_input, video_input], | |
outputs=[image_output, video_output], | |
live=True, | |
title="YOLOv8 Object Detection", | |
description="Upload an image or video to detect objects using YOLOv8.") | |
if __name__ == "__main__": | |
iface.launch() | |