# Segment Anything in Medical Images

MedSAM adapts Segment Anything to segment many medical image types

Jun Ma, Yuting He, Feifei Li, Lin Han, Chenyu You, Bo Wang · arXiv · 2023-4-24

- **Problem** Medical segmentation models are usually trained for one task and lose accuracy on new targets or imaging types. SAM, trained on natural photos, struggles with medical targets that have weak boundaries or low contrast.
- **Method** MedSAM fine-tunes SAM on 1,570,263 medical image-mask pairs. It updates the image encoder and mask decoder, keeps the prompt encoder fixed, and takes a bounding box as the prompt.
- **Results** MedSAM ranked first on most of 86 internal validation tasks. On nasopharynx cancer in external validation it reached a median DSC of 87.8%.

## Why task-specific segmentation models fall short

Most medical segmentation models are trained for one task, so their accuracy can drop sharply when the target, the scanner or the imaging type changes. Segment Anything Model (SAM) takes the opposite design: it is a promptable model trained on natural images, where a user marks the target with points or a bounding box. Its direct use on medical data is limited, because medical images differ a great deal from natural photographs.

In the medical studies that tested SAM without changes, it worked on targets with clear edges but struggled with weak boundaries or low contrast.

The question the authors ask is whether SAM can be adapted into one model that covers many medical modalities and targets with a single set of weights, rather than many separate networks. Their answer is MedSAM, which fine-tunes SAM on over a million medical image-mask pairs and compares it with SAM and modality-wise specialist networks.

## Assembling and standardizing the training collection

The collection contains 1,570,263 medical image-mask pairs across 10 imaging modalities and covers over 30 cancer types. The images were gathered from public segmentation resources such as TCIA, Kaggle, Grand-Challenge and MICCAI challenges, and every dataset came with annotations made by human experts. Datasets with incomplete images, branching targets, inaccurate annotations or tiny volumes were excluded.

Intensity ranges differ widely between modalities: CT values run from -2000 to 2000, MR values from 0 to 3000, and endoscopy and ultrasound values from 0 to 255. CT Hounsfield units are windowed first, using window width and level pairs of (W:400, L:40) for soft tissue, (W:1500, L:-160) for lung and (W:80, L:40) for brain, and then rescaled to \[0, 255\].

For MR, X-ray, ultrasound, mammography and OCT, intensities are clipped to the 0.5th and 99.5th percentiles before rescaling to \[0, 255\]. RGB images already in \[0, 255\] keep their values, and out-of-range RGB images are rescaled with max-min normalization.

Every input is resized to 1024 × 1024 × 3. Each 3D slice is resized to 1024 × 1024 and its channel is repeated three times so that it matches the RGB-shaped input. Images are resized with bicubic interpolation and masks with nearest-neighbor interpolation, so the mask boundaries keep their exact labels. Whole-slide pathology images are cut into patches without overlap, and boundary patches are padded with 0.

Internal splits are 80%, 10% and 10% for training, tuning and validation, and they are made per 3D scan or per video so that neighbouring frames do not leak across splits. Pathology splits are made per slide, and the external validation datasets were held out from training altogether.

## How an image and a box become a mask

MedSAM keeps the three-part layout of SAM: an image encoder, a prompt encoder and a mask decoder. The image encoder is a ViT-based network with the base configuration of 12 transformer layers, chosen because larger ViT variants gave only marginal accuracy gains for much more computation. The encoder splits the 1024 × 1024 × 3 input into 16 × 16 × 3 patches and yields a 64 × 64 image embedding, a 16-fold downscaling of the input.

Because this embedding is computed once per image, later box prompts can be processed quickly, which is what makes interactive use practical.

The prompt encoder represents a box by two corner points, the top-left and bottom-right corners, and maps each to a 256-dimensional embedding through positional encoding. The mask decoder has two transformer layers that fuse the image embedding with the prompt embedding, followed by two transposed convolutional layers that raise the resolution to 256 × 256.

The decoder then applies a sigmoid activation and bilinear interpolation to reach the input size, and it outputs a mask together with a confidence score. During MedSAM training the image encoder has 89,670,912 trainable parameters and the mask decoder has 4,058,340.

The image encoder is initialized by masked auto-encoder pre-training and then trained with full supervision on the SAM dataset before MedSAM fine-tuning begins. Fine-tuning starts from SAM with the ViT-Base configuration, so the base architecture is the same one the authors evaluated.

## Fine-tuning objective and optimization

