project2 / app.py
linsan01's picture
Update app.py
e889ec9 verified
import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image
model_path = "Xeption_fruits.keras"
model = tf.keras.models.load_model(model_path)
# Define the core prediction function
def predict_fruit(image):
# Preprocess image
print(type(image))
image = Image.fromarray(image.astype('uint8')) # Convert numpy array to PIL image
image = image.resize((150, 150)) #resize the image to 28x28 and converts it to gray scale
image = np.array(image)
image = np.expand_dims(image, axis=0) # same as image[None, ...]
# Predict
prediction = model.predict(image)
# No need to apply sigmoid, as the output layer already uses softmax
# Convert the probabilities to rounded values
prediction = np.round(prediction, 3)
# Separate the probabilities for each class
p_apple = prediction[0][0] # Probability for class 'articuno'
p_banana = prediction[0][1] # Probability for class 'moltres'
p_pinenapple = prediction[0][2] # Probability for class 'zapdos'
p_strawberries = prediction[0][3]
p_watermelon = prediction[0][4]
return {'apple': p_apple, 'banana': p_banana, 'pinenapple': p_pinenapple, 'strawberries': p_strawberries, 'watermelon': p_watermelon}
# Create the Gradio interface
input_image = gr.Image()
iface = gr.Interface(
fn=predict_fruit,
inputs=input_image,
outputs=gr.Label(),
examples=["images/ap1.jpeg", "images/ap2.jpeg", "images/ap3.jpeg", "images/ba1.jpeg", "images/ba2.jpeg", "images/ba3.jpeg", "images/pi1.jpeg","images/pi2.jpeg","images/pi3.jpeg","images/st1.jpeg", "images/st2.jpeg", "images/st3.jpeg","images/wa1.jpeg","images/wa2.jpeg","images/wa3.jpeg"],
description="FruitFinder")
iface.launch()