yxong1114's picture
upload app
9b41e0c
import gradio as gr
import cv2
import requests
import gdown
import tensorflow as tf
from tensorflow import keras
import numpy as np
from PIL import Image
from keras.models import load_model
url = 'https://drive.google.com/file/d/1ueGC-MBuVip9jkfLJdfeH-RBy6fjDZ5j/view?usp=sharing'
output_path = 'classes.txt'
gdown.download(url, output_path, quiet=False,fuzzy=True)
with open(output_path,'r') as file:
LABELS = [x.strip() for x in file.readlines()]
num_classes = 200
IMG_SIZE = 128
model = load_model('model.h5')
# Preprocess image
def preprocess(image):
image = image.convert('RGB') # To RGB
image = image.resize((IMG_SIZE, IMG_SIZE)) # Resize the image to 128 x 128
image = np.array(image)
image = tf.keras.applications.mobilenet_v2.preprocess_input(image) # Rescale the pixel to [-1,1] for MobileNetV2
return image
def predict(image):
image = preprocess(image)
image = np.expand_dims(image, axis=0) # Add batch dimension
prediction = model.predict(image) # Predict the image using the trained model
# Get the top 3 predictions
idx = np.argsort(prediction[0])[::-1][:3]
top3_value = np.asarray([prediction[0][i] for i in idx[0:3]])
top3_idx = idx[0:3]
return {LABELS[i]:str(v) for i,v in zip(top3_idx,top3_value)}
# Create Gradio interface
input_image = gr.inputs.Image(type='pil')
output_text = 'label'
app = gr.Interface(fn=predict, inputs=input_image, outputs=output_text)
app.launch()