Senasu's picture
Update app.py
dcf58ee 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((64, 64))
img = np.array(img)
img = img / 255.0
img = np.expand_dims(img, axis=0)
return img
st.title('Fruits and Vegetables Image Recognition :grapes: :carrot: :kiwifruit: :broccoli:')
st.write('Upload a vegetable or fruit image and the model will recognize it.')
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 = ['capsicum',
'sweetcorn',
'orange',
'tomato',
'turnip',
'ginger',
'raddish',
'pomegranate',
'pineapple',
'jalepeno',
'apple',
'carrot',
'lettuce',
'bell pepper',
'eggplant',
'beetroot',
'kiwi',
'pear',
'cabbage',
'cauliflower',
'paprika',
'lemon',
'sweetpotato',
'grapes',
'cucumber',
'corn',
'banana',
'garlic',
'chilli pepper',
'watermelon',
'mango',
'peas',
'onion',
'potato',
'spinach',
'soy beans']
# 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='#197339', 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)