Spaces:
Sleeping
Sleeping
File size: 2,783 Bytes
6989a37 13ef1fa 30f242a 13ef1fa 6989a37 c455a41 75e60e4 90d35fd 13ef1fa 6989a37 13ef1fa c455a41 6f2a51c c455a41 6f2a51c 1a4514d 13ef1fa c455a41 13ef1fa c455a41 13ef1fa e3a012f 29b03e2 90d35fd 13ef1fa 29b03e2 90d35fd 29b03e2 90d35fd 29b03e2 13ef1fa 30f242a e3a012f 90d35fd |
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 64 65 66 67 68 69 70 71 72 73 74 75 |
import gradio as gr
from ultralytics import YOLO
from PIL import Image
import numpy as np
import cv2
# Load the YOLOv8 model (make sure the path is correct and model is downloaded)
try:
model = YOLO('yolov8n.pt')
print("Model loaded successfully.")
except Exception as e:
print(f"Error loading model: {e}")
def identify_disease(image):
# Convert the image to RGB if it's not
if image.mode != 'RGB':
image = image.convert('RGB')
# Perform inference
try:
results = model(image)
predictions = results[0]
print("Inference completed.")
except Exception as e:
print(f"Error during inference: {e}")
return image, [{"Disease": "Error", "Confidence": "N/A"}]
# Check if there are any detections
if len(predictions.boxes) == 0:
print("No detections found.")
annotated_image = np.array(image)
cv2.putText(annotated_image, "No disease detected", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
annotated_image = Image.fromarray(annotated_image)
return annotated_image, [{"Disease": "None", "Confidence": "N/A"}]
# Extract predictions
boxes = predictions.boxes
labels = boxes.cls.cpu().numpy() if boxes.cls is not None else []
scores = boxes.conf.cpu().numpy() if boxes.conf is not None else []
class_names = model.names
# Annotate image with bounding boxes and labels
annotated_image = np.array(image)
for box, label, score in zip(boxes.xyxy.cpu().numpy(), labels, scores):
x1, y1, x2, y2 = map(int, box)
class_name = class_names[int(label)]
confidence = f"{score * 100:.2f}%"
annotated_image = cv2.rectangle(annotated_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
annotated_image = cv2.putText(annotated_image, f"{class_name} {confidence}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Convert annotated image back to PIL format
annotated_image = Image.fromarray(annotated_image)
# Prepare results for display
results_list = [{"Disease": class_names[int(label)], "Confidence": f"{score * 100:.2f}%"} for label, score in zip(labels, scores)]
return annotated_image, results_list
# Define Gradio interface with updated syntax
interface = gr.Interface(
fn=identify_disease,
inputs=gr.Image(type="pil"),
outputs=[
gr.Image(type="pil", label="Annotated Image"),
gr.Dataframe(headers=["Disease", "Confidence"], label="Predictions")
],
title="Leaf Disease Identifier with YOLOv8",
description="Upload an image of a leaf, and this tool will identify the disease with confidence scores."
)
# Launch the app
interface.launch()
|