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("