CoolFace
Apppublic

Senasu/Dog_VS_Cat_Image_Classification

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py94 linesDownload Raw Back to root
1import streamlit as st2from tensorflow.keras.models import load_model3from PIL import Image4import numpy as np5import matplotlib.pyplot as plt6import seaborn as sns7 8# Load the trained model9model = load_model('cnn_model.h5')10 11# Function to process the uploaded image12def process_image(img):13    img = img.convert('RGB')  14    img = img.resize((32, 32)) 15    img = np.array(img)  16    img = img / 255.0  17    img = np.expand_dims(img, axis=0) 18    return img19 20# Frontend design21st.set_page_config(page_title="Dog vs Cat Detection", page_icon="🐢🐱", layout="centered")22st.title("Dog vs Cat Image Classification 🐢🐱")23 24# Description25st.markdown("""26    This is a simple Dog vs Cat image classifier. Upload an image of either a dog or a cat, and 27    the model will predict the class along with the confidence level.28    """)29 30# Image upload31file = st.file_uploader('Select an image', type=['jpg', 'jpeg', 'png'])32 33if file is not None:34    img = Image.open(file)35    36    # Display the uploaded image with a border and centered37    st.image(img, caption='Uploaded Image',  38             output_format="PNG", width=400)39 40    # Preprocess the image41    image = process_image(img)42    43    # Model prediction44    with st.spinner('Classifying the image...'):45        predictions = model.predict(image)46        predicted_class = np.argmax(predictions)  47        predicted_prob = predictions[0][predicted_class]  48 49    # Class names for prediction50    class_names = ['Cat','Dog']51 52    # Display the prediction result53    st.subheader(f"Prediction: {class_names[predicted_class]}")54    st.write(f"Confidence: {predicted_prob * 100:.2f}%")55 56    # Display prediction probabilities57    st.write("Prediction Probabilities for Each Class:")58 59    # Prepare probabilities for visualization60    probabilities = predictions[0]61    prob_dict = {class_names[i]: probabilities[i] for i in range(len(class_names))}62    63    # Plot settings64    sns.set(style="whitegrid")  # Use a grid style for the plot65 66    # Create the figure for the bar chart67    fig, ax = plt.subplots(figsize=(10, 6))  # Adjust figure size for better readability68 69    # Plot the bar chart with a brighter color palette70    ax.bar(list(prob_dict.keys()), list(prob_dict.values()), color='#f5a623', edgecolor='black')71    ax.set_ylabel('Probability', fontsize=14, color='black')72    ax.set_title('Prediction Probabilities for Each Class', fontsize=18, color='black')73 74    # Rotate x-axis labels for better readability75    plt.xticks(rotation=45, ha='right', fontsize=12)76 77    # Annotate bars with percentage values78    for index, value in enumerate(prob_dict.values()):79        ax.text(index, value, f'{value * 100:.0f}%', va='bottom', ha='center', fontsize=10)80 81    # Style improvements: Remove background grid and spines82    ax.spines['top'].set_visible(False)83    ax.spines['right'].set_visible(False)84    ax.spines['left'].set_visible(False)85    ax.spines['bottom'].set_visible(False)86    ax.grid(False)87 88    # Adjust layout to prevent clipping89    fig.tight_layout()90 91    # Display the plot in Streamlit92    st.pyplot(fig)93 94