File size: 3,166 Bytes
b28045a
cdc6559
07eb959
b28045a
07eb959
 
 
 
67e64d3
b28045a
07eb959
 
 
 
 
 
 
 
 
b28045a
07eb959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b28045a
07eb959
 
b28045a
 
 
 
 
 
 
 
07eb959
 
b28045a
 
 
 
 
 
 
 
07eb959
 
 
 
 
b28045a
07eb959
 
 
 
 
b28045a
 
 
 
8669f8f
07eb959
b28045a
07eb959
 
 
 
 
 
b28045a
 
 
 
 
 
 
 
 
 
cdc6559
b28045a
 
 
07eb959
b28045a
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
# app_rice_cnn.py
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf

# ----------------- SETTINGS -----------------
MODEL_PATH = "src/best_rice_cnn.keras"  
IMG_SIZE = (160, 160)

CLASS_NAMES = [
    "Arborio",
    "Basmati",
    "Ipsala",
    "Jasmine",
    "Karacadag",
]

# ----------------- MODEL LOADING -----------------
@st.cache_resource
def load_cnn_model():
    try:
        model = tf.keras.models.load_model(MODEL_PATH, compile=False)
    except Exception as e:
        st.error(f"Error loading model: {e}")
        model = None
    return model


def preprocess_image(image: Image.Image) -> np.ndarray:
    """Resize image and scale to [0, 1] for CNN model."""
    img = image.convert("RGB")
    img = img.resize(IMG_SIZE)
    img_array = np.array(img).astype("float32") / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    return img_array


def predict_image(model, image_array: np.ndarray):
    preds = model.predict(image_array, verbose=0)[0]
    probs = tf.nn.softmax(preds).numpy()
    pred_idx = int(np.argmax(probs))
    pred_class = CLASS_NAMES[pred_idx]
    pred_conf = float(probs[pred_idx])
    return pred_class, pred_conf, probs


# ----------------- PAGE CONFIG -----------------
st.set_page_config(
    page_title="Rice Classifier – CNN (No Transfer Learning)",
    page_icon="🌾",
    layout="wide",
)

# ----------------- SIDEBAR -----------------
st.sidebar.title("🌾 Rice CNN Classifier")
st.sidebar.write(
    "This app uses a custom CNN model (no transfer learning) to classify rice grains."
)

st.sidebar.subheader("Rice classes")
for idx, name in enumerate(CLASS_NAMES):
    st.sidebar.write(f"- **{idx}** → {name}")

st.sidebar.markdown("---")
st.sidebar.caption("Author: Enes Yamac")

# ----------------- MAIN PAGE -----------------
st.title("🌾 Rice Classifier – CNN (No Transfer Learning)")
st.write("Upload a rice grain image. The CNN model will predict the rice type.")

uploaded_file = st.file_uploader(
    "Upload a rice image (JPG or PNG)",
    type=["jpg", "jpeg", "png"],
)

if uploaded_file is not None:
    image = Image.open(uploaded_file)

    col1, col2 = st.columns([1, 1])

    with col1:
        st.subheader("Uploaded image")
        st.image(image, width=500)

    with st.spinner("Loading CNN model and making prediction..."):
        model = load_cnn_model()

    if model is not None:
        img_array = preprocess_image(image)
        pred_class, pred_conf, probs = predict_image(model, img_array)

        with col2:
            st.subheader("Prediction")
            st.markdown(f"**Predicted class:** `{pred_class}`")
            st.markdown(f"**Confidence:** `{pred_conf:.2%}`")

            st.subheader("Class probabilities")
            df = pd.DataFrame(
                {"class": CLASS_NAMES, "probability": probs}
            ).set_index("class")
            st.bar_chart(df)

            with st.expander("Show probabilities as text"):
                for name, p in zip(CLASS_NAMES, probs):
                    st.write(f"- {name}: {p:.2%}")
else:
    st.info("Please upload a rice image to get a prediction.")