Spaces:
Sleeping
Sleeping
File size: 2,187 Bytes
e8c4882 1d2e742 431f73f 1d2e742 e8c4882 431f73f 1d2e742 431f73f e8c4882 431f73f 1d2e742 431f73f 1d2e742 431f73f 1d2e742 431f73f 1d2e742 431f73f 1d2e742 431f73f ed5c9d7 e8c4882 1d2e742 c704fcd ed5c9d7 1d2e742 ed5c9d7 431f73f 1d2e742 |
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 |
import os
import gradio as gr
from ultralytics import YOLO
from PIL import Image
import numpy as np
import cv2
# Define the directory paths for the model and assets based on the current script location
script_dir = os.path.dirname(os.path.abspath(__file__)) # Current script directory
yolo_weights_path = os.path.join(script_dir, 'toolkit', 'ALL_best.pt') # Path to YOLO weights
# Load the YOLO model
model = YOLO(yolo_weights_path)
model.fuse() # Optional for optimization
print("YOLO model loaded successfully with weights.")
# Function to perform detection and segmentation with YOLO
def apply_yolo_segmentation(image):
try:
# Run YOLO on the image and get the results
results = model.predict(source=image, save=False) # Use save=False to keep results in memory
# Retrieve the annotated image from YOLO results
result_image = results[0].plot() # `plot()` returns the image with annotations
# Convert to RGB for Gradio output
result_image_rgb = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)
return result_image_rgb
except Exception as e:
print(f"Error in YOLO segmentation: {e}")
return image # Return the original image if segmentation fails
# Define the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("<h1 style='text-align: center;'>Image Segmentation with YOLO</h1>")
gr.Markdown("Upload an image to see segmentation results using the YOLO model.")
# Input and output layout
with gr.Row():
with gr.Column():
gr.Markdown("### Upload an Image")
input_image = gr.Image(type="numpy", label="Upload an image") # Removed 'tool' and 'source' arguments
submit_btn = gr.Button("Submit")
clear_btn = gr.Button("Clear")
with gr.Column():
gr.Markdown("### Segmented Image Output")
output_image = gr.Image(type="numpy", label="Segmented Image")
# Set up button functionality
submit_btn.click(fn=apply_yolo_segmentation, inputs=input_image, outputs=output_image)
clear_btn.click(fn=lambda: None, outputs=output_image)
# Launch the Gradio app
demo.launch()
|