Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456781234510678910111213141516171819202122232425131415161718192021222324252627282930313233343536373839404142262728293031323334353637383940414243444546def classify_image(img, model_choice): def preprocess_input(img, model): img = cv2.imread(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (150, 150)) img = img.astype(np.float32) / 255.0 img = np.expand_dims(img, axis=0) return imgimport onnxruntime as ortimport gradio as grimport numpy as npimport cv2
img_preprocessed = preprocess_input(img, model_choice)# Define model pathsmodel_paths = { "ResNet": "./Models_onnx/resnet50.onnx", "EfficientNet": "./Models_onnx/efficientnet.onnx", "VGGNet": "./Models_onnx/vgg_16.onnx", # Add more models as needed}
class_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]
def preprocess_input(img_path): img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (150, 150)) img = img.astype(np.float32) / 255.0 img = np.expand_dims(img, axis=0) return img
def classify_image(img_path, model_choice): # Run inference based on the selected model model = { "ResNet": onnx_resnet_model, "EfficientNet": onnx_efficientnet_model, "VGGNet": onnx_vggnet_model, # "InceptionV3": onnx_inception_model # Uncomment or remove based on your needs }[model_choice]
input_name = model.get_inputs()[0].name try: predictions = model.run(None, {input_name: img_preprocessed}) class_idx = np.argmax(predictions) class_name = class_names[class_idx]
# Get the top 3 predictions top_predictions = sorted(enumerate(predictions[0]), key=lambda x: x[1], reverse=True)[:3] top_classes = [class_names[idx] for idx, _ in top_predictions] top_probs = [round(prob * 100, 2) for _, prob in top_predictions]
result = { "Original Image": img.tolist(), # Convert to list for compatibility with Gradio # Assuming img_resized was meant to be img_preprocessed "Resized Image": img_preprocessed.tolist(), f"Predicted class using {model_choice}": class_name, "Top 3 Predictions": list(zip(top_classes, top_probs)), "Confidence Scores": predictions[0].tolist() } except Exception as e: result = {"Error": str(e)}
return result onnx_model = ort.InferenceSession(model_paths[model_choice]) input_name = onnx_model.get_inputs()[0].name
img_preprocessed = preprocess_input(img_path) predictions = onnx_model.run(None, {input_name: img_preprocessed}) class_idx = np.argmax(predictions) class_name = class_names[class_idx]
return class_name
# Create Gradio interfaceiface = gr.Interface( fn=classify_image, inputs=[gr.Image(), gr.Dropdown(list(model_paths.keys()), label="Select Model")], outputs="text", live=True)
# Launch the interfaceiface.launch()app.py+43-39