File size: 3,211 Bytes
74d5b67
d6423a1
74d5b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7112051
74d5b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6423a1
74d5b67
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# --- Fish Classifier using Transfer Learning (ResNet50)
import streamlit as st
import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import preprocess_input, ResNet50
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

st.set_page_config(
    page_title="Fish Classifier (ResNet50 – Transfer Learning)",
    layout="centered"
)

# ------------------ SETTINGS ------------------
MODEL_PATH = "src/best_fish_resnet50.keras" 
IMG_SIZE = (224, 224)

CLASS_NAMES = [
    "Black Sea Sprat",
    "Gilt-Head Bream",
    "Horse Mackerel",
    "Red Mullet",
    "Red Sea Bream",
    "Sea Bass",
    "Shrimp",
    "Striped Red Mullet",
    "Trout"
]

# ------------------ LOAD MODEL ------------------
@st.cache_resource
def load_model_cached():
    base_model = ResNet50(
        weights="imagenet",
        include_top=False,
        input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)
    )
    base_model.trainable = False

    model = Sequential([
        base_model,
        GlobalAveragePooling2D(),
        Dense(256, activation="relu"),
        Dropout(0.5),
        Dense(len(CLASS_NAMES), activation="softmax")
    ])

    model.load_weights(MODEL_PATH)
    return model

model = load_model_cached()

# ------------------ IMAGE PREPROCESSING ------------------
def preprocess_image(image: Image.Image) -> np.ndarray:
    image = image.convert("RGB")
    image = image.resize(IMG_SIZE)
    img_array = np.array(image)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = preprocess_input(img_array)
    return img_array

# ------------------ PREDICTION ------------------
def predict(image: Image.Image):
    processed_img = preprocess_image(image)
    preds = model.predict(processed_img)
    probs = tf.nn.softmax(preds[0]).numpy()
    top_idx = np.argmax(probs)
    return CLASS_NAMES[top_idx], probs[top_idx], probs

# ------------------ STREAMLIT UI ------------------
st.title("🐟 Fish Classifier (Transfer Learning – ResNet50)")
st.write(
    "This app uses a **ResNet50 Transfer Learning model** trained on 9 fish species "
    "from the *Large Scale Fish Dataset*."
)

st.sidebar.header("πŸ”§ Model Info")
st.sidebar.write(f"**Model file:** `{MODEL_PATH}`")
st.sidebar.write("**Class labels:**")
for cls in CLASS_NAMES:
    st.sidebar.write(f"- {cls}")

uploaded_file = st.file_uploader("πŸ“€ Upload a fish image", type=["jpg", "jpeg", "png"])

if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="πŸ“Έ Uploaded Image", use_container_width=True)

    if st.button("πŸ” Predict (ResNet50)"):
        with st.spinner("Analyzing..."):
            top_class, top_prob, probabilities = predict(image)

        st.subheader("πŸ”Ž Prediction")
        st.write(f"**Class:** `{top_class}`")
        st.write(f"**Confidence:** {top_prob:.2%}")

        st.subheader("πŸ“Š Confidence per Class")
        for cls, prob in zip(CLASS_NAMES, probabilities):
            st.write(f"- **{cls}** β†’ {prob:.2%}")
else:
    st.info("Upload an image to start.")