Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import onnxruntime as ortimport onnximport numpy as npimport gradio as grimport cv2# Load ONNX modelsonnx_inception_model = ort.InferenceSession('./Models_onnx/inceptionv3.onnx')onnx_vggnet_model = ort.InferenceSession('./Models_onnx/vgg_16.onnx')onnx_resnet_model = ort.InferenceSession('./Models_onnx/resnet50.onnx')onnx_efficientnet_model = ort.InferenceSession('./Models_onnx/efficientnet.onnx')class_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]def preprocess_input(img):img = cv2.imread(img)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = cv2.resize(img, (150, 150))img = img.astype(np.float32) / 255.0img = np.expand_dims(img, axis=0)return imgdef classify_image(img, model_choice):# Run inference based on the selected modelmodel = {"InceptionV3": onnx_inception_model,"VGGNet": onnx_vggnet_model,"ResNet": onnx_resnet_model,"EfficientNet": onnx_efficientnet_model,}.get(model_choice)if model is None:return {"Error": f"Model {model_choice} not found"}# Check if the input is a Gradio Image objectif isinstance(img, gr.Image):# Get the image file path from the Gradio Image objectimg_path = img.filepathelse:# Assume the input is already a file pathimg_path = imgimg_preprocessed = preprocess_input(img_path)input_name = model.get_inputs()[0].nameoutput_name = model.get_outputs()[0].nametry:predictions = model.run(None, {input_name: img_preprocessed})class_idx = np.argmax(predictions[0][0])class_name = class_names[class_idx]confidence_score = round(predictions[0, class_idx] * 100, 2)result = {"Predicted class": class_name, "Confidence Score": confidence_score}except Exception as e:result = {"Error": str(e)}return resultimage_input = gr.Image()# Create a Gradio interface with a dropdown for model selectioniface = gr.Interface(fn=classify_image,inputs=[image_input, gr.Dropdown(["InceptionV3", "VGGNet", "ResNet", "EfficientNet"], label="Select Model")],outputs="label",title='Image Classification',live=True)iface.launch(share=True, debug=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import torchimport torchvision.transforms as transformsfrom PIL import Imageimport gradio as gr# Load your PyTorch InceptionV3 modelmodel_path = "Image_Classification_with_pre-traind_Models/inceptionv3_-saved-model-59-val_accuracy-0.94.hdf5" # Update with your model pathmodel = torch.load(model_path, map_location=torch.device('cpu'))model.eval()# Load the image transformertransform = transforms.Compose([transforms.Resize((150, 150)),transforms.ToTensor(),])# Define class names corresponding to your datasetclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]# Define the classify_image functiondef classify_image(img):# Preprocess the imageimg = Image.fromarray((img * 255).astype('uint8')) # Assuming img is a NumPy arrayimg = transform(img)img = img.unsqueeze(0) # Add batch dimension# Make predictions using the PyTorch modelwith torch.no_grad():logits = model(img)# Get predicted class indexclass_idx = torch.argmax(logits[0]).item()# Map class index to class nameclass_name = class_names[class_idx]# Return the predicted class name as a stringreturn f"Predicted class: {class_name}"# Create a Gradio interfaceiface = gr.Interface(fn=classify_image,inputs=["image"],outputs="text",live=True)# Launch the Gradio interfaceiface.launch(share=True,debug=True)
app.py+34-54