Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pickle
|
| 4 |
+
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input
|
| 5 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
| 6 |
+
from tensorflow.keras.models import Model
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
# Load saved model and class names
|
| 10 |
+
with open("knn_model.pkl", "rb") as f:
|
| 11 |
+
knn = pickle.load(f)
|
| 12 |
+
|
| 13 |
+
with open("class_mapping.pkl", "rb") as f:
|
| 14 |
+
classes = pickle.load(f)
|
| 15 |
+
|
| 16 |
+
# Load MobileNetV2 feature extractor
|
| 17 |
+
base_model = MobileNetV2(weights="imagenet", include_top=False, pooling="avg", input_shape=(224, 224, 3))
|
| 18 |
+
|
| 19 |
+
st.title("🐾 Animal Classifier using KNN & MobileNetV2")
|
| 20 |
+
|
| 21 |
+
uploaded_file = st.file_uploader("Upload an animal image", type=["jpg", "jpeg", "png"])
|
| 22 |
+
|
| 23 |
+
if uploaded_file is not None:
|
| 24 |
+
img = Image.open(uploaded_file).convert("RGB")
|
| 25 |
+
st.image(img, caption="Uploaded Image", use_column_width=True)
|
| 26 |
+
|
| 27 |
+
# Preprocess and extract features
|
| 28 |
+
img = img.resize((224, 224))
|
| 29 |
+
img_array = img_to_array(img)
|
| 30 |
+
img_array = preprocess_input(img_array)
|
| 31 |
+
features = base_model.predict(np.expand_dims(img_array, axis=0), verbose=0)
|
| 32 |
+
|
| 33 |
+
# Predict using KNN
|
| 34 |
+
pred = knn.predict(features)[0]
|
| 35 |
+
predicted_class = classes[pred]
|
| 36 |
+
|
| 37 |
+
st.markdown(f"### 🔍 Predicted Class: `{predicted_class}`")
|