import gradio as gr import tensorflow as tf import numpy as np from PIL import Image model_path = "Cat_transfer_learning_MobileNetV2.keras" model = tf.keras.models.load_model(model_path) # Define the core prediction function def predict_cat(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_americanshorthair = prediction[0][0] # Probability for class 'articuno' p_bengal = prediction[0][1] # Probability for class 'moltres' p_mainecoon = prediction[0][2] # Probability for class 'zapdos' p_ragdoll = prediction[0][3] # Probability for class 'zapdos' p_scottishfold = prediction[0][4] p_sphinx = prediction[0][5] return {'americanshorthair': p_americanshorthair, 'bengal': p_bengal, 'mainecoon': p_mainecoon, 'ragdoll': p_ragdoll, 'scottishfold': p_scottishfold, 'sphinx': p_sphinx } # Create the Gradio interface input_image = gr.Image() iface = gr.Interface( fn=predict_cat, inputs=input_image, outputs=gr.Label(), examples=["images/americanshorthair_1.jpg", "images/americanshorthair_2.jpg", "images/americanshorthair_3.jpg", "images/bengal_1.jpg", "images/bengal_2.jpeg", "images/bengal_3.jpg", "images/mainecoon_1.jpg", "images/mainecoon_2.jpeg", "images/mainecoon_3.jpg", "images/ragdoll_1.jpg", "images/ragdoll_2.jpg", "images/ragdoll_3.jpeg", "images/scottishfold_1.jpeg", "images/scottishfold_2.jpg", "images/scottishfold_3.jpg", "images/sphinx_1.jpg", "images/sphinx_2.jpg", "images/sphinx_3.jpg"], description="Let's predict some cats!") iface.launch()