|
import gradio as gr |
|
import tensorflow as tf |
|
from tensorflow.keras.applications import ResNet152, preprocess_input, decode_predictions |
|
from tensorflow.keras.preprocessing.image import img_to_array |
|
from PIL import Image |
|
import numpy as np |
|
|
|
|
|
MODEL_PATH = "resnet152-image-classifier" |
|
model = tf.keras.models.load_model(MODEL_PATH) |
|
|
|
def predict_image(image): |
|
""" |
|
This function processes the uploaded image and returns the top 3 predictions. |
|
""" |
|
|
|
image = image.resize((224, 224)) |
|
image_array = img_to_array(image) |
|
image_array = preprocess_input(image_array) |
|
image_array = np.expand_dims(image_array, axis=0) |
|
|
|
|
|
predictions = model.predict(image_array) |
|
decoded_predictions = decode_predictions(predictions, top=3)[0] |
|
|
|
|
|
results = {label: f"{confidence * 100:.2f}%" for _, label, confidence in decoded_predictions} |
|
return results |
|
|
|
|
|
interface = gr.Interface( |
|
fn=predict_image, |
|
inputs=gr.Image(type="pil"), |
|
outputs=gr.Label(num_top_classes=3), |
|
title="ResNet152 Image Classifier", |
|
description="Upload an image, and the model will predict what's in the image.", |
|
examples=["dog.jpg", "cat.jpg"], |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
interface.launch() |
|
|