File size: 2,273 Bytes
eb9e91a | 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import streamlit as st
import numpy as np
import json
from tensorflow.keras.models import Model
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.preprocessing import image
st.set_page_config(
page_title="Elephant Species Classifier",
page_icon="๐",
layout="centered"
)
st.title("๐ Elephant Species Classifier")
st.write("Upload an elephant image and click **Predict**.")
# ------------------ Load Model ------------------ #
@st.cache_resource
def load_artifacts():
base = MobileNetV2(
input_shape=(224, 224, 3),
include_top=False,
weights="imagenet"
)
base.trainable = False
x = GlobalAveragePooling2D()(base.output)
x = Dense(448, activation="relu")(x)
x = Dropout(0.4)(x)
outputs = Dense(2, activation="softmax")(x)
model = Model(base.input, outputs)
model.load_weights("Models/best_Mobilenetv2.weights.h5")
with open("class_indices.json") as f:
class_indices = json.load(f)
idx_to_class = {v: k for k, v in class_indices.items()}
return model, idx_to_class
model, idx_to_class = load_artifacts()
# ------------------ Upload ------------------ #
uploaded_file = st.file_uploader(
"Choose an Elephant Image",
type=["jpg", "jpeg", "png"]
)
if uploaded_file is not None:
col1, col2, col3 = st.columns([1,2,1])
with col2:
st.image(uploaded_file, width=250, caption="Uploaded Image")
st.write("")
if st.button("๐ Predict", type="primary", use_container_width=True):
with st.spinner("Predicting..."):
img = image.load_img(uploaded_file, target_size=(224,224))
x = image.img_to_array(img)
x = x / 255.0
x = np.expand_dims(x, axis=0)
preds = model.predict(x, verbose=0)
pred_idx = np.argmax(preds)
pred_class = idx_to_class[pred_idx]
confidence = np.max(preds) * 100
st.success(f"### ๐ Prediction: {pred_class}")
st.info(f"**Confidence:** {confidence:.2f}%")
else:
st.info("Please upload an image to begin.") |