Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pickle
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from skimage.transform import resize
|
| 6 |
+
|
| 7 |
+
# Load the trained KNN model and class names
|
| 8 |
+
with open("knn_model.pkl", "rb") as f:
|
| 9 |
+
knn_model = pickle.load(f)
|
| 10 |
+
|
| 11 |
+
with open("class_names.pkl", "rb") as f:
|
| 12 |
+
class_names = pickle.load(f)
|
| 13 |
+
|
| 14 |
+
# Image Preprocessing Function
|
| 15 |
+
def preprocess_image(image):
|
| 16 |
+
"""Resizes and flattens the image for model prediction."""
|
| 17 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Convert RGB to BGR for OpenCV
|
| 18 |
+
image_resized = resize(image, (224, 224)) # Resize to match training size
|
| 19 |
+
image_flattened = image_resized.flatten().reshape(1, -1) # Flatten to 1D
|
| 20 |
+
return image_flattened
|
| 21 |
+
|
| 22 |
+
# Prediction Function
|
| 23 |
+
def predict_animal(image):
|
| 24 |
+
"""Predicts the class of the uploaded image."""
|
| 25 |
+
processed_image = preprocess_image(image)
|
| 26 |
+
prediction = knn_model.predict(processed_image)[0]
|
| 27 |
+
return f"Predicted Animal: {class_names[prediction]}"
|
| 28 |
+
|
| 29 |
+
# Gradio UI
|
| 30 |
+
title = "Animal Image Classifier 🐾"
|
| 31 |
+
description = "Upload an image of an animal and click 'Identify' to predict the species."
|
| 32 |
+
|
| 33 |
+
app = gr.Interface(
|
| 34 |
+
fn=predict_animal,
|
| 35 |
+
inputs=gr.Image(type="numpy"),
|
| 36 |
+
outputs="text",
|
| 37 |
+
title=title,
|
| 38 |
+
description=description,
|
| 39 |
+
theme="huggingface",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Run the app
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
app.launch()
|