CoolFace
Apppublic

FaizaRiaz/Animal_Classification

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
app.py38 linesDownload Raw Back to root
1import streamlit as st2import numpy as np3import pickle4from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input5from tensorflow.keras.preprocessing.image import img_to_array6from tensorflow.keras.models import Model7from PIL import Image8 9# Load saved model and class names10with open("knn_model.pkl", "rb") as f:11    knn = pickle.load(f)12 13with open("class_mapping.pkl", "rb") as f:14    classes = pickle.load(f)15 16# Load MobileNetV2 feature extractor17base_model = MobileNetV2(weights="imagenet", include_top=False, pooling="avg", input_shape=(224, 224, 3))18 19st.title("๐Ÿพ Animal Classifier using KNN & MobileNetV2")20 21uploaded_file = st.file_uploader("Upload an animal image", type=["jpg", "jpeg", "png"])22 23if 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 features28    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 KNN34    pred = knn.predict(features)[0]35    predicted_class = classes[pred]36 37    st.markdown(f"### ๐Ÿ” Predicted Class: `{predicted_class}`")38