Team Ai
Apppublic

syariefsq/ComputerVisionRoadCleanlinessClassifier

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
prediction.py74 linesDownload Raw Back to src
1import streamlit as st2import tensorflow as tf3import numpy as np4import pickle5from PIL import Image6 7# Load Model and Class Names8MODEL_PATH = './src/my_best_road_cnn_model.keras'9CLASS_NAMES_PATH = './src/class_names.pkl'10IMG_HEIGHT, IMG_WIDTH = 128, 12811 12@st.cache_resource13def load_model():14    return tf.keras.models.load_model(MODEL_PATH)15 16@st.cache_data17def load_class_names():18    with open(CLASS_NAMES_PATH, 'rb') as f:19        return pickle.load(f)20 21model = load_model()22class_names = load_class_names()23 24# Preprocess Image25def preprocess_image(image, target_height, target_width):26    img = image.resize((target_width, target_height))27    img_array = np.array(img) / 255.028    img_array = np.expand_dims(img_array, axis=0)29    return img_array30 31# Predict32def predict_image_class(model, preprocessed_image, class_names):33    prob = model.predict(preprocessed_image)[0][0]34    idx = 1 if prob > 0.5 else 035    return class_names[idx], prob36 37# Streamlit UI38 39def run():40    st.title("🛣️ Road Clean/Dirty Image Classifier")41 42    st.write("Upload a Road image to **Classify** as **Clean** or **Dirty**.")43    st.write("The model predicts whether the road is clean or dirty based on the uploaded image.")44 45    uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png", "bmp", "gif", "webp"])46 47    if uploaded_file is not None:48        image = Image.open(uploaded_file).convert("RGB")49        st.image(image, caption="Uploaded Image", use_container_width=True)50 51        preprocessed = preprocess_image(image, IMG_HEIGHT, IMG_WIDTH)52        label, prob = predict_image_class(model, preprocessed, class_names)53 54        st.subheader(f"Prediction: {label}")55        st.write(f"Probability: {prob:.2%}")56 57        st.write("### Monitoring Insights:")58 59        if label.lower() == "dirty":60            st.info(61                "⚠️ **Dirty Road Detected!**\n\n"62                "This road is predicted as **Dirty**. "63                "Dirty roads can contribute to environmental pollution, health risks, and infrastructure damage. "64                "Consider prioritizing cleaning for this area."65            )66        else:67            st.success(68                "✅ **Clean Road Detected!**\n\n"69                "This road is predicted as **Clean**. "70                "Continue regular monitoring to maintain cleanliness."71            )72 73if __name__ == "__main__":74    run()