File size: 2,398 Bytes
9fcad62 b42a3d4 9fcad62 b42a3d4 9fcad62 b42a3d4 9fcad62 b42a3d4 ef6526f b42a3d4 9fcad62 b42a3d4 9fcad62 9aea5dd b42a3d4 9fcad62 ef6526f 9fcad62 ef6526f 9fcad62 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import gradio as gr
import tensorflow as tf
from tensorflow.keras.applications.resnet import ResNet152, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing.image import img_to_array
from PIL import Image
import numpy as np
# Load the pre-trained ResNet152 model
MODEL_PATH = "resnet152-image-classifier.h5" # Path to the saved model
try:
model = tf.keras.models.load_model(MODEL_PATH)
except Exception as e:
print(f"Error loading model: {e}")
exit()
def predict_image(image):
"""
Process the uploaded image and return the top 3 predictions.
"""
try:
# Decode the base64 image string back to a PIL.Image object
image_data = base64.b64decode(image)
image = Image.open(BytesIO(image_data))
image = image.convert("RGB") # Ensure RGB format
# Preprocess the image
image = image.resize((224, 224)) # ResNet152 expects 224x224 input
image_array = img_to_array(image)
image_array = preprocess_input(image_array) # Normalize the image
image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
# Get predictions
predictions = model.predict(image_array)
decoded_predictions = decode_predictions(predictions, top=3)[0]
# Format predictions as a list of tuples (label, confidence)
results = [(label, float(confidence)) for _, label, confidence in decoded_predictions]
return dict(results)
except Exception as e:
return {"Error": str(e)}
# Create the Gradio interface
"""
interface = gr.Interface(
fn=predict_image,
inputs=gr.Image(type="pil"), # Accepts an image input
outputs=gr.Label(num_top_classes=3), # Shows top 3 predictions with confidence
title="ResNet152 Image Classifier",
description="Upload an image, and the model will predict what's in the image.",
examples=["dog.jpg", "cat.jpg"], # Example images for users to test
)
"""
interface = gr.Interface(
fn=predict_image,
inputs=gr.Textbox(label="Base64 Image String"), # Accepts base64-encoded string
outputs=gr.Label(num_top_classes=3), # Shows top 3 predictions with confidence
title="ResNet152 Image Classifier",
description="Upload an image as a Base64 string, and the model will predict what's in the image.",
)
# Launch the Gradio app
if __name__ == "__main__":
interface.launch()
|