File size: 4,375 Bytes
f68a63a
0287c29
9716754
f68a63a
9716754
 
 
 
f68a63a
 
 
9716754
f68a63a
9716754
 
 
f68a63a
 
 
8cabf80
9716754
 
 
 
 
 
 
 
 
 
 
 
 
 
f68a63a
 
 
9716754
 
956f18c
 
9716754
 
 
f68a63a
 
 
9716754
 
 
 
f68a63a
 
9716754
 
 
f68a63a
9716754
 
f68a63a
9716754
 
 
 
f68a63a
 
 
9716754
f68a63a
9716754
 
f68a63a
 
9716754
 
f68a63a
 
 
 
9716754
 
f68a63a
 
9716754
f68a63a
 
 
 
 
9716754
 
 
 
f68a63a
 
 
9716754
f68a63a
9716754
 
 
f68a63a
 
 
9716754
 
f68a63a
9716754
f68a63a
9716754
 
f68a63a
 
9716754
f68a63a
9716754
f68a63a
 
 
 
 
 
 
9716754
f68a63a
 
0287c29
9716754
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# --- Fish Classifier (CNN from scratch) ---------------------------------------
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf
from tensorflow.keras.models import load_model

# -----------------------------------------------------------------------------
# PAGE CONFIG
# -----------------------------------------------------------------------------
st.set_page_config(
    page_title="Fish Classifier (CNN – From Scratch)",
    layout="centered"
)

# -----------------------------------------------------------------------------
# SETTINGS
# -----------------------------------------------------------------------------
MODEL_PATH = "src/best_fish_cnn_new.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"
]

# -----------------------------------------------------------------------------
# MODEL LOADING (CACHED)
# -----------------------------------------------------------------------------
@st.cache_resource
def load_model_cached():
    model = tf.keras.models.load_model(MODEL_PATH, compile=False)
    return model

model = load_model_cached()

# -----------------------------------------------------------------------------
# HELPER FUNCTIONS
# -----------------------------------------------------------------------------
def preprocess_image(image: Image.Image) -> np.ndarray:
    """Resize and normalize image for the CNN model."""
    image = image.convert("RGB")
    image = image.resize(IMG_SIZE)
    img_array = np.array(image).astype("float32") / 255.0  
    img_array = np.expand_dims(img_array, axis=0)        
    return img_array

def predict_image(image: Image.Image):
    """Run model prediction and return class label and probability vector."""
    img_batch = preprocess_image(image)
    preds = model.predict(img_batch)
    probs = preds[0]                    
    pred_index = int(np.argmax(probs))
    pred_class = CLASS_NAMES[pred_index]
    return pred_class, probs

# -----------------------------------------------------------------------------
# UI – HEADER
# -----------------------------------------------------------------------------
st.title("🐟 Fish Species Classifier (CNN From Scratch)")

st.write(
    "Upload a fish image and the model will predict one of **9 fish species**. "
    "This model is a custom Convolutional Neural Network (**no transfer learning**) "
    "trained on the Kaggle fish dataset."
)

# -----------------------------------------------------------------------------
# SIDEBAR INFO
# -----------------------------------------------------------------------------
st.sidebar.header("ℹ️ About this app")
st.sidebar.markdown(
    """
    **Model:** Custom CNN (no transfer learning)  
    **Input size:** 224 Γ— 224  
    **Classes:** 9 fish species  

    **Validation performance:**  
    - Accuracy: ~84%  
    - Top-3 accuracy: ~95%  

    **Author:** Enes Yamac  
    """
)

# -----------------------------------------------------------------------------
# FILE UPLOAD
# -----------------------------------------------------------------------------
uploaded_file = st.file_uploader(
    "πŸ“€ Upload a fish image (JPG/PNG)", 
    type=["jpg", "jpeg", "png"]
)

# -----------------------------------------------------------------------------
# PREDICTION + OUTPUT
# -----------------------------------------------------------------------------
if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded image", use_container_width=True)

    with st.spinner("πŸ” Predicting..."):
        pred_class, probs = predict_image(image)

    st.subheader("πŸ”Ž Prediction")
    st.write(f"**Predicted class:** `{pred_class}`")

    # Wahrscheinlichkeiten vorbereiten
    prob_dict = {cls: float(p) for cls, p in zip(CLASS_NAMES, probs)}
    prob_df = (
        pd.DataFrame.from_dict(prob_dict, orient="index", columns=["Probability"])
        .sort_values("Probability", ascending=False)
    )

    st.subheader("πŸ“Š Class probabilities")
    st.bar_chart(prob_df)

    with st.expander("Show numeric probabilities"):
        st.dataframe(prob_df.style.format("{:.2%}"))

else:
    st.info("Please upload an image to start.")