Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from keras.models import load_model # TensorFlow is required for Keras to work | |
| from PIL import Image, ImageOps # Install pillow instead of PIL | |
| import numpy as np | |
| # Load the model | |
| model = load_model("keras_model.h5", compile=False) | |
| # Load the labels | |
| class_names = open("labels.txt", "r").readlines() | |
| # Define the prediction function | |
| def classify_image(image): | |
| # Resize the image to 224x224 and normalize | |
| size = (224, 224) | |
| image = ImageOps.fit(image, size, Image.Resampling.LANCZOS).convert("RGB") | |
| image_array = np.asarray(image) | |
| normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 | |
| data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) | |
| data[0] = normalized_image_array | |
| # Predict with the model | |
| prediction = model.predict(data) | |
| index = np.argmax(prediction) | |
| class_name = class_names[index].strip() # Remove any trailing spaces or newline characters | |
| confidence_score = prediction[0][index] | |
| return f"{class_name}, Confidence Score: {float(confidence_score)}" | |
| # Create the Gradio interface | |
| interface = gr.Interface( | |
| fn = classify_image, | |
| inputs = gr.Image(type="pil"), # Accepts an image as input | |
| outputs = [ | |
| gr.Label(label="Prediction"), # Class name and confidence score as a labeled output | |
| ], | |
| title = "Image Classifier", | |
| description = "Upload an image, and the model will classify it into one of the predefined classes." | |
| ) | |
| # Launch the Gradio app | |
| interface.launch() |