Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from keras.applications import MobileNetV2
|
| 4 |
+
from keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
|
| 5 |
+
from keras.utils import img_to_array
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
# Load pretrained MobileNetV2 (ImageNet weights = transfer learning)
|
| 9 |
+
model = MobileNetV2(weights="imagenet")
|
| 10 |
+
|
| 11 |
+
def predict(image):
|
| 12 |
+
# Resize to 224x224 as required by MobileNetV2
|
| 13 |
+
img = image.resize((224, 224))
|
| 14 |
+
arr = img_to_array(img)
|
| 15 |
+
arr = np.expand_dims(arr, axis=0) # shape: (1, 224, 224, 3)
|
| 16 |
+
arr = preprocess_input(arr) # normalize for MobileNetV2
|
| 17 |
+
|
| 18 |
+
preds = model.predict(arr)
|
| 19 |
+
top5 = decode_predictions(preds, top=5)[0] # [(id, label, prob), ...]
|
| 20 |
+
|
| 21 |
+
return {label: float(prob) for (_, label, prob) in top5}
|
| 22 |
+
|
| 23 |
+
demo = gr.Interface(
|
| 24 |
+
fn=predict,
|
| 25 |
+
inputs=gr.Image(type="pil"),
|
| 26 |
+
outputs=gr.Label(num_top_classes=5),
|
| 27 |
+
title="Image Classifier (MobileNetV2 Transfer Learning)",
|
| 28 |
+
description="Upload an image and the model predicts what it is using Keras MobileNetV2 pretrained on ImageNet.",
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
demo.launch()
|