import gradio as gr import numpy as np from PIL import Image, ImageDraw import joblib from sklearn.metrics import mean_squared_error, mean_absolute_error from tensorflow.keras.models import load_model import os # Model Loading try: lr_model = joblib.load('lr_model.pkl') svm_model = joblib.load('svm_model.pkl') ann_model = load_model('ann_model.h5') cnn_model = load_model('cnn_model.h5') scaler = joblib.load('scaler.pkl') except Exception as e: raise Exception(f"Error loading models or scaler: {str(e)}") # Preprocessing function def preprocess_image(img): try: img = img.convert('L').resize((64, 64)) # Converting to grayscale & resize to 64x64 img_array = np.array(img) / 255.0 # Normalize to [0, 1] return img_array[..., np.newaxis] # Shape: (64, 64, 1) except Exception as e: raise Exception(f"Error preprocessing image: {str(e)}") # Denormalizing the bounding box def denormalize_bbox(bbox, img_width, img_height): xmin, ymin, xmax, ymax = bbox return [ xmin * img_width, ymin * img_height, xmax * img_width, ymax * img_height ] # IoU def IOU(actual_bbox, pred_bbox2): '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity''' bbox1 = actual_bbox bbox2 = pred_bbox2 x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3] x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3] w_I = min(x1 + w1, x2 + w2) - max(x1, x2) h_I = min(y1 + h1, y2 + h2) - max(y1, y2) if w_I <= 0 or h_I <= 0: # no overlap return 0 I = w_I * h_I U = w1 * h1 + w2 * h2 - I return I / U # Validating and correcting the bounding box def validate_bbox(bbox): bbox = np.clip(bbox, 0, 1) # checking xmin <= xmax, ymin <= ymax xmin, ymin, xmax, ymax = bbox xmin, xmax = min(xmin, xmax), max(xmin, xmax) ymin, ymax = min(ymin, ymax), max(ymin, ymax) return np.array([xmin, ymin, xmax, ymax]) # Predicting and visualizing def predict_and_visualize(image, model_name, gt_xmin=None, gt_ymin=None, gt_xmax=None, gt_ymax=None): if image is None: return None, "Error: No image provided." try: img_array = preprocess_image(image) img_width, img_height = image.size except Exception as e: return None, f"Error preprocessing image: {str(e)}" # Preparing input try: if model_name == 'CNN': input_array = img_array[np.newaxis, ...] else: input_array = scaler.transform(img_array.flatten()[np.newaxis, ...]) except Exception as e: return None, f"Error preparing input: {str(e)}" # Model Selection model = { 'Linear Regression': lr_model, 'SVM': svm_model, 'ANN': ann_model, 'CNN': cnn_model }[model_name] # Prediction try: pred = model.predict(input_array, verbose=0) if model_name in ['ANN', 'CNN'] else model.predict(input_array) pred_bbox = pred[0] # Validating & correcting the bounding box pred_bbox = validate_bbox(pred_bbox) except Exception as e: return None, f"Error during prediction: {str(e)}" # Denormalize predicted bounding box pred_bbox_denorm = denormalize_bbox(pred_bbox, img_width, img_height) img_draw = image.copy() draw = ImageDraw.Draw(img_draw) try: draw.rectangle(pred_bbox_denorm, outline='red', width=2) except Exception as e: return None, f"Error drawing predicted box: {str(e)}" # metrics metrics = "" if all(v is not None for v in [gt_xmin, gt_ymin, gt_xmax, gt_ymax]): try: gt_bbox = np.array([gt_xmin / img_width, gt_ymin / img_height, gt_xmax / img_width, gt_ymax / img_height]) gt_bbox = validate_bbox(gt_bbox) gt_bbox_denorm = denormalize_bbox(gt_bbox, img_width, img_height) draw.rectangle(gt_bbox_denorm, outline='green', width=2) iou = IOU(gt_bbox_denorm, pred_bbox_denorm) mse = mean_squared_error(gt_bbox, pred_bbox) mae = mean_absolute_error(gt_bbox, pred_bbox) metrics = f"IoU: {iou:.4f}\nMSE: {mse:.4f}\nMAE: {mae:.4f}" except Exception as e: metrics = f"Error computing metrics: {str(e)}" return img_draw, metrics # Gradio interface iface = gr.Interface( fn=predict_and_visualize, inputs=[ gr.Image(type='pil', label='Upload Image'), gr.Dropdown( choices=['Linear Regression', 'SVM', 'ANN', 'CNN'], label='Select Model', value='CNN' ), gr.Number(label='Ground Truth Xmin (optional, in pixels)'), gr.Number(label='Ground Truth Ymin (optional, in pixels)'), gr.Number(label='Ground Truth Xmax (optional, in pixels)'), gr.Number(label='Ground Truth Ymax (optional, in pixels)') ], outputs=[ gr.Image(type='pil', label='Image with Bounding Box (Red: Predicted, Green: Ground Truth)'), gr.Textbox(label='Metrics (IoU, MSE, MAE) if Ground Truth Provided') ], title='Bounding Box Prediction Web App', description='Upload an image and select a model (Linear Regression, SVM, ANN, or CNN) to predict a bounding box. Optionally provide ground truth coordinates (in pixels) to see the ground truth box and evaluation metrics.' ) # Launch the app if __name__ == "__main__": iface.launch(server_name="0.0.0.0", server_port=7860)