MedSAM fine-tunes SAM on more than a million medical image-mask pairs, which is the change that separates it from the original model. The prompt encoder is fixed, while the image encoder and the mask decoder are updated throughout training. During training, each box prompt is simulated from the expert mask and randomly perturbed by 0-20 pixels.

The loss combines binary cross-entropy and Dice loss with equal weight. Writing S for the predicted segmentation, G for the ground truth, s\_i and g\_i for their values at voxel i, and N for the number of voxels, the terms are defined as follows. \\\[ L\_{\\mathrm{BCE}} = -\\frac{1}{N}\\sum\_{i=1}^{N}\\left\[g\_i \\log s\_i + (1-g\_i)\\log(1-s\_i)\\right\] \\\] \\\[ L\_{\\mathrm{Dice}} = 1 - \\frac{2\\sum\_{i=1}^{N} g\_i s\_i}{\\sum\_{i=1}^{N} g\_i^2 + \\sum\_{i=1}^{N} s\_i^2} \\\] The total loss is \\\[ L = L\_{\\mathrm{BCE}} + L\_{\\mathrm{Dice}} \\\].

The cross-entropy term penalizes each voxel's error, and the Dice term rewards overlap between prediction and ground truth.

The global batch size is 160, and no data augmentation is applied. The model was trained for 150 epochs on 20 A100 (80G) GPUs, and the last checkpoint was kept as the final model.

## Why boxes rather than points or full automation

A fully automatic model would have to guess the intended target, and the same liver CT image can call for segmenting the tumour or the whole liver with surrounding organs depending on the clinician. Input modalities also vary in dimension: CT and MR give 3D volumes, while X-ray and ultrasound give 2D images. The authors therefore use a promptable 2D model, which also handles 3D data by processing it as a series of 2D slices.

The authors argue that a bounding box gives a clearer spatial context for the target than a point, which can be ambiguous when neighbouring structures look alike. Drawing a box is also quick, which helps when several objects are segmented in one image. Supplementary Fig. 1 shows segmentation examples with the different prompt types.

## Internal validation across 86 tasks

The comparison covers 86 internal validation tasks, with each of the four methods scored by the median Dice Similarity Coefficient (DSC) per task. The U-Net and DeepLabV3+ specialists are trained per modality, while SAM and MedSAM each run as one model across all modalities. Two specialist families were trained, giving 20 specialist models in total.

SAM performed worst on most tasks, although it did well on some RGB tasks, such as polyp segmentation in endoscopy images, with a median DSC of 91.3% (IQR 81.2-95.1%). The authors attribute this to SAM's training on natural RGB images and to the fact that many RGB targets have distinct appearances. Both specialist families outperformed SAM by a wide margin, and MedSAM showed a narrower spread of task scores than either specialist family.

In the podium plot, MedSAM ranked first on most tasks, U-Net most often ranked second and DeepLabV3+ most often third, and SAM ranked last on almost every task. Examples of liver tumour in CT, brain tumour in MRI, breast tumour in ultrasound and polyp in endoscopy show that SAM tends to under- or over-segment targets with weak boundaries, while MedSAM stays close to the specialists or exceeds them.

## External validation on 60 unseen tasks

The external set has 60 tasks, each drawn from a new dataset or involving an unseen target, and none of them was used in training. On most CT and MR tasks SAM still performed worse, but the specialists no longer consistently beat it. For right kidney segmentation in MR T1-weighted images, the DSC values were 90.1% for SAM, 85.3% for U-Net and 86.4% for DeepLabV3+.

The authors read this as limited generalization of the specialist models to unseen targets.

MedSAM reached a median DSC of 87.8% (IQR 85.0-91.4%) on nasopharynx cancer segmentation, which is the example the authors highlight. On this task the reported gains are 52.3% over SAM, 15.5% over U-Net and 22.7 over DeepLabV3+, and the last figure is printed without a unit. MedSAM also outperformed SAM and the specialists on some unseen modalities, such as abdomen T1 InPhase and OutPhase, with improvements of up to 10%.

The authors report that MedSAM is consistently superior across the external set, with more examples in Supplementary Fig. 13.

## A new modality and the task-specific U-Net comparison

The multiple myeloma plasma cell dataset is a distinct modality and task, and it was never seen during MedSAM training. MedSAM still outperformed SAM on this dataset, which the authors present as evidence of generalization.

For the task-specific comparison the authors chose four tasks: liver cancer in CT, abdominal organs in MR, nerve cancer in ultrasound and polyp in endoscopy. Task-specific U-Net models often performed well on the internal splits but diminished markedly on the external sets, whereas MedSAM was applied without fine-tuning and kept consistent performance on both.

