Spaces:
Sleeping
Sleeping
File size: 1,479 Bytes
3f24d58 |
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 |
import streamlit as st
import numpy as np
import joblib
import pickle
from PIL import Image
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, MobileNetV2
from tensorflow.keras.models import Model
# Constants
IMAGE_SIZE = (128, 128)
# Load the trained KNN model
knn_model = joblib.load("knn_animal_classifier.pkl")
# Load class labels
with open("class_labels.pkl", "rb") as f:
class_labels = pickle.load(f)
# Load the MobileNetV2 feature extractor
base_model = MobileNetV2(weights="imagenet", include_top=False, input_shape=(128, 128, 3), pooling="avg")
feature_extractor = Model(inputs=base_model.input, outputs=base_model.output)
# Streamlit UI
st.title("🐾 Animal Image Classifier (KNN + MobileNetV2)")
st.write("Upload an image of an animal to classify it.")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file).convert("RGB")
st.image(image, caption="Uploaded Image", use_column_width=True)
# Preprocess image
img = image.resize(IMAGE_SIZE)
img_array = img_to_array(img)
img_array = preprocess_input(img_array)
img_array = np.expand_dims(img_array, axis=0)
# Extract features and predict
features = feature_extractor.predict(img_array)
prediction = knn_model.predict(features)[0]
st.success(f"🧠 Predicted Animal: **{prediction}**")
|