Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines8910111213141516171819202122232425263 unmodified lines303132333435367 unmodified lines44454647484950515253545556575859604 unmodified lines65666768697071721 unmodified line74757677787980818283848586878889909192935 unmodified lines991001011021031041058 unmodified lines1141151161171187 unmodified linesimport os# Load all four models and scalerlr_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')# Preprocessing function (adapted from your project)def preprocess_image(img):img = img.convert('L').resize((64, 64)) # Convert to grayscale, resize to 64x64img_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 = bboxreturn [3 unmodified linesymax * img_height]# Compute IoU (from your project)def IOU(bbox1, bbox2):x1, y1, x2, y2 = bbox1x1_p, y1_p, x2_p, y2_p = bbox27 unmodified linesunion_area = bbox1_area + bbox2_area - inter_areareturn 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 imageimg_array = preprocess_image(image)img_width, img_height = image.size# Prepare input based on modelif 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 modelmodel = {4 unmodified lines}[model_name]# Make predictionpred = 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 boxpred_bbox_denorm = denormalize_bbox(pred_bbox, img_width, img_height)1 unmodified line# Draw predicted bounding box (red)img_draw = image.copy()draw = ImageDraw.Draw(img_draw)draw.rectangle(pred_bbox_denorm, outline='red', width=2)# Initialize metricsmetrics = ""# If ground truth is provided, draw it (green) and compute metricsif 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, metrics5 unmodified linesgr.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)'),8 unmodified linesdescription='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()7 unmodified lines8910111213141516171819202122232425262728293031323 unmodified lines363738394041427 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384854 unmodified lines909192939495969798991001011021 unmodified line1041051061071081091101111121131141151161171181191201211221231241251261271281291305 unmodified lines1361371381391401411428 unmodified lines1511521531541551567 unmodified linesimport os# Load all four models and scalertry:lr_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')except Exception as e:raise Exception(f"Error loading models or scaler: {str(e)}")# Preprocessing functiondef preprocess_image(img):try:img = img.convert('L').resize((64, 64)) # Convert to grayscale, resize to 64x64img_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)}")# Denormalize bounding boxdef denormalize_bbox(bbox, img_width, img_height):xmin, ymin, xmax, ymax = bboxreturn [3 unmodified linesymax * img_height]# Compute IoUdef IOU(bbox1, bbox2):x1, y1, x2, y2 = bbox1x1_p, y1_p, x2_p, y2_p = bbox27 unmodified linesunion_area = bbox1_area + bbox2_area - inter_areareturn inter_area / union_area if union_area > 0 else 0# Validate and correct bounding boxdef validate_bbox(bbox):# Clip to [0, 1]bbox = np.clip(bbox, 0, 1)# Ensure xmin <= xmax, ymin <= ymaxxmin, ymin, xmax, ymax = bboxxmin, xmax = min(xmin, xmax), max(xmin, xmax)ymin, ymax = min(ymin, ymax), max(ymin, ymax)return np.array([xmin, ymin, xmax, ymax])# Predict and visualizedef 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."# Preprocess imagetry:img_array = preprocess_image(image)img_width, img_height = image.sizeexcept Exception as e:return None, f"Error preprocessing image: {str(e)}"# Prepare inputtry: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)except Exception as e:return None, f"Error preparing input: {str(e)}"# Select modelmodel = {4 unmodified lines}[model_name]# Make predictiontry:pred = model.predict(input_array, verbose=0) if model_name in ['ANN', 'CNN'] else model.predict(input_array)pred_bbox = pred[0] # Shape: (4,)# Validate and correct bounding boxpred_bbox = validate_bbox(pred_bbox)except Exception as e:return None, f"Error during prediction: {str(e)}"# Denormalize predicted bounding boxpred_bbox_denorm = denormalize_bbox(pred_bbox, img_width, img_height)1 unmodified line# Draw predicted bounding box (red)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)}"# Initialize metricsmetrics = ""# If ground truth is provided, draw it (green) and compute metricsif 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) # Validate ground truthgt_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, metrics5 unmodified linesgr.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)'),8 unmodified linesdescription='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 appif __name__ == "__main__":iface.launch(server_name="0.0.0.0", server_port=7860)
app.py+69-31