Because the comparison covers four tasks, the result describes these tasks rather than the full benchmark.

## Effect of training set size

The authors trained MedSAM on 10,000 and on 100,000 images, uniformly sampled from the full training set so that data diversity was preserved, and compared these models with the default model. Performance rose with the number of training images on both internal and external validation sets, which the authors describe as following a scaling rule.

The comparison reports the trend across three training sizes, and the text gives no exact per-size scores.

## Annotation time with MedSAM assistance

The study uses the adrenocortical carcinoma CT dataset, in which the adrenal tumour was neither in training nor in the existing validation sets. Ten cases with 733 tumour slices were sampled, and two radiologists with 8 and 6 years of clinical practice each annotated them in two ways. In the first way, each expert annotated the 3D tumour slice by slice.

In the second, each expert drew long and short axes every 3-10 slices, and MedSAM segmented the tumour from these sparse markers before manual refinement. The markers are turned into rectangle masks, the masks are interpolated across unlabelled slices, and the resulting masks are converted to bounding boxes for MedSAM. The time of the second pipeline includes the initial markers, the MedSAM inference and the refinement, and ITK-SNAP was used for manual work.

With MedSAM assistance, annotation time fell by 82.37% for one expert and by 82.95% for the other. These are reductions in annotation time for two experts on 10 cases, not a measurement across a larger group of annotators.

## Limitations

Vessel-like branching structures are hard for the model because a bounding box can be ambiguous for them; arteries and veins share the same box in eye fundus images. Branching targets were excluded from the curated dataset, so the training data cover this structure type only through its exclusion. The authors suggest that MedSAM can be fine-tuned for less-represented modalities or for vessels, but this fine-tuning was not tested in these experiments.

The external datasets were held out from training, so the external results do not reflect training on those datasets. Volumes are handled slice by slice in a 2D model, and the DeepLabV3+ specialists were trained on images resized to 224 × 224 × 3.

## Paper info

