Spaces:
Sleeping
Sleeping
Update app.py
Browse files11232 unmodified lines6781091011126 unmodified lines1920212322232425262729282930313 unmodified lines35363739404142434445464748495051525338394041424344454647484950515253545556575558575960616263646365666768676869707172737475757677787879808081828384848586871 unmodified line89909192929394959695969798991001011021031041031041051061 unmodified line1081091101121111121131151141151161191171181191205 unmodified lines126127128131129130131132# 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 scaler# 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)) # Convert to grayscale, resize to 64x64 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)}")
# Denormalize bounding box# Denormalizing the bounding boxdef denormalize_bbox(bbox, img_width, img_height): xmin, ymin, xmax, ymax = bbox return [3 unmodified lines ymax * img_height ]
# Compute IoUdef 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
# Validate and correct bounding box# 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_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 boxdef validate_bbox(bbox): # Clip to [0, 1] bbox = np.clip(bbox, 0, 1) # Ensure xmin <= xmax, ymin <= ymax # 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])
# Predict and visualize# 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."
# Preprocess image try: img_array = preprocess_image(image) img_width, img_height = image.size except Exception as e: return None, f"Error preprocessing image: {str(e)}"
# Prepare input # Preparing input try: if model_name == 'CNN': input_array = img_array[np.newaxis, ...] # Shape: (1, 64, 64, 1) input_array = img_array[np.newaxis, ...] else: input_array = scaler.transform(img_array.flatten()[np.newaxis, ...]) # Shape: (1, 4096) input_array = scaler.transform(img_array.flatten()[np.newaxis, ...]) except Exception as e: return None, f"Error preparing input: {str(e)}"
# Select model # Model Selection model = { 'Linear Regression': lr_model, 'SVM': svm_model,1 unmodified line 'CNN': cnn_model }[model_name]
# Make prediction # Prediction try: 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 box 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)
# Draw predicted bounding box (red)= img_draw = image.copy() draw = ImageDraw.Draw(img_draw) try:1 unmodified line except Exception as e: return None, f"Error drawing predicted box: {str(e)}"
# Initialize metrics # 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]): 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 truth 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 lines
return img_draw, metrics
# Define Gradio interface# Gradio interfaceiface = gr.Interface( fn=predict_and_visualize, inputs=[app.py+35-37