Rice-Classifier-CNN / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
8669f8f verified
Raw History Blame Contribute Delete
3.17 kB
# 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.")