Spaces:
Runtime error
Runtime error
Download app.py from trs/Image_Classification_with_pre-traind_Models: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/trs/Image_Classification_with_pre-traind_Models/resolve/36e402d8d5b03bc3cf2131e130c4a1b080a21c9e/app.py
- Command line
-
hf download hf://spaces/trs/Image_Classification_with_pre-traind_Models@36e402d8d5b03bc3cf2131e130c4a1b080a21c9e/app.py
-
curl -L -o app.py https://huggingface.co/spaces/trs/Image_Classification_with_pre-traind_Models/resolve/36e402d8d5b03bc3cf2131e130c4a1b080a21c9e/app.py
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 | |