trs's picture
Update app.py
36e402d verified
Raw History Blame
1.67 kB
def 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 img
img_preprocessed = preprocess_input(img, 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