Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118# app.pyimport gradio as grimport numpy as npfrom PIL import Image, ImageDrawimport joblibfrom sklearn.metrics import mean_squared_error, mean_absolute_errorfrom tensorflow.keras.models import load_modelimport os
# Load all four models and scalerlr_model = joblib.load('models/lr_model.pkl')svm_model = joblib.load('models/svm_model.pkl')ann_model = load_model('models/ann_model.h5')cnn_model = load_model('models/cnn_model.h5')scaler = joblib.load('models/scaler.pkl')
# Preprocessing function (adapted from your project)def preprocess_image(img): img = img.convert('L').resize((64, 64)) # Convert 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)
# Denormalize bounding box (from your project)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 ]
# Compute IoU (from your project)def IOU(bbox1, bbox2): x1, y1, x2, y2 = bbox1 x1_p, y1_p, x2_p, y2_p = bbox2 xi1 = max(x1, x1_p) yi1 = max(y1, y1_p) xi2 = min(x2, x2_p) yi2 = min(y2, y2_p) inter_area = max(0, xi2 - xi1) * max(0, yi2 - yi1) bbox1_area = (x2 - x1) * (y2 - y1) bbox2_area = (x2_p - x1_p) * (y2_p - y1_p) union_area = bbox1_area + bbox2_area - inter_area return inter_area / union_area if union_area > 0 else 0
# Predict and visualize bounding boxdef predict_and_visualize(image, model_name, gt_xmin=None, gt_ymin=None, gt_xmax=None, gt_ymax=None): # Preprocess image img_array = preprocess_image(image) img_width, img_height = image.size
# Prepare input based on model if model_name == 'CNN': input_array = img_array[np.newaxis, ...] # Shape: (1, 64, 64, 1) else: input_array = scaler.transform(img_array.flatten()[np.newaxis, ...]) # Shape: (1, 4096)
# Select model model = { 'Linear Regression': lr_model, 'SVM': svm_model, 'ANN': ann_model, 'CNN': cnn_model }[model_name]
# Make prediction pred = model.predict(input_array, verbose=0) if model_name in ['ANN', 'CNN'] else model.predict(input_array) pred_bbox = pred[0] # Shape: (4,) for [xmin, ymin, xmax, ymax]
# Denormalize predicted bounding box pred_bbox_denorm = denormalize_bbox(pred_bbox, img_width, img_height)
# Draw predicted bounding box (red) img_draw = image.copy() draw = ImageDraw.Draw(img_draw) draw.rectangle(pred_bbox_denorm, outline='red', width=2)
# Initialize metrics metrics = ""
# If ground truth is provided, draw it (green) and compute metrics if all(v is not None for v in [gt_xmin, gt_ymin, gt_xmax, gt_ymax]): gt_bbox = np.array([gt_xmin / img_width, gt_ymin / img_height, gt_xmax / img_width, gt_ymax / img_height]) 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}"
return img_draw, metrics
# Define Gradio interfaceiface = 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' # Default to 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.')
if __name__ == "__main__": iface.launch()app.pyAdded+118