Spaces:
Sleeping
Sleeping
Update app.py
Browse files12342 unmodified lines789101112136 unmodified lines202122232425262728293031323 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586871 unmodified line89909192939495969798991001011021031041051061071 unmodified line1091101111121131141151161171181191201211225 unmodified lines128129130131132133134# app.pyimport gradio as grimport numpy as npfrom PIL import Image, ImageDraw2 unmodified linesfrom tensorflow.keras.models import load_modelimport os# Load all four models and scalertry:lr_model = joblib.load('lr_model.pkl')svm_model = joblib.load('svm_model.pkl')6 unmodified lines# 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 = bbox2xi1 = 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_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 = {'Linear Regression': lr_model,'SVM': svm_model,1 unmodified line'CNN': cnn_model}[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)# Draw predicted bounding box (red)img_draw = image.copy()draw = ImageDraw.Draw(img_draw)try:1 unmodified lineexcept 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)5 unmodified linesreturn img_draw, metrics# Define Gradio interfaceiface = gr.Interface(fn=predict_and_visualize,inputs=[1232 unmodified lines67891011126 unmodified lines192021222324252627282930313 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586871 unmodified line89909192939495969798991001011021031041051061 unmodified line1081091101111121131141151161171181191205 unmodified lines126127128129130131132import gradio as grimport numpy as npfrom PIL import Image, ImageDraw2 unmodified linesfrom tensorflow.keras.models import load_modelimport os# Model Loadingtry:lr_model = joblib.load('lr_model.pkl')svm_model = joblib.load('svm_model.pkl')6 unmodified lines# Preprocessing functiondef preprocess_image(img):try:img = img.convert('L').resize((64, 64)) # Converting 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)}")# Denormalizing the bounding boxdef denormalize_bbox(bbox, img_width, img_height):xmin, ymin, xmax, ymax = bboxreturn [3 unmodified linesymax * img_height]# IoUdef 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_bboxbbox2 = pred_bbox2x1, 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 overlapreturn 0I = w_I * h_IU = w1 * h1 + w2 * h2 - Ireturn I / U# Validating and correcting the bounding boxdef validate_bbox(bbox):bbox = np.clip(bbox, 0, 1)# checking 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])# Predicting and visualizingdef 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.sizeexcept Exception as e:return None, f"Error preprocessing image: {str(e)}"# Preparing inputtry: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 Selectionmodel = {'Linear Regression': lr_model,'SVM': svm_model,1 unmodified line'CNN': cnn_model}[model_name]# Predictiontry: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 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)=img_draw = image.copy()draw = ImageDraw.Draw(img_draw)try:1 unmodified lineexcept Exception as e:return None, f"Error drawing predicted box: {str(e)}"# metricsmetrics = ""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)5 unmodified linesreturn img_draw, metrics# Gradio interfaceiface = gr.Interface(fn=predict_and_visualize,inputs=[
app.py+35-37