Senasu's picture
Upload 3 Files
93786b4 verified
import streamlit as st
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
model = load_model('cnn_model.h5')
def process_image(img):
img = img.convert('RGB')
img = img.resize((224, 224))
img = np.array(img)
img = img / 255.0
img = np.expand_dims(img, axis=0)
return img
st.title('Rice Classification :rice_scene:')
st.write('Upload a rice image and the model will detect type of rice.')
file = st.file_uploader('Select an image', type=['jpg', 'jpeg', 'png'])
if file is not None:
# Display the uploaded image
img = Image.open(file)
st.image(img, caption='Uploaded Image')
# Preprocess the image
image = process_image(img)
# Model prediction
with st.spinner('Classifying the image...'):
predictions = model.predict(image)
predicted_class = np.argmax(predictions)
predicted_prob = predictions[0][predicted_class]
# Class names for prediction
class_names = ['Arborio',
'Basmati',
'Ipsala',
'Jasmine',
'Karacadag']
# Display the prediction
st.subheader(f"Prediction: {class_names[predicted_class]}")
st.write(f"Confidence: {predicted_prob * 100:.2f}%")
# Display prediction probabilities
st.write("Prediction Probabilities for Each Class:")
probabilities = predictions[0]
prob_dict = {class_names[i]: probabilities[i] for i in range(len(class_names))}
# Plot settings
sns.set(style="white") # Clean style with no grid background
# Create the figure
fig, ax = plt.subplots(figsize=(12, 8)) # Adjust figure size for better readability
# Plot the bar chart
ax.bar(list(prob_dict.keys()), list(prob_dict.values()), color='#F29F05', edgecolor='black')
ax.set_ylabel('Probability', fontsize=14)
ax.set_title('Prediction Probabilities for Each Class', fontsize=20)
# Rotate x-axis labels for better readability
plt.xticks(rotation=90, ha='right', fontsize=15)
# Annotate bars with percentage values
for index, value in enumerate(prob_dict.values()):
ax.text(index, value, f'{value * 100:.0f}%', va='bottom', ha='center', fontsize=10)
# Remove background grid and spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.grid(False)
# Adjust layout to prevent clipping
fig.tight_layout()
# Display the plot in Streamlit
st.pyplot(fig)