Spaces:
Sleeping
Sleeping
File size: 4,339 Bytes
425b51a 818c12f 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 571b79d 425b51a 818c12f 425b51a 571b79d 425b51a | 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 130 131 132 133 134 135 136 137 138 139 | # app_rice_resnet50.py
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import preprocess_input
# ----------------- SETTINGS -----------------
# Falls das Modell im Root liegt, nimm: "./best_rice_resnet50.keras"
MODEL_PATH = "src/best_rice_resnet50.keras"
IMG_SIZE = (224, 224)
CLASS_NAMES = [
"Arborio",
"Basmati",
"Ipsala",
"Jasmine",
"Karacadag",
]
# ----------------- MODEL LOADING -----------------
@st.cache_resource
def load_resnet_model():
try:
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
return model
except Exception as e:
st.error(f"Error loading model: {e}")
return None
def preprocess_image(image: Image.Image) -> np.ndarray:
"""Resize image and apply ResNet50 preprocessing."""
img = image.convert("RGB")
img = img.resize(IMG_SIZE)
img_array = np.array(img).astype("float32")
img_array = preprocess_input(img_array)
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict_image(model, image_array: np.ndarray):
"""Safe prediction with Top-3; robust gegen Längen-Mismatch."""
preds = model.predict(image_array, verbose=0)[0]
probs = tf.nn.softmax(preds).numpy()
n_model = len(probs)
n_labels = len(CLASS_NAMES)
n = min(n_model, n_labels)
# Hauptklasse (nur im Bereich [0, n))
main_idx = int(np.argmax(probs[:n]))
pred_class = CLASS_NAMES[main_idx]
pred_conf = float(probs[main_idx])
# Top-k (hier 3) nur im gültigen Bereich
k = min(3, n)
topk_idx = np.argsort(probs[:n])[-k:][::-1]
topk = [(CLASS_NAMES[i], float(probs[i])) for i in topk_idx]
# Nur die ersten n Wahrscheinlichkeiten zurückgeben
return pred_class, pred_conf, probs[:n], topk, n_model, n_labels
# ----------------- PAGE CONFIG -----------------
st.set_page_config(
page_title="Rice Classifier – ResNet50 (Transfer Learning)",
page_icon="🌾",
layout="wide",
)
# ----------------- SIDEBAR -----------------
st.sidebar.title("🌾 Rice ResNet50 Classifier")
st.sidebar.write(
"This app uses a ResNet50 transfer learning model 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 – ResNet50 (Transfer Learning)")
st.write("Upload a rice grain image. The model will predict the rice type and show top-3 results.")
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 ResNet50 model and making prediction..."):
model = load_resnet_model()
if model is not None:
img_array = preprocess_image(image)
pred_class, pred_conf, probs, top3, n_model, n_labels = predict_image(
model, img_array
)
# kurze Warnung, falls Modell/Labels nicht exakt matchen
if n_model != n_labels:
st.warning(
f"Model outputs {n_model} classes, CLASS_NAMES has {n_labels}. "
f"Only the first {min(n_model, n_labels)} are shown."
)
with col2:
st.subheader("Prediction")
st.markdown(f"**Predicted class:** `{pred_class}`")
st.markdown(f"**Confidence:** `{pred_conf:.2%}`")
st.subheader("Top-3 predictions")
for name, p in top3:
st.write(f"- {name}: {p:.2%}")
st.subheader("Class probabilities")
df = pd.DataFrame(
{"class": CLASS_NAMES[: len(probs)], "probability": probs}
).set_index("class")
st.bar_chart(df)
with st.expander("Show probabilities as text"):
for name, p in zip(CLASS_NAMES[: len(probs)], probs):
st.write(f"- {name}: {p:.2%}")
else:
st.info("Please upload a rice image to get a prediction.") |