trs's picture
Update app.py
bb0ce12 verified
Raw History Blame
2.43 kB
import numpy as np
import os
import cv2
import gradio as gr
import onnx
import onnxruntime as ort
import tensorflow as tf
onnx_efficientnet_path = './Models_onnx/efficientnet.onnx'
#onnx_inception_path = './Models_onnx/inceptionv3.onnx'
onnx_vggnet_path = './Models_onnx/vgg_16.onnx'
onnx_resnet_path = './Models_onnx/resnet50.onnx'
# Load ONNX models
#onnx_inception_model = ort.InferenceSession(onnx_inception_path)
onnx_vggnet_model = ort.InferenceSession(onnx_vggnet_path)
onnx_resnet_model = ort.InferenceSession(onnx_resnet_path)
onnx_efficientnet_model = ort.InferenceSession(onnx_efficientnet_path)
class_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]
def classify_image(img, model_choice):
if model_choice == "ResNet":
img = tf.image.resize(img, (150, 150))
img = resnet_preprocess_input(img)
elif model_choice == "EfficientNet":
img = tf.image.resize(img, (150, 150))
img = efficientnet_preprocess_input(img)
elif model_choice == "VGGNet":
img = tf.image.resize(img, (150, 150))
img = vgg_preprocess_input(img)
elif model_choice == "InceptionV3":
img = tf.image.resize(img, (150, 150))
img = inception_preprocess_input(img)
else:
return "Invalid model choice"
img = tf.expand_dims(img, 0)
# Use gr.to_onnx to convert ONNX models to Gradio-compatible format
onnx_models = {
"ResNet": gr.to_onnx(onnx_resnet_model),
"EfficientNet": gr.to_onnx(onnx_efficientnet_model),
"VGGNet": gr.to_onnx(onnx_vggnet_model),
"InceptionV3": gr.to_onnx(onnx_inception_model),
}
onnx_model = onnx_models.get(model_choice)
if onnx_model is None:
return "Invalid model choice"
# Perform inference using the ONNX model
predictions = gr.run(onnx_model, {"input": img})
class_idx = np.argmax(predictions["output"])
# Map class index to class name
class_name = class_names[class_idx]
# Return the predicted class name as a string
return f"Predicted class using {model_choice}: {class_name}"
image_input = gr.Image()
# Create a Gradio interface with a dropdown for model selection
iface = gr.Interface(
fn=classify_image,
inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")],
outputs="text",
live=True
).launch(debug=True)