File size: 2,521 Bytes
28f2c43 54d5131 63fa8a2 d33a25e 63fa8a2 4dfc4a8 63fa8a2 9e8b32d 63fa8a2 4dfc4a8 71aa51e 63fa8a2 4dfc4a8 63fa8a2 | 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 | import streamlit as st
import numpy as np
import cv2
import pickle
from pathlib import Path
# ------------------------------
# Paths
# ------------------------------
SRC_PATH = Path(__file__).parent # points to src/
# ------------------------------
# Load models
# ------------------------------
with open(SRC_PATH / "pca_model.pkl", "rb") as f:
pca = pickle.load(f)
with open(SRC_PATH / "svc_model.pkl", "rb") as f:
svc = pickle.load(f)
with open(SRC_PATH / "scaler.pkl", "rb") as f:
scaler = pickle.load(f)
# ------------------------------
# Label mapping
# ------------------------------
label_map = {
0: "fresh apple",
1: "fresh banana",
2: "fresh orange",
3: "rotten apple",
4: "rotten banana",
5: "rotten orange"
}
# ------------------------------
# Streamlit UI
# ------------------------------
st.title("π Fruit Image Classification")
# ---- Example images ----
st.subheader("Example Images")
example_images = [
"Fresh Apple.jpg",
"Fresh Banana.jpg",
"Fresh Orange.jpg",
"Rotten Apple.jpg",
"Rotten Banana.jpg",
"Rotten Orange.jpg"
]
cols = st.columns(3)
for i, img_file in enumerate(example_images):
img_path = SRC_PATH / img_file
if img_path.exists():
img = cv2.imread(str(img_path))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cols[i % 3].image(img, caption=img_file.split(".")[0], width=150)
else:
st.warning(f"Image '{img_file}' not found.")
st.markdown("**Classes:** fresh apple, fresh banana, fresh orange, rotten apple, rotten banana, rotten orange")
# ------------------------------
# File uploader
# ------------------------------
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Read uploaded file as OpenCV image
file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
# Convert BGR β RGB for display
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
st.image(img_rgb, caption="Uploaded Image", use_container_width=True)
# ------------------------------
# Preprocess & predict
# ------------------------------
img_resized = cv2.resize(img, (64, 64))
img_flat = img_resized.flatten().reshape(1, -1)
img_scaled = scaler.transform(img_flat)
img_pca = pca.transform(img_scaled)
pred = svc.predict(img_pca)[0]
label = label_map.get(pred, "Unknown")
st.success(f"Predicted Class: {label}")
|