Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from tensorflow.keras.applications import ResNet152, preprocess_input, decode_predictions
|
| 4 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
# Load the pre-trained ResNet152 model
|
| 9 |
+
MODEL_PATH = "resnet152-image-classifier" # Directory where the model is saved
|
| 10 |
+
model = tf.keras.models.load_model(MODEL_PATH)
|
| 11 |
+
|
| 12 |
+
def predict_image(image):
|
| 13 |
+
"""
|
| 14 |
+
This function processes the uploaded image and returns the top 3 predictions.
|
| 15 |
+
"""
|
| 16 |
+
# Preprocess the image
|
| 17 |
+
image = image.resize((224, 224)) # ResNet152 expects 224x224 input
|
| 18 |
+
image_array = img_to_array(image)
|
| 19 |
+
image_array = preprocess_input(image_array) # Normalize the image
|
| 20 |
+
image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
|
| 21 |
+
|
| 22 |
+
# Get predictions
|
| 23 |
+
predictions = model.predict(image_array)
|
| 24 |
+
decoded_predictions = decode_predictions(predictions, top=3)[0]
|
| 25 |
+
|
| 26 |
+
# Format predictions as a dictionary
|
| 27 |
+
results = {label: f"{confidence * 100:.2f}%" for _, label, confidence in decoded_predictions}
|
| 28 |
+
return results
|
| 29 |
+
|
| 30 |
+
# Create the Gradio interface
|
| 31 |
+
interface = gr.Interface(
|
| 32 |
+
fn=predict_image,
|
| 33 |
+
inputs=gr.Image(type="pil"), # Accepts an image input
|
| 34 |
+
outputs=gr.Label(num_top_classes=3), # Shows top 3 predictions with confidence
|
| 35 |
+
title="ResNet152 Image Classifier",
|
| 36 |
+
description="Upload an image, and the model will predict what's in the image.",
|
| 37 |
+
examples=["dog.jpg", "cat.jpg"], # Example images for users to test
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Launch the Gradio app
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
interface.launch()
|