Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,42 +3,42 @@ from ultralytics import YOLO
|
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
|
| 6 |
-
# Load
|
| 7 |
-
model = YOLO(
|
| 8 |
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
-
def
|
| 12 |
-
|
| 13 |
-
return {}
|
| 14 |
-
|
| 15 |
-
# Convert numpy array input to PIL Image if needed
|
| 16 |
if isinstance(image, np.ndarray):
|
| 17 |
image = Image.fromarray(image)
|
| 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 |
if __name__ == "__main__":
|
| 44 |
-
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
|
| 6 |
+
# Load your pretrained YOLOv8 model (replace with your model path if customized)
|
| 7 |
+
model = YOLO("yolov8n.pt") # Using tiny YOLOv8 pretrained weights for example
|
| 8 |
|
| 9 |
+
# Define the class names according to your trained model classes
|
| 10 |
+
class_names = ["butterfly", "chicken", "elephant", "horse", "spider", "squirrel"]
|
| 11 |
|
| 12 |
+
def classify_animal(image):
|
| 13 |
+
# Convert numpy array to PIL Image
|
|
|
|
|
|
|
|
|
|
| 14 |
if isinstance(image, np.ndarray):
|
| 15 |
image = Image.fromarray(image)
|
| 16 |
+
# YOLO expects numpy array input, convert back to np array
|
| 17 |
+
img_np = np.array(image)
|
| 18 |
+
|
| 19 |
+
# Perform prediction
|
| 20 |
+
results = model(img_np)
|
| 21 |
+
|
| 22 |
+
# Extract top prediction
|
| 23 |
+
if results and len(results) > 0:
|
| 24 |
+
boxes = results[0].boxes
|
| 25 |
+
if boxes is not None and len(boxes) > 0:
|
| 26 |
+
# Get the highest confidence prediction
|
| 27 |
+
best_box = boxes[0]
|
| 28 |
+
conf = best_box.conf[0].item()
|
| 29 |
+
class_id = int(best_box.cls[0].item())
|
| 30 |
+
class_name = class_names[class_id] if class_id < len(class_names) else "Unknown"
|
| 31 |
+
return f"Predicted: {class_name} (Confidence: {conf:.2f})"
|
| 32 |
+
return "No animal detected."
|
| 33 |
+
|
| 34 |
+
# Build Gradio interface
|
| 35 |
+
iface = gr.Interface(
|
| 36 |
+
fn=classify_animal,
|
| 37 |
+
inputs=gr.Image(type="numpy", label="Upload Animal Image"),
|
| 38 |
+
outputs="text",
|
| 39 |
+
title="Real-Time Animal Type Classification",
|
| 40 |
+
description="Upload an image of an animal to classify it among butterfly, chicken, elephant, horse, spider, and squirrel."
|
| 41 |
+
)
|
| 42 |
|
| 43 |
if __name__ == "__main__":
|
| 44 |
+
iface.launch()
|