File size: 1,814 Bytes
4f23172
4ece717
 
 
 
4f23172
4ece717
 
4f23172
4ece717
4f23172
4ece717
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f23172
4ece717
 
4f23172
 
4ece717
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import gradio as gr
import torch
from ultralytics import YOLO
import cv2
import tempfile

# Load the trained YOLOv8 model
model = YOLO('best.pt')

def predict(image):
    results = model(image)
    # You might want to process results to return bounding boxes, class labels, etc.
    annotated_image = results[0].plot()  # plot the results on the image
    return annotated_image

def predict_video(video):
    # Read the video file
    cap = cv2.VideoCapture(video)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    
    # Create a temporary file to save the output video
    out_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
    out_path = out_file.name
    
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        results = model(frame)
        annotated_frame = results[0].plot()  # plot the results on the frame
        out.write(annotated_frame)
    
    cap.release()
    out.release()
    
    return out_path

# Create Gradio interface
interface = gr.Interface(
    fn=lambda img, vid: (predict(img), predict_video(vid)),
    inputs=[
        gr.inputs.Image(type="numpy", label="Input Image"),
        gr.inputs.Video(label="Input Video")
    ],
    outputs=[
        gr.outputs.Image(type="numpy", label="Output Image"),
        gr.outputs.Video(label="Output Video")
    ],
    title="YOLOv8 Object Detection",
    description="Upload an image or a video and get the object detection results using a YOLOv8 model."
)

if __name__ == "__main__":
    interface.launch()