File size: 972 Bytes
1a1af4b
 
 
 
 
 
 
 
 
 
e539001
4028991
1a1af4b
e539001
 
1a1af4b
 
4028991
1a1af4b
 
 
4028991
 
1a1af4b
4028991
1a1af4b
 
 
 
 
4028991
 
1a1af4b
 
 
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
import gradio as gr
import torch
import cv2
import numpy as np
from PIL import Image
from ultralytics import YOLO

# Load YOLO model
model = YOLO("best.pt").to("cpu")

def predict(image):
    """Detect objects using YOLO and return cropped images."""
    image_np = np.array(image)
    
    # Perform inference
    results = model(image_np, conf=0.85, device='cpu')
    
    cropped_images = []
    for result in results:
        for box in result.boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            cropped = image_np[y1:y2, x1:x2]  # Crop using bounding box
            cropped_images.append(Image.fromarray(cropped))
    
    return cropped_images if cropped_images else image  # Return original if no detections

# Gradio interface
iface = gr.Interface(
    fn=predict,
    inputs="image",
    outputs=gr.Gallery(label="Cropped Objects"),  # Allows multiple images to be displayed
    title="YOLO Object Detection - Cropped Images"
)

iface.launch()