Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines891011111213141512131415161718191720212219202123242526272823293031323 unmodified lines36373833394041427 unmodified lines50515247535455565758596061626364656667686950517071727374755354555657767778798081828384854 unmodified lines9091929368699495969798991001011021 unmodified line10410510610777108109110111112113114115116117118848586878889901191201211221231241251261271281291305 unmodified lines1361371381021391401411428 unmodified lines1511521531541551181567 unmodified linesimport os
# Load all four models and scalertry: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') 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 function (adapted from your project)# Preprocessing functiondef preprocess_image(img): try: 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) 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) except Exception as e: raise Exception(f"Error preprocessing image: {str(e)}")
# Denormalize bounding box (from your project)# Denormalize bounding boxdef denormalize_bbox(bbox, img_width, img_height): xmin, ymin, xmax, ymax = bbox return [3 unmodified lines ymax * img_height ]
# Compute IoU (from your project)# Compute IoUdef IOU(bbox1, bbox2): x1, y1, x2, y2 = bbox1 x1_p, y1_p, x2_p, y2_p = bbox27 unmodified lines union_area = bbox1_area + bbox2_area - inter_area return inter_area / union_area if union_area > 0 else 0
# Predict and visualize bounding box# Validate and correct bounding boxdef validate_bbox(bbox): # Clip to [0, 1] bbox = np.clip(bbox, 0, 1) # Ensure 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 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 image try: img_array = preprocess_image(image) img_width, img_height = image.size 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 # 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) try: 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 model model = {4 unmodified lines }[model_name]
# Make 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,) for [xmin, ymin, xmax, ymax] 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 = 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)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) draw.rectangle(pred_bbox_denorm, outline='red', width=2) except Exception as e: return None, f"Error drawing predicted box: {str(e)}"
# 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]): try: gt_bbox = np.array([gt_xmin / img_width, gt_ymin / img_height, gt_xmax / img_width, gt_ymax / img_height]) 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}" gt_bbox = validate_bbox(gt_bbox) # Validate ground truth 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
5 unmodified lines gr.Dropdown( choices=['Linear Regression', 'SVM', 'ANN', 'CNN'], label='Select Model', value='CNN' # Default to CNN value='CNN' ), gr.Number(label='Ground Truth Xmin (optional, in pixels)'), gr.Number(label='Ground Truth Ymin (optional, in pixels)'),8 unmodified lines 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 appif __name__ == "__main__": iface.launch() iface.launch(server_name="0.0.0.0", server_port=7860)app.py+69-31