Spaces:
Sleeping
Sleeping
Download src/eval_medsam.py from amitaddi/btxrd-workstation: direct link, hf CLI and curl.
- Browser
- Download file 5.56 kB
-
https://huggingface.co/spaces/amitaddi/btxrd-workstation/resolve/main/src/eval_medsam.py
- Command line
-
hf download hf://spaces/amitaddi/btxrd-workstation/src/eval_medsam.py
-
curl -L -o eval_medsam.py https://huggingface.co/spaces/amitaddi/btxrd-workstation/resolve/main/src/eval_medsam.py
5.56 kB
| """ | |
| MedSAM Evaluation on BTXRD. | |
| Evaluates MedSAM (SAM fine-tuned on 1.5M medical images) in zero-shot mode | |
| with bounding box prompts. | |
| Usage: | |
| python -m src.eval_medsam --project_root . | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import argparse | |
| import numpy as np | |
| from datetime import datetime | |
| from tqdm import tqdm | |
| import torch | |
| from src.data.dataset import BTXRDSAMDataset | |
| from src.models.medsam_wrapper import MedSAMWrapper, MEDSAM_AVAILABLE | |
| from src.metrics import compute_all_metrics, aggregate_metrics | |
| def evaluate_medsam(wrapper: MedSAMWrapper, | |
| dataset: BTXRDSAMDataset, | |
| max_samples: int = None) -> dict: | |
| """ | |
| Evaluate MedSAM with box prompts. | |
| Args: | |
| wrapper: MedSAMWrapper instance | |
| dataset: BTXRDSAMDataset | |
| max_samples: Limit samples | |
| Returns: | |
| Results dict with per-sample and aggregated metrics | |
| """ | |
| per_sample_metrics = [] | |
| per_class_metrics = {i: [] for i in range(9)} | |
| n = len(dataset) if max_samples is None else min(max_samples, len(dataset)) | |
| for idx in tqdm(range(n), desc="Evaluating MedSAM"): | |
| image, prompts, gt_mask, metadata = dataset[idx] | |
| results = wrapper.predict_all_objects(image, prompts) | |
| pred_combined = wrapper.combine_masks(results, gt_mask.shape) | |
| metrics = compute_all_metrics(pred_combined, gt_mask) | |
| metrics['stem'] = metadata['stem'] | |
| metrics['num_objects'] = metadata['num_objects'] | |
| metrics['medsam_score'] = np.mean([r['score'] for r in results]) | |
| per_sample_metrics.append(metrics) | |
| for prompt, result in zip(prompts, results): | |
| cls_id = prompt['class_id'] | |
| obj_metrics = compute_all_metrics(result['mask'], gt_mask) | |
| obj_metrics['medsam_score'] = result['score'] | |
| per_class_metrics[cls_id].append(obj_metrics) | |
| 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, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description='MedSAM evaluation on BTXRD') | |
| parser.add_argument('--project_root', type=str, default='.') | |
| parser.add_argument('--split', type=str, default='val') | |
| parser.add_argument('--expand_ratio', type=float, default=0.0) | |
| parser.add_argument('--max_samples', type=int, default=None) | |
| parser.add_argument('--device', type=str, default='cuda') | |
| args = parser.parse_args() | |
| if not MEDSAM_AVAILABLE: | |
| print("ERROR: MedSAM not installed!") | |
| print("Run: pip install git+https://github.com/bowang-lab/MedSAM.git") | |
| sys.exit(1) | |
| device = args.device if torch.cuda.is_available() else 'cpu' | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| run_dir = os.path.join(args.project_root, 'results', 'runs', | |
| f'medsam_zeroshot_{timestamp}') | |
| os.makedirs(run_dir, exist_ok=True) | |
| with open(os.path.join(run_dir, 'config.json'), 'w') as f: | |
| json.dump(vars(args), f, indent=2) | |
| 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})") | |
| print("Loading MedSAM...") | |
| wrapper = MedSAMWrapper(device=device) | |
| results = evaluate_medsam(wrapper, dataset, max_samples=args.max_samples) | |
| CLASS_NAMES = [ | |
| 'giant cell tumor', 'multiple osteochondromas', 'osteochondroma', | |
| 'osteofibroma', 'osteosarcoma', 'other bt', 'other mt', | |
| 'simple bone cyst', 'synovial osteochondroma' | |
| ] | |
| overall = results['overall'] | |
| print(f"\n{'='*60}") | |
| print("MedSAM Zero-Shot Results") | |
| 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"\nPer-Class Dice:") | |
| for cls_id, cls_agg in sorted(results['per_class'].items()): | |
| if 'dice' in cls_agg: | |
| name = CLASS_NAMES[cls_id] | |
| print(f" {name:30s}: {cls_agg['dice']['mean']:.4f} ± {cls_agg['dice']['std']:.4f}") | |
| # Save | |
| def make_serializable(obj): | |
| 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 | |
| with open(os.path.join(run_dir, 'results.json'), 'w') as f: | |
| json.dump(make_serializable(results), f, indent=2) | |
| print(f"\nResults saved to: {run_dir}") | |
| if __name__ == '__main__': | |
| main() | |