hb-setosys's picture
Update app.py
7168d1f verified
raw
history blame
1.69 kB
import gradio as gr
import tensorflow as tf
from tensorflow.keras.applications import EfficientNetV2L
from tensorflow.keras.applications.efficientnet_v2 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing.image import img_to_array
from PIL import Image
import numpy as np
# Load the stronger pre-trained model (EfficientNetV2L)
model = EfficientNetV2L(weights="imagenet")
def predict_image(image):
"""
Process the uploaded image and return the top 3 predictions as a dictionary.
"""
try:
# Preprocess the image
image = image.resize((480, 480)) # EfficientNetV2L expects 480x480 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 dictionary (label -> confidence)
results = {label: float(confidence) for _, label, confidence in decoded_predictions}
return 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="EfficientNetV2L Image Classifier",
description="Upload an image, and the model will predict what's in the image with higher accuracy."
)
# Launch the Gradio app
if __name__ == "__main__":
interface.launch()