Spaces:
Sleeping
Sleeping
Download src/eval_sam2_enhanced.py from amitaddi/btxrd-workstation: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/amitaddi/btxrd-workstation/resolve/main/src/eval_sam2_enhanced.py
- Command line
-
hf download hf://spaces/amitaddi/btxrd-workstation/src/eval_sam2_enhanced.py
-
curl -L -o eval_sam2_enhanced.py https://huggingface.co/spaces/amitaddi/btxrd-workstation/resolve/main/src/eval_sam2_enhanced.py
12.2 kB
| """ | |
| Enhanced SAM2 Evaluation with All Improvement Strategies. | |
| Combines: | |
| 1. Larger SAM2 model (sam2_hiera_large / base_plus) | |
| 2. Bounding box padding (15% expansion) | |
| 3. Iterative mask refinement (3 passes) | |
| 4. Multi-scale inference + fusion (1024, 1536, 2048) | |
| 5. CRF + morphological post-processing | |
| Includes ablation mode to measure each strategy's contribution. | |
| Usage: | |
| python -m src.eval_sam2_enhanced --project_root . --variant sam2_hiera_large | |
| python -m src.eval_sam2_enhanced --project_root . --ablation | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import argparse | |
| import numpy as np | |
| from datetime import datetime | |
| from pathlib import Path | |
| from tqdm import tqdm | |
| import cv2 | |
| import torch | |
| from src.data.dataset import BTXRDSAMDataset | |
| from src.models.sam2_wrapper import SAM2Wrapper, SAM2_AVAILABLE | |
| from src.models.postprocessing import refine_mask, morphological_refine | |
| from src.metrics import compute_all_metrics, aggregate_metrics | |
| CLASS_NAMES = [ | |
| 'Giant Cell Tumor', 'Multiple Osteochondromas', 'Osteochondroma', | |
| 'Osteofibroma', 'Osteosarcoma', 'Other BT', 'Other MT', | |
| 'Simple Bone Cyst', 'Synovial Osteochondroma' | |
| ] | |
| def evaluate_enhanced(wrapper: SAM2Wrapper, | |
| dataset: BTXRDSAMDataset, | |
| mode: str = 'full', | |
| max_samples: int = None, | |
| iterations: int = 3, | |
| use_multiscale: bool = True, | |
| use_crf: bool = True, | |
| use_morphology: bool = True, | |
| scales: list = None, | |
| box_blend_alpha: float = 0.0) -> dict: | |
| """ | |
| Evaluate SAM2 with enhanced strategies. | |
| Args: | |
| wrapper: SAM2Wrapper instance | |
| dataset: BTXRDSAMDataset with expand_ratio already set | |
| mode: 'full' (all strategies), 'iterative_only', 'multiscale_only', | |
| 'postprocess_only', 'box_only' (baseline with padding) | |
| max_samples: Limit evaluation | |
| iterations: Iterative refinement passes | |
| use_multiscale: Enable multi-scale inference | |
| use_crf: Enable CRF post-processing | |
| use_morphology: Enable morphological cleanup | |
| scales: Multi-scale target sizes | |
| Returns: | |
| Dict with per-sample and aggregated metrics | |
| """ | |
| per_sample_metrics = [] | |
| per_class_metrics = {i: [] for i in range(9)} | |
| n_samples = len(dataset) if max_samples is None else min(max_samples, len(dataset)) | |
| for idx in tqdm(range(n_samples), desc=f"Evaluating [{mode}]"): | |
| image, prompts, gt_mask, metadata = dataset[idx] | |
| # Process each object in the image | |
| pred_masks = [] | |
| obj_scores = [] | |
| for prompt in prompts: | |
| box = prompt['box'] | |
| if use_multiscale and mode in ('full', 'multiscale_only'): | |
| # Multi-scale inference (includes iterative refinement internally) | |
| mask, score = wrapper.predict_multiscale_box( | |
| image, box, scales=scales, iterations=iterations | |
| ) | |
| elif mode in ('full', 'iterative_only'): | |
| # Iterative refinement only | |
| wrapper.set_image(image) | |
| mask, score = wrapper.predict_iterative_box(box, iterations=iterations) | |
| else: | |
| # Simple box prompt (baseline with padding) | |
| wrapper.set_image(image) | |
| mask, score = wrapper.predict_with_box(box) | |
| # Post-processing | |
| if mode in ('full', 'postprocess_only'): | |
| mask = refine_mask(image, mask, use_crf=use_crf, use_morphology=use_morphology, box=box, box_blend_alpha=box_blend_alpha) | |
| pred_masks.append(mask) | |
| obj_scores.append(score) | |
| # Combine per-object masks | |
| pred_combined = wrapper.combine_masks( | |
| [{'mask': m, 'score': s} for m, s in zip(pred_masks, obj_scores)], | |
| gt_mask.shape | |
| ) | |
| # Compute metrics | |
| metrics = compute_all_metrics(pred_combined, gt_mask) | |
| metrics['stem'] = metadata['stem'] | |
| metrics['num_objects'] = metadata['num_objects'] | |
| metrics['avg_sam2_score'] = float(np.mean(obj_scores)) | |
| per_sample_metrics.append(metrics) | |
| # Per-class tracking | |
| for prompt, mask in zip(prompts, pred_masks): | |
| cls_id = prompt['class_id'] | |
| if mask.shape != gt_mask.shape: | |
| mask = cv2.resize(mask, (gt_mask.shape[1], gt_mask.shape[0]), | |
| interpolation=cv2.INTER_NEAREST) | |
| obj_metrics = compute_all_metrics(mask, gt_mask) | |
| per_class_metrics[cls_id].append(obj_metrics) | |
| # Aggregate | |
| overall = aggregate_metrics(per_sample_metrics) | |
| per_class_agg = {} | |
| for cls_id, cls_metrics in per_class_metrics.items(): | |
| if len(cls_metrics) > 0: | |
| per_class_agg[cls_id] = aggregate_metrics(cls_metrics) | |
| return { | |
| 'per_sample': per_sample_metrics, | |
| 'overall': overall, | |
| 'per_class': per_class_agg, | |
| 'n_samples': n_samples, | |
| 'mode': mode, | |
| } | |
| def print_results(results: dict, label: str): | |
| """Pretty-print evaluation results.""" | |
| overall = results['overall'] | |
| print(f"\n{'='*60}") | |
| print(f" {label}") | |
| print(f"{'='*60}") | |
| print(f" Dice: {overall['dice']['mean']:.4f} Β± {overall['dice']['std']:.4f}") | |
| print(f" IoU: {overall['iou']['mean']:.4f} Β± {overall['iou']['std']:.4f}") | |
| if 'hd95' in overall: | |
| print(f" HD95: {overall['hd95']['mean']:.2f} Β± {overall['hd95']['std']:.2f}") | |
| print(f" Precision: {overall['precision']['mean']:.4f}") | |
| print(f" Recall: {overall['recall']['mean']:.4f}") | |
| print(f"\n Per-Class Dice:") | |
| for cls_id, cls_agg in sorted(results.get('per_class', {}).items()): | |
| if 'dice' in cls_agg: | |
| name = CLASS_NAMES[int(cls_id)] if int(cls_id) < len(CLASS_NAMES) else f"Class {cls_id}" | |
| print(f" {name:30s}: {cls_agg['dice']['mean']:.4f} Β± {cls_agg['dice']['std']:.4f} (n={cls_agg['dice']['n']})") | |
| def make_serializable(obj): | |
| """Convert numpy types to JSON-serializable Python types.""" | |
| if isinstance(obj, np.ndarray): | |
| return obj.tolist() | |
| if isinstance(obj, (np.float32, np.float64)): | |
| return float(obj) | |
| if isinstance(obj, (np.int32, np.int64)): | |
| return int(obj) | |
| if isinstance(obj, dict): | |
| return {k: make_serializable(v) for k, v in obj.items()} | |
| if isinstance(obj, list): | |
| return [make_serializable(v) for v in obj] | |
| return obj | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Enhanced SAM2 evaluation') | |
| parser.add_argument('--project_root', type=str, default='.') | |
| parser.add_argument('--variant', type=str, default='sam2_hiera_large', | |
| choices=['sam2_hiera_tiny', 'sam2_hiera_small', | |
| 'sam2_hiera_base_plus', 'sam2_hiera_large']) | |
| parser.add_argument('--expand_ratio', type=float, default=0.15, | |
| help='Bounding box expansion ratio (default: 0.15 = 15%%)') | |
| parser.add_argument('--iterations', type=int, default=3, | |
| help='Iterative refinement passes') | |
| parser.add_argument('--split', type=str, default='val') | |
| parser.add_argument('--max_samples', type=int, default=None) | |
| parser.add_argument('--device', type=str, default='cuda') | |
| parser.add_argument('--ablation', action='store_true', | |
| help='Run ablation study (test each strategy individually)') | |
| parser.add_argument('--no_multiscale', action='store_true', | |
| help='Disable multi-scale inference (faster)') | |
| parser.add_argument('--no_crf', action='store_true', | |
| help='Disable CRF post-processing') | |
| parser.add_argument('--box_blend_alpha', type=float, default=0.0, | |
| help='Weight of bounding box prior in post-processing [0.0, 1.0]') | |
| args = parser.parse_args() | |
| if not SAM2_AVAILABLE: | |
| print("ERROR: SAM2 not installed!") | |
| sys.exit(1) | |
| device = args.device if torch.cuda.is_available() else 'cpu' | |
| print(f"Using device: {device}") | |
| # Output directory | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| suffix = 'ablation' if args.ablation else 'enhanced' | |
| run_dir = os.path.join(args.project_root, 'results', 'runs', | |
| f'sam2_{suffix}_{args.variant}_{timestamp}') | |
| os.makedirs(run_dir, exist_ok=True) | |
| # Save config | |
| with open(os.path.join(run_dir, 'config.json'), 'w') as f: | |
| json.dump(vars(args), f, indent=2) | |
| # Dataset with box padding | |
| dataset = BTXRDSAMDataset( | |
| images_dir=os.path.join(args.project_root, 'BTXRD dataset', 'images', args.split), | |
| labels_dir=os.path.join(args.project_root, 'BTXRD dataset', 'labels', args.split), | |
| expand_ratio=args.expand_ratio, | |
| ) | |
| print(f"Dataset: {len(dataset)} images ({args.split}), expand_ratio={args.expand_ratio}") | |
| # Load SAM2 | |
| print(f"\nLoading SAM2 ({args.variant})...") | |
| wrapper = SAM2Wrapper(variant=args.variant, device=device) | |
| all_results = {} | |
| if args.ablation: | |
| # ββ Ablation Study ββββββββββββββββββββββββββββββββββββββββββ | |
| # Test each strategy in isolation to measure its contribution | |
| ablation_configs = [ | |
| ('baseline_padded', { | |
| 'mode': 'box_only', | |
| 'use_multiscale': False, | |
| 'use_crf': False, | |
| 'use_morphology': False, | |
| }), | |
| ('iterative_3pass', { | |
| 'mode': 'iterative_only', | |
| 'use_multiscale': False, | |
| 'use_crf': False, | |
| 'use_morphology': False, | |
| }), | |
| ('iterative_postprocess', { | |
| 'mode': 'full', | |
| 'use_multiscale': False, | |
| 'use_crf': not args.no_crf, | |
| 'use_morphology': True, | |
| }), | |
| ('full_pipeline', { | |
| 'mode': 'full', | |
| 'use_multiscale': not args.no_multiscale, | |
| 'use_crf': not args.no_crf, | |
| 'use_morphology': True, | |
| }), | |
| ] | |
| for name, config in ablation_configs: | |
| print(f"\n{'#'*60}") | |
| print(f" Ablation: {name}") | |
| print(f"{'#'*60}") | |
| results = evaluate_enhanced( | |
| wrapper, dataset, | |
| mode=config['mode'], | |
| max_samples=args.max_samples, | |
| iterations=args.iterations, | |
| use_multiscale=config.get('use_multiscale', False), | |
| use_crf=config.get('use_crf', False), | |
| use_morphology=config.get('use_morphology', False), | |
| box_blend_alpha=args.box_blend_alpha, | |
| ) | |
| print_results(results, name) | |
| all_results[name] = results | |
| else: | |
| # ββ Full Enhanced Evaluation βββββββββββββββββββββββββββββββββ | |
| results = evaluate_enhanced( | |
| wrapper, dataset, | |
| mode='full', | |
| max_samples=args.max_samples, | |
| iterations=args.iterations, | |
| use_multiscale=not args.no_multiscale, | |
| use_crf=not args.no_crf, | |
| use_morphology=True, | |
| box_blend_alpha=args.box_blend_alpha, | |
| ) | |
| print_results(results, f"SAM2 Enhanced ({args.variant})") | |
| all_results['enhanced'] = results | |
| # Save results | |
| serializable = make_serializable(all_results) | |
| results_path = os.path.join(run_dir, 'results.json') | |
| with open(results_path, 'w') as f: | |
| json.dump(serializable, f, indent=2) | |
| print(f"\n{'='*60}") | |
| print(f"Results saved to: {run_dir}") | |
| print(f"{'='*60}") | |
| if __name__ == '__main__': | |
| main() | |