- **Authors**: Jun Ma, Yuting He, Feifei Li, Lin Han, Chenyu You, Bo Wang
- **Venue**: arXiv · Preprint
- **First published**: 2023-4-24
- **Added**: 2026-11-12
- **Updated**: 2024-4-1
- **Version**: v3
- **arXiv**: 2304.12306
- **DOI**: 10.1038/s41467-024-44824-z
- **Category**: eess.IV · cs.CV
- **Original paper terms**: [CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/2304.12306v3) · [PDF ↗](https://arxiv.org/pdf/2304.12306v3)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Jun Ma, Yuting He, Feifei Li, Lin Han, Chenyu You, Bo Wang (2023). Segment Anything in Medical Images. arXiv:2304.12306v3. https://doi.org/10.1038/s41467-024-44824-z

**BibTeX**

```
@article{ma2023segment,
  title = {{Segment Anything in Medical Images}},
  author = {Jun Ma and Yuting He and Feifei Li and Lin Han and Chenyu You and Bo Wang},
  year = {2023},
  eprint = {2304.12306},
  archivePrefix = {arXiv},
  doi = {10.1038/s41467-024-44824-z},
  url = {https://arxiv.org/abs/2304.12306v3}
}
```

## Related papers

- [TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation](https://refivu.com/en/papers/28bfb581-8f1f-42dd-ab0d-1b3c56282f6a-transunet-transformers-make-strong-encoders-for-medical.md)
- [TotalSegmentator: robust segmentation of 104 anatomical structures in CT images](https://refivu.com/en/papers/38d65e87-91c3-4285-bca2-9755328de70d-totalsegmentator-robust-segmentation-of-104-anatomical.md)
- [EchoAlign: Echocardiography foundation model with multilevel report alignment](https://refivu.com/en/papers/eb79d777-02f7-419b-b2f3-354bb59e9f8e-echoalign-echocardiography-foundation-model-with-multilevel.md)
- [Efficient Multi-Scale 3D CNN with Fully Connected CRF for Accurate Brain Lesion Segmentation](https://refivu.com/en/papers/5fa28c90-a21c-4b80-9a3e-409a47ddd061-efficient-multi-scale-3d-cnn-with-fully-connected.md)
- [Swin-Unet: Unet-like Pure Transformer for Medical Image Segmentation](https://refivu.com/en/papers/178a13b8-5d0e-4448-a1cb-759db558ade3-swin-unet-unet-like-pure-transformer-for-medical.md)
- [SAM 2: Segment Anything in Images and Videos](https://refivu.com/en/papers/44b54691-126e-4def-9b6b-d659caa1f50d-sam-2-segment-anything-in-images-and-videos.md)

## Other paper commentary

- [MMDetection: Open MMLab Detection Toolbox and Benchmark](https://refivu.com/en/papers/10a01329-b3c8-4a57-a8da-f721a2d42d68-mmdetection-open-mmlab-detection-toolbox-and-benchmark.md)
- [SuperPoint: Self-Supervised Interest Point Detection and Description](https://refivu.com/en/papers/d0aa9e04-3220-432a-8074-02191fd86615-superpoint-self-supervised-interest-point-detection-and.md)
- [OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks](https://refivu.com/en/papers/a615b23b-cb60-4fff-95a7-0a3b82dc2d4e-overfeat-integrated-recognition-localization-and-detection.md)
- [Random Erasing Data Augmentation](https://refivu.com/en/papers/4dd86d04-2086-4796-aa90-74b9d083d0ee-random-erasing-data-augmentation.md)
- [CornerNet: Detecting Objects as Paired Keypoints](https://refivu.com/en/papers/f70d57a2-b48d-4fc2-baa1-2e7e2057bad5-cornernet-detecting-objects-as-paired-keypoints.md)
- [Deep CORAL: Correlation Alignment for Deep Domain Adaptation](https://refivu.com/en/papers/0a5f5341-f013-4a47-b5c4-af4c12f6a0aa-deep-coral-correlation-alignment-for-deep-domain-adaptation.md)
- [Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments](https://refivu.com/en/papers/cdbfc66c-b5f8-47cf-8741-06704dc59cc0-multi-agent-actor-critic-for-mixed-cooperative-competitive.md)
- [Pruning Filters for Efficient ConvNets](https://refivu.com/en/papers/54826eca-5fee-4b64-b058-a4fcd92f8178-pruning-filters-for-efficient-convnets.md)
- [Recent Trends in Deep Learning Based Natural Language Processing](https://refivu.com/en/papers/6cdbf953-5aaa-4de2-9e22-528902a11655-recent-trends-in-deep-learning-based-natural-language.md)
- [Generalizing from a Few Examples: A Survey on Few-Shot Learning](https://refivu.com/en/papers/8988e143-7a9e-4146-9f9b-40c8e0cb6bb2-generalizing-from-a-few-examples-a-survey-on.md)
- [CatBoost: unbiased boosting with categorical features](https://refivu.com/en/papers/2bddd7a0-b14d-422c-836d-b47da78a26fd-catboost-unbiased-boosting-with-categorical-features.md)
- [In Defense of the Triplet Loss for Person Re-Identification](https://refivu.com/en/papers/9a193d31-bb38-4b07-8752-1bc32882197d-in-defense-of-the-triplet-loss-for-person.md)

## Terms in this paper

- [u-net](https://refivu.com/en/terms/f49a93d54ad5-u-net)
- [cross-entropy loss](https://refivu.com/en/terms/14067bdf8b9f-cross-entropy-loss)
- [positional encoding](https://refivu.com/en/terms/4544e2c25b3b-positional-encoding)
- [Vision Transformer (ViT)](https://refivu.com/en/terms/5676f2cc1c70-vision-transformer-vit)
- [nnU-Net](https://refivu.com/en/terms/606216a52500-nnu-net)
- [Dice loss](https://refivu.com/en/terms/a73130d07df5-dice-loss)
- [Wilcoxon signed-rank test](https://refivu.com/en/terms/40244c3cc86b-wilcoxon-signed-rank-test)
- [DeepLabv3+](https://refivu.com/en/terms/26afd1971cb0-deeplabv3)
- [mask decoder](https://refivu.com/en/terms/3976b4ac4671-mask-decoder)
- [prompt encoder](https://refivu.com/en/terms/97d4c34715cd-prompt-encoder)
- [normalized surface distance](https://refivu.com/en/terms/5456cde5af2d-normalized-surface-distance)
- [promptable segmentation](https://refivu.com/en/terms/efe47c90802b-promptable-segmentation)
- [Segment Anything Model](https://refivu.com/en/terms/21c36db01b7b-segment-anything-model)
- [specialist models](https://refivu.com/en/terms/9a6327ab53e9-specialist-models)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/505368c7-a7cf-4cc6-b939-a8043e6cf7cd-segment-anything-in-medical-images)
