File size: 1,085 Bytes
11c3816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
from keras.applications import MobileNetV2
from keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
from keras.utils import img_to_array
from PIL import Image

# Load pretrained MobileNetV2 (ImageNet weights = transfer learning)
model = MobileNetV2(weights="imagenet")

def predict(image):
    # Resize to 224x224 as required by MobileNetV2
    img = image.resize((224, 224))
    arr = img_to_array(img)
    arr = np.expand_dims(arr, axis=0)       # shape: (1, 224, 224, 3)
    arr = preprocess_input(arr)             # normalize for MobileNetV2

    preds = model.predict(arr)
    top5 = decode_predictions(preds, top=5)[0]  # [(id, label, prob), ...]

    return {label: float(prob) for (_, label, prob) in top5}

demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=gr.Label(num_top_classes=5),
    title="Image Classifier (MobileNetV2 Transfer Learning)",
    description="Upload an image and the model predicts what it is using Keras MobileNetV2 pretrained on ImageNet.",
)

demo.launch()