33 Generative Models for Medical Image Segmentation
Why Medical Image Segmentation Matters
A patient walks into a hospital. A computed tomography scan reveals a shadow on the lung - a faint, irregularly bordered region that could be a benign granuloma or a malignant nodule. The radiologist must decide: where does the suspicious tissue end and the healthy parenchyma begin? This decision, made pixel by pixel across hundreds of cross-sectional slices, is medical image segmentation. It is the invisible bridge between raw medical images and the life-saving clinical decisions that follow.
Every day, this scene plays out millions of times across the world's hospitals, clinics, and imaging centres. A neurosurgeon studies an MRI to determine the precise boundaries of a glioblastoma before removing it. A radiation oncologist delineates the prostate on a CT scan so that a linear accelerator can deliver a lethal dose to the tumour while sparing the rectum and bladder. A pathologist examines a digitised tissue slide and must distinguish cancerous cell nuclei from benign ones among thousands of overlapping cells. A cardiologist traces the endocardial border on an echocardiogram to measure ejection fraction. In every case, the clinical workflow depends on the same fundamental operation: partitioning an image into anatomically or pathologically meaningful regions.
The stakes are high. An incorrectly drawn tumour boundary in radiotherapy planning can mean the difference between curing a cancer and irradiating healthy tissue. An imprecise cardiac segmentation can lead to a misdiagnosis of heart failure. A missed lesion on a screening mammogram can delay treatment by years. Medical image segmentation is not an abstract computer vision exercise - it is a clinical tool on which human lives depend.
This chapter develops the mathematical foundations, algorithmic tools, and practical intuitions needed to understand how generative models are transforming medical image segmentation. We begin, in this section, by defining the segmentation problem precisely, surveying its clinical applications, and confronting the annotation bottleneck that motivates the entire enterprise. We then introduce the generative perspective - the idea that segmentation is not about predicting a single mask, but about modelling a distribution over plausible masks - and lay out the roadmap for the remainder of the chapter.
What Is Medical Image Segmentation?
At its core, medical image segmentation is a labelling problem. Given a medical image, the task is to assign every spatial element (pixel in 2D, voxel in 3D) to one of a predefined set of anatomical or pathological categories.
Definition 1 (Medical image segmentation).
Let be a medical image with spatial dimensions and channels (e.g., for grayscale CT, for RGB histopathology). A segmentation mask is a map (MASK DEF) where is the number of foreground classes and denotes the background. The segmentation task is to produce a mask that assigns each pixel to the correct anatomical or pathological class. In the 3D setting, the image has an additional depth dimension (the number of slices), and the mask becomes .
This definition, while simple, conceals enormous practical complexity. The “correct” label for a pixel is often ambiguous: tumour boundaries are infiltrative and gradual, organ boundaries depend on the imaging protocol, and different experts may disagree on the same case. We return to this fundamental ambiguity in The Generative Revolution, where it becomes a primary motivation for the generative approach.
Medical image segmentation encompasses two distinct but related paradigms that are worth distinguishing at the outset.
Definition 2 (Semantic vs. instance segmentation).
Semantic segmentation assigns each pixel to a class label without distinguishing between individual objects of the same class. For example, in a brain MRI, every voxel labelled “white matter” belongs to the same semantic region, regardless of which anatomical tract it is part of. Formally, the mask takes values in a fixed label set .
Instance segmentation additionally distinguishes individual objects within the same class. In cell nuclei segmentation, for example, each nucleus receives a unique identifier, so two adjacent nuclei of the same cell type are assigned different labels. Formally, the mask takes values in a countable set , where indexes distinct instances of class .
Most organ and tumour segmentation tasks are semantic (one liver, one spleen, one tumour mass), while cell-level and lesion-counting tasks require instance-level discrimination.
A third paradigm, panoptic segmentation, merges the two: every pixel receives both a class label (semantic) and, for countable “thing” classes, an instance identifier, while uncountable “stuff” classes (background tissue, air) receive only semantic labels. Panoptic segmentation has gained traction in computational pathology, where tissue regions (stuff) and individual cells (things) must be jointly characterised.
Clinical Applications of Segmentation
Medical image segmentation serves as a foundational step in a remarkably diverse array of clinical workflows. We survey the most important ones below.
Diagnosis and screening.
Segmentation enables quantitative analysis of anatomical structures and pathological regions. By delineating the left ventricle on cardiac MRI, clinicians compute ejection fraction - the percentage of blood pumped out with each heartbeat - which is the single most important metric for diagnosing heart failure. By segmenting lung nodules on low-dose CT, computer-aided detection systems flag suspicious findings for radiologist review, reducing missed cancers on screening examinations. By measuring hippocampal volume on brain MRI, neurologists track the progression of Alzheimer's disease over time.
Treatment planning.
Radiation therapy requires precise delineation of the tumour and surrounding organs at risk (OARs). The segmentation directly determines the radiation dose distribution: voxels inside the tumour receive a high dose, while voxels inside nearby organs are constrained to receive a low dose. A segmentation error of even a few millimetres can have serious consequences - under-dosing the tumour leads to recurrence, while over-dosing an organ at risk causes toxicity. Modern radiotherapy workflows require segmentation of – structures per patient, a task that takes a trained dosimetrist minutes to several hours per case.
Surgical navigation and planning.
In neurosurgery, preoperative MRI is segmented to create a 3D model of the brain, the tumour, and critical structures such as the motor cortex and major blood vessels. This model is registered to the patient's anatomy during surgery, providing the surgeon with a real-time map of what lies beneath the cortical surface. Similar workflows exist in orthopaedic surgery (segmenting bones for joint replacement planning), hepatic surgery (segmenting liver lobes and vascular trees for resection planning), and craniofacial surgery (segmenting the skull for reconstructive procedures).
Longitudinal monitoring.
Tracking disease progression over time requires segmenting the same structures on images acquired at different time points. In multiple sclerosis, new or enlarging white matter lesions on serial MRI scans indicate disease activity and guide treatment decisions. In oncology, the Response Evaluation Criteria in Solid Tumors (RECIST) guidelines require measurement of target lesion diameters, which in practice necessitates segmentation. Consistent, automated segmentation eliminates the inter-observer variability that plagues manual measurement.
Computational pathology.
Digital whole-slide images of tissue biopsies can contain billions of pixels. Segmenting individual cell nuclei, glandular structures, and tissue regions is the first step in computational pathology pipelines that predict cancer grade, molecular subtypes, and patient prognosis. The density and spatial arrangement of tumour-infiltrating lymphocytes, quantified through segmentation, has emerged as a prognostic biomarker in breast cancer and melanoma.
Key Idea.
Segmentation is the bridge between pixels and clinical decisions. Raw medical images are high-dimensional, noisy, and difficult for downstream algorithms (or busy clinicians) to interpret directly. Segmentation compresses this complexity into a structured representation - a labelled map of anatomical and pathological regions - that enables quantitative analysis, treatment planning, and longitudinal monitoring. Without segmentation, the vast majority of advanced clinical workflows would be impossible.
The Modalities of Medical Imaging
Before proceeding, it is helpful to understand the main imaging modalities that produce the data on which segmentation algorithms operate. Each modality has distinct physical principles, noise characteristics, resolution, and contrast properties that shape the segmentation challenge.
Computed tomography (CT).
CT measures X-ray attenuation and produces 3D volumes where voxel intensity is measured in Hounsfield units (HU), calibrated so that water is HU and air is HU. CT excels at depicting bony structures and lung parenchyma, and is the workhorse of oncologic imaging. A typical CT volume has dimensions , where ranges from (a focused abdominal scan) to over (a whole-body PET/CT), with in-plane resolution of – mm and slice spacing of – mm. The fixed Hounsfield scale provides a consistent intensity meaning across scanners and patients, which is a significant advantage for algorithm development.
Magnetic resonance imaging (MRI).
MRI exploits nuclear magnetic resonance to produce soft-tissue contrast far superior to CT. Unlike CT, MRI intensities are not calibrated to an absolute scale: the same tissue can appear bright or dark depending on the pulse sequence (T1-weighted, T2-weighted, FLAIR, diffusion-weighted, etc.). This intensity variability across scanners, protocols, and even sessions is a major challenge for segmentation algorithms. MRI is the primary modality for brain, musculoskeletal, and cardiac imaging, with typical resolutions of mm for structural brain MRI and mm for cardiac cine MRI.
Histopathology.
Whole-slide images (WSIs) are gigapixel RGB images of tissue sections stained with haematoxylin and eosin (H&E) or immunohistochemical markers. A single WSI can be pixels, requiring segmentation algorithms that operate at multiple scales. Staining variability between laboratories is a major domain shift challenge.
Ultrasound.
Ultrasound is real-time, portable, and inexpensive, but produces images with poor spatial resolution, high speckle noise, and operator-dependent quality. Segmentation of cardiac chambers on echocardiography and fetal structures on obstetric ultrasound are high-impact applications.
Other modalities.
Positron emission tomography (PET) provides functional information about metabolic activity. Fundus photography captures the retinal surface for ophthalmic screening. Optical coherence tomography (OCT) images retinal layers with micrometre resolution. Each modality presents unique segmentation challenges, but the mathematical framework we develop in this chapter applies broadly.
Segmentation Tasks: Three Illustrative Examples
To make the discussion concrete, we introduce three representative segmentation tasks that will serve as running examples throughout the chapter.
Example 1 (Lung nodule segmentation for radiotherapy planning).
Consider a -year-old patient diagnosed with stage IIA non-small cell lung cancer. A contrast-enhanced CT scan of the chest is acquired, producing a volume with mm in-plane resolution and mm slice spacing. The radiation oncologist must delineate the gross tumour volume (GTV) - the visible extent of the tumour on imaging - which will be expanded by a margin to create the planning target volume (PTV) that accounts for microscopic disease spread and patient motion.
The segmentation task is binary: each voxel is labelled as tumour or non-tumour. However, the boundary between the nodule and the surrounding atelectatic (collapsed) lung is often indistinct on CT, and inter-observer variability among radiation oncologists is substantial. A study by joskowicz2019inter found that the Dice coefficient between expert annotations on lung tumours varied from to , with a median of . This means that even the “ground truth” is uncertain, a fact that motivates the probabilistic approaches we develop later.
The clinical consequence of segmentation quality is direct. The radiation dose to the tumour is computed from the GTV contour. If the GTV is too small, tumour cells at the periphery receive insufficient dose and may survive, leading to local recurrence. If the GTV is too large, healthy lung tissue is irradiated unnecessarily, potentially causing radiation pneumonitis. The segmentation is, quite literally, a life-or-death boundary.
Example 2 (Brain tumour delineation for surgical planning).
A -year-old patient presents with seizures and is found to have a glioblastoma multiforme (GBM) on brain MRI. The neurosurgeon must plan a maximal safe resection: removing as much tumour as possible while preserving eloquent cortex (motor strip, language areas, visual cortex). The preoperative MRI includes four sequences: T1-weighted, T1-weighted with gadolinium contrast, T2-weighted, and T2-FLAIR. Each sequence provides complementary information:
T1 with contrast: The enhancing tumour core appears bright due to gadolinium leakage through the disrupted blood–brain barrier.
T2-FLAIR: The surrounding oedema (fluid accumulation) appears bright, extending well beyond the enhancing core.
T2-weighted: The necrotic (dead) core of the tumour appears bright due to fluid content.
The segmentation task requires delineating three nested regions: enhancing tumour, non-enhancing tumour/necrosis, and peritumoral oedema. This is a multi-class semantic segmentation problem on a multi-modal 3D input. The Brain Tumor Segmentation (BraTS) challenge, which has run annually since 2012, provides standardised benchmarks for this task and has driven much of the methodological progress in the field.
The clinical stakes are particularly acute in neurosurgery. Aggressive resection improves survival - every additional percentage of tumour removed is associated with longer overall survival - but resecting eloquent cortex can cause permanent neurological deficits (paralysis, speech loss, blindness). The segmentation defines the surgical corridor: the path through the brain that maximises tumour removal while minimising damage to critical structures.
The Annotation Crisis
The clinical importance of segmentation creates enormous demand for labelled training data. Yet producing these labels is extraordinarily expensive, requiring highly trained medical professionals whose time is already scarce.
The cost of expert annotation.
Annotating a single 3D CT volume for radiotherapy planning (delineating the tumour and – organs at risk) requires minutes to hours of a radiation oncologist's time. At typical consultant rates, this translates to $50–$500 per case. Training a deep learning model to the point of clinical utility typically requires hundreds to thousands of annotated cases, implying an annotation budget of $50,000–$500,000 per anatomical region per imaging modality - and this cost must be repeated for every new clinical task, every new scanner, and every new patient population.
Inter-observer variability.
Even when expert annotations are available, they are not deterministic. Multiple experts annotating the same image will produce different masks. This variability is not noise - it reflects genuine ambiguity in the imaging data. Tumour boundaries are gradual, not sharp. The transition from pathological to normal tissue is a continuum, not a step function. Annotation guidelines can reduce variability but never eliminate it, because the underlying biology is inherently ambiguous.
Consider the following quantitative picture. In the 2021 BraTS challenge, the mean inter-rater Dice coefficient for the enhancing tumour subregion was approximately . This means that two board-certified neuroradiologists, given the same MRI, produce tumour delineations that overlap by only . For the peritumoral oedema, the overlap drops further. For prostate segmentation on MRI, inter-observer Dice scores as low as have been reported.
The implication is striking: the “ground truth” segmentation mask does not exist in any absolute sense. What exists is a distribution of plausible masks, shaped by the annotator's training, experience, visual acuity, and even fatigue level. A segmentation model that outputs a single deterministic mask is committing to one point in this distribution, discarding all information about the uncertainty. This observation is a central motivation for the generative approach.
Scale of the problem.
The scale of medical imaging data production is staggering. Globally, an estimated billion medical imaging examinations are performed annually, producing petabytes of data. The number of trained radiologists, by contrast, is approximately worldwide. The ratio of images to experts is growing exponentially, driven by aging populations, expanded screening programmes, and new imaging modalities. In many low- and middle-income countries, the radiologist-to-population ratio is below per - compared to per in the United States - creating a dramatic access gap that automated segmentation could help close.
Annotation formats and standards.
Medical image annotations are stored in a variety of formats, each with its own conventions. In radiation oncology, contours are stored as DICOM RT Structure Sets - ordered sequences of coordinates defining polygon vertices on each axial slice. In research settings, volumetric masks are typically stored as NIfTI files (3D arrays of integer labels aligned with the image volume). Point annotations (used in interactive segmentation) are stored as coordinate lists. Bounding box annotations, popular in detection tasks and as prompts for foundation models, specify rectangular regions of interest. The diversity of formats reflects the diversity of clinical workflows and complicates the development of universal segmentation benchmarks.
The cold-start problem.
When a new clinical application emerges - say, segmenting a novel biomarker visible on a newly developed MRI sequence - there are zero annotated training examples. Building an initial annotated dataset requires bootstrapping: experts must segment the first cases entirely from scratch, without the benefit of AI-assisted pre-segmentation. This cold-start problem is particularly acute in rare diseases, where the total number of cases worldwide may be in the hundreds. Generative models that can perform zero-shot or few-shot segmentation (Pillar 3 of our framework) directly address this challenge.
Caution.
It is tempting to treat inter-observer variability as “label noise” and apply standard noise-robust training techniques. This is misguided. Label noise refers to random errors (e.g., an annotator accidentally clicking the wrong pixel), which can be averaged away with more annotations. Inter-observer variability, by contrast, reflects systematic differences in clinical judgment about genuinely ambiguous regions. Averaging multiple annotations produces a “consensus” mask that may not correspond to any clinically valid interpretation. A probabilistic model that captures the full distribution of expert opinions is more clinically useful than a single consensus mask.
Standard Loss Functions for Segmentation
Before introducing the generative perspective, we review the standard loss functions used to train segmentation models, as they form the foundation on which generative approaches build.
Cross-entropy loss.
For a segmentation model that outputs per-pixel class probabilities , the pixel-wise cross-entropy loss is (Cross Entropy) where is the number of pixels, is the one-hot encoding of the ground truth label for pixel , and is the predicted probability that pixel belongs to class . Cross-entropy treats each pixel independently and weighs all pixels equally, which can be problematic when foreground structures occupy a small fraction of the image (the class imbalance problem).
Dice loss.
The Dice coefficient is a set overlap metric widely used in medical image segmentation: (DICE Coeff) where are the ground truth and predicted labels for pixel , respectively. The Dice coefficient ranges from (no overlap) to (perfect overlap) and is related to the Jaccard index by .
To use the Dice coefficient as a training loss, we define the soft Dice loss using predicted probabilities: (DICE LOSS) where is the predicted foreground probability and is a small constant for numerical stability. Unlike cross-entropy, the Dice loss operates on the set level rather than the pixel level, making it naturally robust to class imbalance.
Combined losses.
In practice, many segmentation models use a combination of cross-entropy and Dice loss: (Combined LOSS) where is a weighting hyperparameter. The cross-entropy component provides well-behaved gradients for each pixel (especially in the early stages of training when predictions are far from the ground truth), while the Dice component directly optimises the evaluation metric and handles class imbalance. Setting is a common default.
Hausdorff distance loss.
For applications where boundary accuracy is critical (e.g., radiotherapy planning), the Hausdorff distance (Hausdorff) measures the worst-case boundary error between predicted and ground truth contours and . Because the Hausdorff distance is not differentiable, distance-transform-based approximations are used during training.
A Brief History of Medical Image Segmentation
The history of medical image segmentation spans five decades and mirrors the broader evolution of computer vision and machine learning.
Historical Note.
From hand-drawn contours to AI-powered segmentation.
The manual era (1970s–1990s). The earliest “segmentation” in medical imaging was entirely manual: physicians drew contours on printed film using grease pencils, or traced boundaries on early computer displays using a mouse or digitising tablet. The DISPLAY program at the Montreal Neurological Institute (1980s) was among the first interactive tools allowing clinicians to manually label brain structures on MRI. Manual segmentation remained the clinical standard well into the 2000s and, for many anatomical structures, remains so today.
Classical computer vision (1990s–2010s). The first automated approaches borrowed from classical image processing: thresholding, region growing, watershed transforms, and morphological operations. Level set methods and active contours (Kass et al., 1988) introduced the idea of evolving a curve or surface to fit organ boundaries, optimising an energy functional that balanced data fidelity (image gradients) with regularisation (contour smoothness). Atlas-based methods registered a manually labelled template brain to new patients, propagating the labels via the estimated deformation field. Random forests and other shallow machine learning methods offered improved flexibility by learning discriminative features from hand-crafted descriptors (Haar-like features, histogram of oriented gradients, local binary patterns).
The deep learning revolution (2015–present). The publication of U-Net (Ronneberger et al., 2015) in 2015 marked a turning point. U-Net introduced a symmetric encoder–decoder architecture with skip connections that passed high-resolution features directly from the encoder to the decoder, enabling precise localisation even with limited training data. The architecture was remarkably successful in medical imaging, where it quickly became the dominant approach. Subsequent innovations included 3D U-Net for volumetric segmentation (Cicek et al., 2016), Attention U-Net (Oktay et al., 2018), nnU-Net (Isensee et al., 2021) (a self-configuring framework that automatically adapts preprocessing, architecture, and training to each dataset), and transformer-based architectures such as TransUNet (Chen et al., 2021) and Swin-UNETR (Hatamizadeh et al., 2021).
The generative era (2022–present). Most recently, generative models - particularly diffusion models and large vision-language models - have opened entirely new paradigms for segmentation. Rather than training a discriminative model to predict a single mask, these approaches model the full distribution of plausible segmentations, generate synthetic training data to augment scarce annotations, and enable zero-shot segmentation of anatomical structures never seen during training.
The Probabilistic U-Net (Kohl et al., 2018) (2018) introduced the idea of combining a U-Net with a conditional VAE to produce diverse, plausible segmentation samples. MedSegDiff (Wu et al., 2024) (2024) demonstrated that diffusion models could directly generate segmentation masks with competitive quality. The Segment Anything Model (Kirillov et al., 2023) (SAM, 2023), though not originally designed for medical imaging, was rapidly adapted to produce MedSAM and SAM-Med2D, foundation models capable of segmenting medical structures with minimal prompting. These developments represent a fundamental shift in how the community thinks about segmentation: not as a deterministic mapping, but as a generative process.
This chapter develops these ideas in detail.
Why Automation Matters
The case for automated medical image segmentation rests on three pillars: consistency, speed, and accessibility.
Consistency.
A deterministic algorithm produces the same segmentation every time it processes the same image. It does not suffer from fatigue, does not vary with time of day, and is not influenced by the case it reviewed immediately before. While humans exhibit significant intra-observer variability (the same expert annotating the same image on different days will produce different masks), a well-validated algorithm provides reproducible results that facilitate longitudinal comparison and multi-centre clinical trials.
Speed.
Modern deep learning models can segment a 3D CT volume in seconds on a GPU, compared to the minutes or hours required for manual annotation. For radiotherapy planning, where – structures must be delineated per patient, automation can reduce the contouring step from several hours to under a minute, dramatically improving clinical throughput. This is not merely a convenience: in emergency settings (stroke, trauma), speed can be the difference between a salvageable outcome and permanent disability.
Accessibility.
Expert segmentation requires years of specialised training. In many parts of the world, this expertise is simply unavailable. Automated segmentation deployed on cloud-based or edge computing platforms can bring expert-level analysis to underserved communities, rural hospitals, and low-resource settings. The democratisation of medical image analysis through AI has the potential to reduce the global health equity gap in a way that training more radiologists alone cannot.
Quantitative impact.
The quantitative gains from automation are striking. A multi-centre study of TotalSegmentator (Wasserthal et al., 2023), an automated CT segmentation tool covering anatomical structures, found that the model matched expert performance (mean Dice ) on of structures, while reducing segmentation time from – minutes per case to under seconds. In radiotherapy, the DeepMind collaboration with University College London Hospital demonstrated that automated head-and-neck organ-at-risk segmentation reduced contouring time by while maintaining clinical acceptability. These results suggest that the bottleneck in medical image analysis is shifting from “can we build accurate models?” to “can we deploy them safely and equitably?”
Remark 1 (Automation is augmentation, not replacement).
It is important to emphasise that current automated segmentation systems are designed to augment clinical workflows, not replace human experts. The typical deployment pattern is “AI-assisted contouring”: the algorithm produces an initial segmentation that the clinician reviews and edits. This human-in-the-loop approach combines the speed and consistency of automation with the clinical judgment and anatomical knowledge of the expert. Regulatory bodies (e.g., the U.S. FDA) typically require human oversight for AI-generated segmentations used in clinical decision-making.
The Generative Revolution
The story of medical image segmentation over the past decade has been dominated by discriminative models: neural networks trained to map an input image directly to a segmentation mask . U-Net, nnU-Net, TransUNet, and their many variants all share this basic structure. Given an image, the model outputs a single prediction - the most likely mask according to the learned mapping. This approach has been tremendously successful, achieving superhuman performance on many benchmarks and entering clinical practice in a growing number of applications.
So why should we look beyond discriminative models? Why invoke the considerably heavier machinery of generative modelling for a task that discriminative models already handle well?
The answer lies in three fundamental limitations of the discriminative paradigm that become critical in the medical setting.
Limitations of Discriminative Models
Limitation 1: Single-output predictions discard uncertainty.
A discriminative model trained with cross-entropy or Dice loss learns a function that outputs a single “best guess” mask. Even if the model outputs per-pixel probabilities, these probabilities are typically overconfident and do not capture the structured uncertainty that is clinically relevant. When a tumour boundary is genuinely ambiguous, the clinician needs to know not just “this pixel has a chance of being tumour” but “here are three plausible delineations of the tumour boundary, and they differ in the inferior margin.” The former is a marginal probability; the latter is a sample from a joint distribution over the entire mask. Discriminative models provide the former but not the latter.
To see why marginal probabilities are insufficient, consider a simple example. Suppose two equally qualified experts annotate a image patch near a tumour boundary. Expert A labels pixels through as tumour; Expert B labels pixels through as tumour. The pixel-wise average of their annotations assigns probability to both rows, producing a blurred boundary that corresponds to neither expert's opinion. A generative model, by contrast, can represent both experts' annotations as distinct, coherent samples from the posterior distribution.
Limitation 2: Brittle generalisation under domain shift.
Medical images exhibit enormous variability across scanners, protocols, institutions, and patient populations. A model trained on T1-weighted brain MRI from scanner A at hospital B may fail catastrophically when applied to images from scanner C at hospital D, even though the underlying anatomy is the same. This domain shift problem is one of the primary barriers to clinical deployment.
Discriminative models learn a point mapping from images to masks. When the input distribution shifts, this mapping may extrapolate unpredictably. Generative models, by learning the joint distribution or the conditional as a full probability distribution, can in principle provide better-calibrated predictions under distribution shift and flag inputs that fall outside the training distribution. Furthermore, generative models trained on one domain can be adapted to new domains through techniques such as style transfer, domain randomisation, and guided sampling, without retraining.
Limitation 3: Data hunger and the labelling bottleneck.
Discriminative models are data-hungry: performance scales with the number of labelled training examples, and medical annotations are expensive to produce (as we discussed in The Annotation Crisis). Generative models offer a potential escape from this bottleneck through synthetic data generation: training a generative model on a small set of annotated images and then using it to synthesise an unlimited number of realistic image–mask pairs for downstream training.
tableSummary of key limitations of discriminative
segmentation models and how the generative approach addresses each.
Limitation Discriminative Generative Uncertainty Single mask output; pixel-wise probabilities lose correlations Samples multiple plausible masks; captures spatial correlations [4pt]
Domain shift Point mapping; brittle extrapolation Learns data distribution for synthesis; principled OOD detection [4pt]
Data scarcity Requires large labelled datasets Transfers via generative priors; few-shot and zero-shot synthesis
The Distribution Perspective
The shift from discriminative to generative segmentation can be understood as a change in what the model is asked to learn.
Definition 3 (Discriminative vs. generative segmentation).
A discriminative segmentation model learns a function (or, with probabilistic output, a point estimate ) that maps an input image to a single predicted mask . Training minimises a loss between the prediction and a reference annotation .
A generative segmentation model learns the full conditional distribution over segmentation masks given the input image. At inference time, the model can sample multiple plausible masks , compute the posterior mean , or evaluate the probability of any specific mask .
The generative perspective has a beautiful conceptual consequence: when experts disagree, the truth is not a compromise, but a distribution.
Insight.
When experts disagree, the truth is a distribution, not a point. If three radiologists produce three different segmentation masks for the same tumour, the “correct” answer is not the average of their masks (which may correspond to no clinically valid interpretation), but the distribution that assigns appropriate probability to each expert's delineation and to the space of plausible masks in between. A generative model that samples from this distribution provides the clinician with the full picture of uncertainty, enabling more informed decision-making.
Let us formalise this idea. Suppose we have expert annotators, each producing a mask for the same image . The empirical distribution over expert annotations is (Empirical Expert DIST) where is the Dirac delta. A discriminative model that minimises cross-entropy against this empirical distribution converges (in the infinite-data limit) to the pixel-wise marginal , which is the marginalised distribution that loses all information about the correlation structure between pixels. A generative model that learns the full joint distribution preserves these correlations: it can sample mask (a coherent delineation consistent with annotator 1's style) or mask (consistent with annotator 2's style), rather than producing a blurred average.
The mathematical statement is that the pixel-wise entropy decomposes as (Entropy Decomposition) where the multi-information captures the statistical dependencies between pixel labels. A model that only captures marginal entropies (i.e., a discriminative model with independent pixel-wise outputs) overestimates the entropy and produces incoherent samples. Generative models that capture the full joint distribution preserve the multi-information, producing samples that are spatially coherent.
Three Pillars of Generative Medical Segmentation
The application of generative models to medical image segmentation is not a single idea but a constellation of related approaches. We organise them into three pillars.
Pillar 1: Synthetic data generation.
Given a small annotated dataset, a generative model (GAN, VAE, or diffusion model) can be trained to synthesise realistic medical images together with their corresponding segmentation masks. These synthetic image–mask pairs augment the training set for a downstream segmentation model, effectively amplifying the value of each expert annotation. The key technical challenge is ensuring that the synthetic images are diverse, realistic, and label-consistent - that the generated masks accurately correspond to the anatomy depicted in the generated images.
Pillar 2: Ambiguity modelling.
Rather than training a model to predict the single “correct” mask, the generative approach models the full posterior distribution over plausible masks. This enables sampling multiple coherent segmentation hypotheses, computing uncertainty maps that highlight ambiguous regions, and providing clinicians with a richer picture of the segmentation landscape. Conditional diffusion models, probabilistic U-Nets, and stochastic segmentation networks are the primary architectural vehicles for this pillar.
Pillar 3: Zero-shot and few-shot adaptation.
Large-scale generative models trained on diverse datasets can segment anatomical structures they have never been explicitly trained on, by leveraging learned priors about anatomy, tissue contrast, and spatial relationships. Foundation models such as the Segment Anything Model (SAM) and its medical adaptations (MedSAM, SAM-Med2D) demonstrate this capability: given a text prompt or a few point clicks, they can segment novel structures without task-specific training data. This pillar addresses the annotation bottleneck at its root, by reducing the amount of labelled data needed from thousands of annotated volumes to a handful of prompts.
A Probabilistic Framework for Segmentation
Let us develop the probabilistic framework that underpins generative segmentation more carefully. We model the data-generating process as follows. There exists an unknown true conditional distribution over segmentation masks given images. This distribution captures the full range of clinically plausible segmentations, including the variability across expert annotators.
A discriminative model approximates this distribution with a parametric family and optimises (KL Objective) If factorises as a product of independent pixel-wise distributions, i.e., (MEAN Field) then the model is performing a mean-field approximation that cannot capture correlations between pixel labels. This is precisely the standard discriminative segmentation setup: each pixel receives an independent probability, and the “predicted mask” is obtained by taking the at each pixel independently.
A generative model, by contrast, uses a flexible parameterisation that can represent the full joint distribution. For instance, a conditional diffusion model defines (Diffusion Marginal) where the reverse process gradually refines a noisy mask into a coherent segmentation , conditioned on the image . The Markov chain structure of the reverse process induces rich correlations between pixel labels, because each denoising step operates on the entire mask jointly.
Similarly, a conditional VAE defines the generative process as (CVAE Marginal) where the latent variable captures the “style” or “interpretation” of the segmentation. Different samples of produce different coherent masks, and the marginal is a mixture over these interpretations.
Posterior collapse and mode coverage.
A critical challenge for generative segmentation models is ensuring that the learned distribution actually covers all modes of the true distribution . In a conditional VAE, the model may suffer from posterior collapse, where the decoder learns to ignore the latent variable and produce the same output regardless of , effectively reverting to a discriminative model. In a diffusion model, mode collapse is less common due to the gradual denoising process, but the model may still underrepresent rare annotation styles.
The quality of a generative segmentation model can be evaluated along two axes:
Sample quality: each individual sample should be a coherent, clinically plausible mask.
Sample diversity: the set of samples should span the range of plausible segmentations, reflecting the true inter-annotator variability.
These two desiderata are in tension: a model that generates only the “average” mask achieves high quality but zero diversity, while a model that generates random masks achieves high diversity but low quality. The art of generative segmentation lies in achieving both simultaneously.
Measuring Segmentation Quality
For generative segmentation models, standard metrics must be supplemented with measures that capture the quality of the predicted distribution, not just the quality of a single prediction.
The generalised energy distance.
Let be a set of samples from the model and be the set of ground truth annotations from experts. The generalised energy distance (Kohl et al., 2018) is defined as (GED) where is a distance metric (typically ) and the expectations are over independent draws from the sample and ground truth sets. The GED is zero if and only if the model distribution matches the empirical distribution of expert annotations, making it a principled metric for evaluating ambiguity-aware segmentation models.
Sample Dice and best-of-.
A simpler evaluation strategy draws samples from the model and reports the best Dice coefficient achieved among them: (BEST OF S) This metric rewards models whose sample set covers the ground truth but does not penalise low-quality samples as long as at least one sample is good. It is complemented by the mean sample Dice, which averages over samples and rewards consistent quality.
Calibration.
A well-calibrated generative segmentation model should produce samples whose empirical frequency matches the true probability. If the model assigns probability to a particular boundary configuration, then roughly of samples should exhibit that configuration. Calibration can be assessed by partitioning the image into regions, computing the predicted probability that each region is foreground (by averaging over samples), and comparing this to the empirical frequency among expert annotations. A calibration curve (predicted probability vs. observed frequency) that lies close to the diagonal indicates a well-calibrated model.
Structural similarity of samples.
Beyond Dice and IoU, it is often informative to examine how samples differ from one another structurally. For instance, do all samples agree on the bulk of the tumour and differ only at the boundary? Or do some samples include an entirely separate lesion that others miss? The pairwise sample Dice matrix for provides a compact summary of sample agreement. A model that produces diverse boundary variations will have high off-diagonal entries (similar masks with small boundary differences), while a model that switches between qualitatively different interpretations will have lower off-diagonal entries.
Chapter Roadmap
The remainder of this chapter develops the three pillars of generative medical segmentation in detail. fig:medseg:roadmap provides a visual roadmap.
File B: Synthetic data generation.
We develop the theory and practice of generating synthetic medical images paired with segmentation masks. Topics include GAN-based synthesis (pix2pix, SPADE, GAN augmentation), VAE-based synthesis, and diffusion-based synthesis. We address the critical question of label consistency - ensuring that generated masks accurately correspond to the anatomy in generated images - and present quantitative frameworks for evaluating synthetic data quality.
File C: Ambiguity modelling.
We present architectures that model the full posterior distribution over segmentation masks: the Probabilistic U-Net, Stochastic Segmentation Networks, and Hierarchical Probabilistic U-Net. We develop the variational inference framework for training these models and discuss evaluation metrics for multi-modal segmentation outputs.
File D: Diffusion-based segmentation.
We develop diffusion models as segmentation engines: training conditional denoising diffusion probabilistic models (DDPMs) to generate segmentation masks conditioned on medical images. Topics include the connection between diffusion and energy-based models, classifier-free guidance for segmentation, and efficient sampling strategies.
File E: Foundation models for medical segmentation.
We cover the Segment Anything Model (SAM) and its medical adaptations, vision-language models for segmentation (e.g., text-prompted organ segmentation), and the emerging paradigm of universal medical segmentation models trained on large-scale multi-organ datasets.
File F: Clinical deployment considerations.
We address the practical challenges of deploying generative segmentation models in clinical settings: regulatory requirements, uncertainty communication, failure mode detection, and human-AI interaction design.
File G: Frontiers and open problems.
We survey the research frontier: 3D generative segmentation, interactive refinement, continual learning from clinical feedback, and the convergence of generative segmentation with large multimodal models.
Exercises
Exercise 1 (Properties of the Dice coefficient).
Let be two sets of pixel indices (e.g., the foreground pixels in two segmentation masks), and define the Dice coefficient as .
Show that , with if and only if and if and only if .
Prove that is not a metric (i.e., it violates the triangle inequality). Hint: Consider three sets in .
Show the relationship between the Dice coefficient and the Jaccard index (intersection over union): (DICE IOU Relation)
Prove that is a metric. Hint: Show that satisfies the triangle inequality, where denotes the symmetric difference.
Consider the soft Dice loss in (DICE LOSS). Compute its gradient and show that pixels in small foreground regions receive larger gradient magnitudes than pixels in large foreground regions, explaining why the Dice loss naturally handles class imbalance.
Exercise 2 (Why averaging expert annotations is suboptimal).
Consider a binary segmentation task on a image (four pixels in a row). Two equally qualified experts annotate the image as follows: (Expert1) Expert 1 believes the object occupies pixels 2–3; Expert 2 believes it occupies pixels 3–4. Both agree that pixel 3 is foreground.
Compute the pixel-wise average and threshold it at to produce a “consensus” mask. What is the resulting mask?
Compute the Dice coefficient between the consensus mask and each expert annotation. Is the consensus mask closer to either expert's annotation than the experts are to each other?
Now consider a more extreme example with three experts: Compute the pixel-wise average and threshold at . Show that the resulting consensus mask is identical to , effectively discarding the views of experts 1 and 2.
Argue that a generative model that can sample all three expert-like masks provides strictly more clinical information than any single consensus mask.
Challenge. Formally define a loss function for training a generative model that maximises the likelihood of the set of expert annotations, rather than their average. Hint: Consider using the log-likelihood of a mixture model.
Exercise 3 (Cross-entropy vs. Dice loss for imbalanced segmentation).
Consider a binary segmentation task where the foreground (e.g., a small tumour) occupies of pixels and the background occupies . A model predicts for all pixels (foreground probability equal to the class prior).
Compute the cross-entropy loss for this prediction.
Compute the soft Dice loss for this prediction (set ).
Now suppose the model predicts for all pixels (predicting everything as background). Compute both losses. Which loss function more strongly penalises this degenerate prediction?
Discuss the implications for training segmentation models on datasets with extreme class imbalance.
Exercise 4 (Entropy of ambiguous segmentations).
Consider a binary segmentation task. The mask has possible configurations. Suppose the true conditional distribution places equal probability on two masks: (TWO MODE DIST)
Compute the joint entropy .
Compute the marginal entropy for each pixel . What is ?
Compute the multi-information . Interpret this quantity in terms of the spatial structure of the uncertainty.
A discriminative model with independent pixel-wise outputs matches the marginals: for all . Sample from . What fraction of samples match either of the two ground truth masks? What does this tell you about the inadequacy of pixel-wise independence assumptions?
Compute . Is it positive? Interpret.
Exercise 5 (Generative model sample size).
A generative segmentation model produces samples .
The pixel-wise uncertainty at pixel can be estimated as the sample variance . For binary masks, show that this simplifies to where .
How large must be to estimate a probability of with a confidence interval of width at most ? Hint: Use the normal approximation to the binomial.
Discuss the trade-off between computational cost (larger requires more forward passes through the generative model) and estimation accuracy. In what clinical scenarios might a small (e.g., ) be sufficient?
With the clinical motivation established and the generative perspective introduced, we are ready to dive into the technical heart of the chapter. In the next file, we develop the first pillar - synthetic data generation - showing how generative models can transform a handful of expert annotations into a rich, diverse training set that enables segmentation models to learn more effectively from less labelled data.
A Taxonomy of Segmentation Tasks
The previous section established that medical image segmentation is the task of assigning anatomically or pathologically meaningful labels to every spatial element of a medical image. But this single sentence conceals an enormous diversity of concrete problems. Segmenting a lung nodule from a chest CT scan and segmenting a mitotic cell from a fluorescence microscopy video share the word “segmentation,” yet the data formats, spatial scales, annotation conventions, and clinical requirements differ so profoundly that they might as well be different disciplines.
A taxonomy, a principled classification of segmentation tasks along meaningful axes, is essential for several reasons. First, it guides model design: the architecture and loss function suited to dense volumetric organ segmentation are rarely optimal for sparse instance detection in gigapixel histology slides. Second, it clarifies where generative models add the most value: data augmentation helps most when annotation is expensive and domains are narrow, while uncertainty modelling is most critical when inter-rater disagreement is high. Third, it organises the literature: the flood of papers on medical image segmentation becomes navigable once we understand which axis each paper addresses.
We organise the taxonomy along four orthogonal axes, each capturing a distinct dimension of variation:
Output structure: What kind of label map does the model produce? (Semantic, instance, or panoptic.)
Spatial dimensionality: How many spatial and temporal dimensions does the input occupy? (2D, 3D, 2D+, or 4D.)
Clinical target: What anatomy or pathology is being segmented? (Cells, lungs, brain, abdomen, heart, vessels, endoscopy, histology.)
Annotation interface: How does the user interact with the segmentation system? (Fully automatic, interactive, weakly supervised, or text-guided.)
These axes are largely independent: one can have a fully automatic, 3D, panoptic segmentation of cardiac chambers, or an interactive, 2D, semantic segmentation of retinal vessels. The Cartesian product of all four axes defines a combinatorial space of possible segmentation problems, and real-world clinical applications occupy specific points in this space.
fig:medseg:taxonomy:tree presents the full taxonomy as a tree diagram. We devote one subsection to each axis, developing formal definitions where appropriate and highlighting the implications for generative modelling at each branch.
By Output Structure
The most fundamental distinction among segmentation tasks is the kind of label map the model produces. Three paradigms dominate the field, each with increasing structural richness: semantic segmentation, instance segmentation, and panoptic segmentation. Understanding the formal differences among them is essential because each paradigm demands different loss functions, different evaluation metrics, and different generative augmentation strategies.
Semantic Segmentation
In semantic segmentation, every pixel (or voxel) receives a class label drawn from a fixed, predefined set of categories. Two pixels belonging to two different kidneys both receive the label “kidney”; the model does not distinguish between individual instances of the same class.
Definition 4 (Semantic Segmentation).
Let be an input image with channels, spatial height , and spatial width . Let be a set of semantic classes, where class typically denotes background. A semantic segmentation of is a map (Semantic) assigning each spatial location to exactly one class . Equivalently, can be represented as a one-hot tensor satisfying for all .
Semantic segmentation is the most common formulation in organ-level medical imaging. When a radiologist delineates the liver on an abdominal CT scan, they produce a semantic map with two classes (liver and background). Multi-organ segmentation extends this to dozens of classes: liver, spleen, pancreas, left kidney, right kidney, aorta, and so on. The TotalSegmentator project, for instance, provides semantic labels for 104 anatomical structures in whole-body CT, ranging from skeletal bones to the portal vein.
The key limitation of semantic segmentation is that two distinct instances of the same class, say two separate liver lesions, are merged into a single connected component in the label map, making it impossible to count or individually characterise them. If a CT scan contains three separate metastatic lesions in the liver, all three receive the label “lesion” and are indistinguishable in the output map unless they happen to be spatially disconnected.
From the perspective of generative modelling, semantic segmentation benefits from augmentation strategies that preserve class boundaries. A diffusion model generating synthetic training pairs must produce images whose organ boundaries are anatomically plausible and whose class labels are pixel-accurate. We will return to this requirement when discussing conditional generation in later sections.
Instance Segmentation
Instance segmentation goes beyond class labels to identify individual objects. Two cells of the same type receive different instance identifiers, enabling the model to count them, measure their properties individually, and track them across frames.
Definition 5 (Instance Segmentation).
Let be an input image. An instance segmentation of is a collection of binary masks , where each mask delineates the spatial extent of instance , and is its class label. Masks may overlap in general, but in standard settings we require (Instance) ensuring each pixel belongs to at most one instance (with pixels not covered by any mask assigned to background).
Instance segmentation is indispensable in cellular and histological analysis. Consider a pathologist examining a haematoxylin and eosin (H&E) stained tissue section under the microscope. The slide may contain thousands of nuclei, many touching or overlapping, and the clinical question often requires counting specific cell types (e.g., the mitotic index in breast cancer grading) or measuring individual cell morphology (nuclear pleomorphism). Semantic segmentation would fuse all nuclei into a single “nucleus” region, losing the ability to count. Instance segmentation preserves individual identity.
The challenge for generative models in this setting is combinatorial: the number of instances varies across images and can range from a handful (large tumour regions) to thousands (dense cell clusters). A generative model must learn not only the appearance of individual instances but also their spatial distribution, including the statistics of touching, overlapping, and clustering.
Panoptic Segmentation
Panoptic segmentation unifies semantic and instance segmentation into a single framework by distinguishing between two categories of scene elements:
Stuff classes represent amorphous, uncountable regions: background tissue, stroma, necrotic areas, or interstitial fluid. These receive only semantic labels.
Thing classes represent countable, individual objects: cells, nuclei, glands, polyps, or nodules. These receive both a semantic class label and a unique instance identifier.
Definition 6 (Panoptic Segmentation).
Let be a partition of the class set into stuff and thing categories. A panoptic segmentation of image is a map (Panoptic) where assigns pixel to class with instance identifier . For stuff classes , all pixels of class share the same instance identifier . For thing classes , distinct objects of the same class receive distinct identifiers .
Panoptic segmentation has gained traction in computational pathology, where a tissue slide contains both amorphous regions (stroma, necrosis, inflammation) and countable structures (glands, nuclei, vessels). The PanNuke dataset, for example, provides panoptic annotations across 19 tissue types with five nucleus categories and surrounding tissue context.
For generative augmentation, panoptic segmentation imposes the strongest constraints: the generated image-label pairs must respect both the semantic coherence of stuff regions (tissue texture must match the label) and the instance-level fidelity of thing regions (each generated nucleus must be individually delineated). This dual requirement pushes the limits of current generative models and is an active area of research.
Key Idea.
Output Structure Determines Loss and Evaluation The choice of output structure propagates through the entire pipeline. Semantic segmentation is evaluated by per-class Dice coefficients and pixel accuracy. Instance segmentation requires matching predicted instances to ground-truth instances (typically via the Hungarian algorithm or intersection-over-union matching) before computing average precision. Panoptic segmentation uses the Panoptic Quality (PQ) metric, which decomposes into detection quality (did the model find the right instances?) and segmentation quality (did it delineate them accurately?). When designing a generative augmentation pipeline, the generated data must be evaluated against the same metrics used for the downstream task; otherwise, the augmentation may improve pixel-level accuracy while degrading instance-level detection.
By Spatial Dimensionality
Medical images span a wider range of spatial and temporal dimensionalities than natural images. While a photograph from a smartphone is always a 2D RGB image, a medical scan may be a single 2D frame, a 3D volume, a 2D video sequence, or even a full 4D spatio-temporal volume. Each dimensionality brings distinct computational challenges and opportunities for generative models.
2D: Single Slice or Frame
The simplest setting treats each image independently as a 2D array of pixels. This is the natural format for several important modalities:
Chest X-ray: a projection image capturing the entire thorax on a single 2D plane. Segmentation targets include the lung fields, cardiac silhouette, mediastinal structures, and pathological opacities.
Dermatoscopy: a magnified photograph of a skin lesion. The segmentation task is to delineate the lesion boundary from surrounding healthy skin.
Histopathology: a single focal plane captured from a whole-slide scanner. Despite the gigapixel resolution, each tile is processed as a 2D image.
Retinal fundus photography: a 2D image of the retinal surface, used for segmenting vessels, the optic disc, and pathological lesions such as microaneurysms.
In the 2D setting, standard convolutional architectures (U-Net and its descendants) operate directly on the image plane. Generative models for 2D augmentation are the most mature, as they can leverage the extensive infrastructure developed for natural image generation (GANs, diffusion models, VAEs) with relatively straightforward adaptation to the medical domain.
3D: Volumetric Data
Many tomographic imaging modalities produce full 3D volumes:
Computed tomography (CT): a stack of axial slices reconstructed from X-ray projections, producing a volume where is the number of slices along the axial direction.
Magnetic resonance imaging (MRI): volumetric acquisitions with rich soft-tissue contrast. Multiple sequences (T1, T2, FLAIR, T1-contrast) can be stacked as channels, yielding .
Positron emission tomography (PET): functional imaging that measures metabolic activity in 3D.
Three-dimensional segmentation introduces two immediate challenges. First, memory: a CT volume of size contains approximately million voxels, each of which needs a label. Naively applying a 3D U-Net with sufficient feature channels quickly exceeds GPU memory. Practical solutions include patch-based processing (segmenting overlapping 3D cubes and stitching the results), sliding-window inference, and architectures that combine 2D feature extraction with 3D context aggregation.
Second, anisotropy: the voxel spacing along the axial direction (slice thickness) is often much larger than the in-plane resolution. A typical abdominal CT has in-plane spacing of but slice thickness of , making the voxels elongated rather than cubic. Models must account for this anisotropy either through preprocessing (resampling to isotropic spacing) or through architecture design (anisotropic kernel sizes).
For generative models, 3D data is particularly demanding. A 3D diffusion model must learn to generate spatially coherent volumes where anatomical structures maintain correct topology across all three axes. The memory and compute costs grow cubically with resolution, limiting current 3D generative models to relatively coarse resolutions or requiring hierarchical generation strategies (e.g., generating a low-resolution volume and super-resolving it).
Insight.
A pragmatic compromise between 2D and 3D processing is the 2.5D approach: the model processes a stack of consecutive 2D slices (e.g., three adjacent axial slices) as a multi-channel input, gaining limited 3D context without the full memory cost of a 3D convolution. For generative augmentation, this means one can use a 2D diffusion model augmented with neighbouring-slice conditioning rather than building a full 3D generative model. This approach sacrifices inter-slice coherence at long range but is often sufficient for structures that change gradually across slices (e.g., the liver) while being inadequate for structures with fine axial detail (e.g., the pancreatic duct).
2D+Time: Video and Cine Sequences
Some medical imaging modalities produce sequences of 2D frames evolving over time:
Endoscopy video: a camera navigating the gastrointestinal tract captures 25–30 frames per second. Polyp segmentation must operate in real time, and the same polyp appears across many consecutive frames with changing viewpoint, illumination, and deformation.
Ultrasound cine loops: echocardiography records short video sequences of the beating heart. Segmenting the left ventricle across all frames enables measurement of ejection fraction, a key cardiac function metric.
Time-lapse microscopy: live cell imaging records cell behaviour over hours or days at intervals of seconds to minutes. Beyond per-frame segmentation, the temporal dimension enables cell tracking, lineage reconstruction, and detection of division events.
The 2D+ setting introduces temporal consistency as a new requirement. A segmentation that is accurate on each individual frame but flickers wildly between frames is clinically useless; the boundaries of a tracked structure should evolve smoothly. Formally, if denotes the segmentation mask at frame , then a temporally consistent segmentation satisfies (Consistency) where is the optical flow warp from frame to frame and is a small tolerance reflecting true deformation between frames. In practice, this constraint is enforced either through temporal loss terms during training or through post-processing with tracking algorithms.
Generative models for 2D+ data must capture both spatial appearance and temporal dynamics, a challenge closely related to video generation. Video diffusion models, which generate sequences of frames jointly rather than independently, are a natural fit for this setting but remain computationally expensive.
4D: 3D+Time (Spatio-Temporal Volumes)
The most demanding setting combines three spatial dimensions with time:
Dynamic cardiac MRI: short-axis cine MRI captures 20–30 3D volumes per heartbeat. Segmenting the left ventricle, right ventricle, and myocardium across all time frames enables measurement of wall motion, strain, and ejection fraction.
Respiratory-gated CT (4D CT): a sequence of 3D CT volumes captured at different phases of the respiratory cycle. Segmenting lung tumours across phases is essential for radiation therapy planning, where the tumour's motion envelope determines the treatment margin.
A 4D dataset can contain voxel-frames, over million elements. The computational cost of both segmentation and generative modelling at this scale is prohibitive for most current methods. Practical approaches typically decompose the problem: segment individual 3D volumes independently and enforce temporal smoothness as a post-processing step, or use lightweight temporal models (recurrent connections, temporal attention) on top of spatial features.
By Clinical Target
The clinical target, the specific anatomy or pathology to be segmented, determines the unique challenges that a segmentation model must address. Each organ system and tissue type presents its own combination of difficulties: class imbalance, inter-rater variability, topological sensitivity, scale variation, and domain shift. This subsection surveys the major clinical domains, emphasising the characteristics that make each domain a distinctive challenge for both discriminative and generative models.
We summarise the landscape in tab:medseg:clinical:overview before diving into detailed discussions of each domain.
| p1.8cmp2.0cmp4.0cmp4.2cm@ Domain | Modality | Key Challenges | Generative Interventions |
| Cells & Microscopy | Fluorescence, phase-contrast, EM | Dense clusters, division events, domain shift across stains | Style transfer (GAN), synthetic cell generation (DM) |
| [4pt] Lung & Thorax | CT, chest X-ray | Nodule size variation, multi-radiologist variability, low contrast | Nodule synthesis (GAN/DM), multi-rater ambiguity modelling |
| [4pt] Brain & Neuro | MRI (T1, T2, FLAIR, T1ce) | Tumour subregion heterogeneity, white matter lesion variability, small vessel segmentation | Synthetic tumour insertion (DM), multi-sequence generation |
| [4pt] Abdomen | CT, MRI | Extreme class imbalance (pancreas vs. liver), organ size disparity, contrast variation | Organ-conditioned synthesis (GAN/DM), data augmentation for rare organs (VAE) |
| [4pt] Cardiac | MRI (cine), echo\-cardiography | Temporal motion, thin myocardium, phase variability | Cardiac cycle generation (DM), temporal augmentation |
| [4pt] Vessels | CTA, MRA, fundus, OCT-A | Extreme topology sensitivity, thin tubular structures, bifurcation fidelity | Topology-aware generation, synthetic vascular trees (GAN) |
| [4pt] Endoscopy | Video endoscopy | Motion blur, deformation, specular reflections, occlusion | Frame synthesis (GAN/DM), video augmentation |
| [4pt] Pathology | H&E, IHC, whole-slide images | Gigapixel resolution, staining domain shift, dense nuclei | Stain normalisation (GAN), synthetic tile generation (DM) |
Cells and Microscopy
Cellular-level segmentation is among the oldest problems in biomedical image analysis, predating deep learning by decades. The task is deceptively simple in concept, identify the boundary of each cell in a microscopy image, but fiendishly difficult in practice.
Imaging modalities.
The three principal modalities are:
Fluorescence microscopy: specific cellular structures (nuclei, membranes, organelles) are tagged with fluorescent markers that glow under excitation light. Images have high signal-to-noise ratio for tagged structures but zero signal elsewhere.
Phase-contrast microscopy: a label-free technique that converts phase shifts in transmitted light into intensity differences, producing translucent images with characteristic halos around cell boundaries. No staining is required, making it ideal for live-cell imaging.
Electron microscopy (EM): nanometre-resolution imaging of ultrastructure. In connectomics, large EM volumes are segmented to reconstruct neural circuits. The data volumes are enormous (teravoxels), and the segmentation problem is fundamentally 3D.
Characteristic challenges.
Cell segmentation differs from organ segmentation in several critical ways:
Dense clusters: cells in tissue often form confluent monolayers or dense 3D aggregates where boundaries between adjacent cells are ambiguous even to human experts. Splitting touching cells is the central algorithmic challenge.
Division events: in time-lapse imaging, a single mother cell divides into two daughter cells over the course of a few frames. The segmentation must handle the topological change from one connected component to two, and the tracking algorithm must correctly assign lineage.
Tracking: beyond per-frame segmentation, the temporal association of the same cell across frames is required for any quantitative analysis of cell behaviour (migration speed, division rate, apoptosis timing).
Domain shift: fluorescence images from different microscopes, staining protocols, and cell types look dramatically different. A model trained on fluorescent nuclei in HeLa cells may fail completely on phase-contrast images of fibroblasts.
Generative models address these challenges through synthetic data generation (creating realistic microscopy images with known ground-truth segmentations), style transfer (adapting models across imaging modalities), and uncertainty estimation (modelling the ambiguity of cell boundaries in dense clusters). The SplineDist and StarDist frameworks, for example, represent cell shapes as parameterised contours (star-convex polygons or spline curves), and a generative model operating in this shape space can produce diverse, biologically plausible cell populations far more efficiently than pixel-level generation.
Lung and Thorax
The lung and thorax are the most frequently imaged region of the body, owing to the ubiquity of chest X-rays in clinical practice and the central role of CT in lung cancer screening, pulmonary disease assessment, and COVID-19 diagnosis. Segmentation tasks in this domain span a wide range of scales, from delineating the entire lung fields on a chest radiograph to detecting sub-centimetre pulmonary nodules on a CT scan.
Multi-radiologist variability.
A defining characteristic of lung nodule segmentation is the high degree of inter-rater variability. The LIDC-IDRI (Lung Image Database Consortium and Image Database Resource Initiative) dataset provides annotations from four independent radiologists for each nodule. The radiologists frequently disagree on the exact boundary, sometimes dramatically: one radiologist may include a ground-glass opacity surrounding the solid core while another delineates only the solid component. The extent of disagreement depends on nodule subtype (solid, part-solid, or ground-glass), nodule size, and the relationship of the nodule to adjacent structures such as vessels or the pleural surface.
This variability is not noise to be averaged away; it reflects genuine clinical uncertainty about the correct boundary. A generative model that captures this uncertainty, for instance by learning a distribution over plausible segmentation masks rather than predicting a single deterministic mask, provides clinically valuable information. We will formalise this connection between annotation ambiguity and probabilistic segmentation in By Annotation Interface.
Brain and Neuroimaging
The brain presents a rich and complex segmentation landscape. Three major categories of targets dominate the literature:
Brain tumours.
The Brain Tumor Segmentation (BraTS) challenge has been a flagship benchmark since 2012. The task is to segment gliomas from multi-parametric MRI into three nested subregions: the enhancing tumour (ET), the tumour core (TC, comprising ET plus non-enhancing tumour and necrosis), and the whole tumour (WT, comprising TC plus peritumoral oedema/invasion). Each subregion appears with different intensity characteristics across the four MRI sequences (T1, T1 with gadolinium contrast, T2, and FLAIR), making multi-sequence fusion essential.
White matter lesions.
In multiple sclerosis and other demyelinating diseases, white matter lesions appear as hyperintense spots on FLAIR images. They are small, irregularly shaped, and scattered throughout the brain. The segmentation challenge is detecting and delineating many small objects in a large 3D volume, a problem characterised by extreme class imbalance (lesion voxels constitute a tiny fraction of the brain volume).
Cerebrovascular structures.
Segmenting the brain's vascular tree from MR angiography (MRA) or CT angiography (CTA) images is critical for stroke risk assessment, aneurysm detection, and surgical planning. The vessels are thin, branching, and tortuous, requiring models that are sensitive to fine topological details.
For generative models, brain segmentation is appealing because of the well-standardised MRI protocols and the availability of large, curated datasets. The multi-sequence nature of the data also creates opportunities for cross-modal generation: a generative model can synthesise missing MRI sequences from available ones, enabling segmentation even when the full protocol was not acquired.
Abdomen
The abdomen contains a dense collection of organs with widely varying sizes, shapes, and imaging characteristics. Multi-organ abdominal segmentation, the simultaneous delineation of liver, spleen, pancreas, kidneys, adrenal glands, gallbladder, aorta, inferior vena cava, stomach, and other structures, has emerged as a central benchmark task.
Class imbalance and organ size disparity.
The liver may occupy in a CT volume while the pancreas occupies barely , a ratio of over in volume. The adrenal glands are smaller still. This extreme class imbalance means that a model optimised for overall accuracy can achieve excellent performance by segmenting the liver well and ignoring the pancreas entirely. Loss functions that handle class imbalance (Dice loss, focal loss, compound losses) are essential, and generative augmentation can help by synthesising additional training examples focused on rare or small organs.
Contrast variation.
Abdominal CT scans are acquired at different phases of intravenous contrast enhancement (non-contrast, arterial, portal venous, delayed), and each phase highlights different structures. The liver's appearance changes dramatically between non-contrast and portal venous phases. Models must either be trained on a specific phase or learn to be phase-invariant, a challenge that generative models can address by synthesising images across contrast phases.
Datasets and benchmarks.
The Beyond the Cranial Vault (BTCV) challenge, the AMOS (Abdominal Multi-Organ Segmentation) challenge, and the AbdomenCT-1K dataset have established standardised benchmarks for multi-organ abdominal segmentation. AMOS, notably, includes both CT and MRI scans, enabling cross-modality evaluation. The availability of these large, curated datasets has made the abdomen a fertile testing ground for generative augmentation methods: researchers can directly measure whether synthetic training data generated by GANs or diffusion models improves Dice scores on held-out test sets.
Cardiac
Cardiac image segmentation focuses on delineating the chambers of the heart (left ventricle, right ventricle, left atrium, right atrium) and the myocardium (heart muscle). The primary imaging modalities are cine cardiac MRI and echocardiography.
Temporal motion.
The heart is perpetually in motion, cycling between systole (contraction) and diastole (relaxation) approximately once per second. A cine MRI sequence captures 20–30 frames per cardiac cycle, and the segmentation must track the dramatic shape changes of the ventricles as they contract and expand. The left ventricular wall may thin to just 2–3 voxels at end-systole, making boundary detection extremely challenging.
Thin structures.
The myocardium, particularly the right ventricular free wall, can be only one or two voxels thick in standard cardiac MRI acquisitions. At this resolution, the distinction between “inside the wall” and “outside the wall” hinges on subvoxel positioning, and inter-observer agreement drops sharply. Generative models that produce multiple plausible segmentations can capture the resulting uncertainty.
Vessels
Vascular segmentation, the delineation of blood vessels from surrounding tissue, is one of the most topologically sensitive segmentation tasks in medical imaging.
Topology sensitivity.
A small error in an organ segmentation (misplacing the liver boundary by two pixels) may barely affect volumetric measurements. But a small error in vascular segmentation can have catastrophic consequences: a single missed voxel at a bifurcation point can disconnect an entire vascular subtree, falsely suggesting vessel occlusion. Conversely, a spurious connection between two nearby vessels (a false positive bridge) can alter the computed blood flow paths. This extreme sensitivity to topological correctness sets vascular segmentation apart from most other domains.
Major application areas.
Vascular segmentation spans several clinical areas:
Retinal vessels: segmented from fundus photographs or optical coherence tomography angiography (OCT-A). Vessel tortuosity, calibre, and branching patterns are biomarkers for diabetic retinopathy, hypertension, and systemic cardiovascular disease.
Coronary arteries: segmented from CT angiography for detection of stenosis and planning of percutaneous coronary intervention.
Cerebral vessels: segmented from MRA or CTA for aneurysm detection and stroke assessment.
For generative models, vascular segmentation demands topology-preserving generation. A GAN that generates realistic vessel images but occasionally creates disconnected segments or false anastomoses produces training data that teaches the segmentation model incorrect topological priors. Recent work has explored topology-aware loss functions (based on persistent homology) and graph-based generative models that explicitly construct vascular trees.
Endoscopy
Endoscopic imaging captures the internal surfaces of the gastrointestinal tract, the airways, or other body cavities using a camera mounted on a flexible tube. The dominant segmentation task is polyp detection and segmentation in colonoscopy, driven by colorectal cancer screening programmes.
Unique challenges.
Endoscopy video introduces challenges rarely encountered in other medical imaging modalities:
Motion and deformation: the camera and the tissue both move. The colon wall deforms under insufflation (inflation with air or CO), and peristalsis causes the tissue to undulate. Polyps change apparent shape as the camera angle shifts.
Specular reflections: the moist mucosal surface produces bright specular highlights that move with the camera and can obscure or mimic lesion boundaries.
Occlusion: folds in the colon wall can partially hide polyps, and residual faecal matter or bubbles may obscure the view.
Real-time requirement: clinical decision support systems for colonoscopy must operate in real time (at least 25 frames per second), constraining model complexity.
Generative augmentation for endoscopy is particularly valuable because annotation requires expert gastroenterologists, whose time is expensive and limited. GAN-based and diffusion-based polyp synthesis can expand small annotated datasets (such as Kvasir-SEG or CVC-ClinicDB, which contain only a few hundred annotated frames) by orders of magnitude. Moreover, the visual realism bar is relatively low compared to, say, brain MRI: the endoscopy community has demonstrated that even moderately realistic synthetic polyps improve downstream segmentation performance, likely because the diversity of synthetic shapes and textures compensates for the limited variety in small real datasets.
A further complication is the frame-level annotation gap: in a typical colonoscopy video of 30 minutes at 25 fps, over 45,000 frames are captured, but only a small fraction contain visible polyps, and even fewer are annotated. Active learning strategies that combine generative models with selective annotation can prioritise the most informative frames for expert labelling.
Pathology and Histology
Computational pathology operates at the intersection of microscopy and clinical medicine. A whole-slide image (WSI) captured by a digital slide scanner at magnification can contain pixels or more, a single image larger than the entire ImageNet dataset in pixel count.
Segmentation targets.
The two primary targets are:
Nuclei: individual cell nuclei are segmented and classified (tumour, lymphocyte, stromal, epithelial, etc.) for tasks such as tumour grading, immune cell quantification, and spatial biology.
Glands: glandular structures are segmented from surrounding stroma for colorectal cancer grading (the Gleason grading system in prostate cancer is based on gland morphology).
Staining domain shift.
The appearance of histology images is profoundly affected by the staining protocol. Haematoxylin and eosin (H&E) staining, the universal default, produces blue nuclei on a pink background. But the exact shades of blue and pink vary dramatically across laboratories, depending on reagent concentration, staining duration, section thickness, and scanner calibration. A model trained on H&E slides from one hospital may fail on slides from another. Immunohistochemistry (IHC) stains produce yet another appearance.
Generative models offer a powerful solution to staining domain shift through stain normalisation and stain transfer. A CycleGAN or a diffusion model can transform the appearance of a slide from one staining domain to another while preserving the underlying tissue morphology, effectively harmonising datasets from multiple institutions without requiring paired data.
Example 3 (Lung Nodule Annotation: The LIDC-IDRI Dataset).
The LIDC-IDRI dataset contains 1018 chest CT scans with annotations from four board-certified radiologists. Each radiologist independently reviewed each scan and marked nodules in diameter. Consider a part-solid nodule in the right upper lobe. The four radiologists produced the following annotations:
Radiologist A delineated only the solid core, producing a compact mask of approximately .
Radiologist B included the surrounding ground-glass halo, yielding a larger mask of approximately .
Radiologist C followed the solid core but added a narrow margin, producing .
Radiologist D agreed closely with Radiologist B but excluded a small region near an adjacent vessel, yielding .
The pairwise Dice coefficients among these four annotations range from (A vs. B) to (B vs. D). The “correct” segmentation is undefined; the four annotations represent four equally valid clinical interpretations.
This example illustrates a fundamental principle: in many medical segmentation tasks, there is no single ground truth. The label map is a random variable, not a deterministic function of the image. A generative model that learns the conditional distribution rather than a single point estimate can capture this clinically important uncertainty. We will formalise this perspective in the next chapter when we discuss probabilistic segmentation and the stochastic segmentation network.
Example 4 (Brain Tumour Subregion Segmentation: The BraTS Challenge).
The BraTS (Brain Tumor Segmentation) challenge provides multi-institutional MRI data of glioma patients, each with four co-registered MRI sequences: T1-weighted, T1 with gadolinium contrast enhancement (T1ce), T2-weighted, and FLAIR. The segmentation task requires delineating three nested tumour subregions:
Enhancing Tumour (ET): the portion of the tumour that shows bright enhancement on T1ce, indicating active tumour with a disrupted blood-brain barrier. This is the most clinically relevant subregion for surgical targeting and treatment monitoring.
Tumour Core (TC): the union of enhancing tumour, non-enhancing tumour, and necrotic regions. On T1ce, the non-enhancing and necrotic portions appear dark within the enhancing rim.
Whole Tumour (WT): the union of the tumour core and the surrounding peritumoral oedema/invasion zone, which appears hyperintense on FLAIR and T2.
The nested structure means WT TC ET, and each subregion is best visualised on a different MRI sequence. This multi-sequence, multi-label problem showcases several challenges:
Information fusion: the model must learn which sequence is informative for which subregion (FLAIR for oedema, T1ce for enhancement).
Label hierarchy: the nested structure provides built-in consistency constraints that the model should respect.
Missing sequences: in clinical practice, one or more sequences may be unavailable due to acquisition protocol variations or patient intolerance.
Generative models contribute to BraTS-style problems in two ways. First, synthetic tumour generation: a diffusion model conditioned on tumour location and grade can insert realistic synthetic tumours into healthy brain MRI, augmenting the training set without requiring additional patient data. Second, missing-sequence imputation: a generative model can synthesise the missing T1ce from available T1, T2, and FLAIR sequences, enabling segmentation even when the full four-sequence protocol was not acquired.
Example 5 (Cell Tracking in Time-Lapse Microscopy).
Consider a time-lapse fluorescence microscopy experiment imaging GFP-labelled HeLa cells over 48 hours at 5-minute intervals, producing a sequence of 576 frames. At the beginning of the experiment, approximately 50 cells are visible; by the end, the population has grown to over 500 through successive rounds of cell division.
The segmentation and tracking pipeline must solve three coupled problems:
Per-frame instance segmentation: delineate each cell in every frame. As the culture becomes confluent, cells flatten and press against their neighbours, making boundaries increasingly difficult to resolve.
Temporal association: link the same cell across consecutive frames. Between frames (5 minutes apart), cells may migrate by several cell diameters, change shape dramatically, or partially overlap with neighbours.
Division detection: identify frames where a mother cell splits into two daughter cells. During mitosis, the cell rounds up, becoming temporarily brighter and more compact, before dividing. The tracking algorithm must create a branching event in the lineage tree.
The Cell Tracking Challenge (CTC) provides standardised benchmarks for this problem across multiple cell types and imaging conditions. Generative models can assist in several ways: synthesising realistic cell populations at various densities to augment sparse training sets, generating plausible division sequences for training division detectors, and providing uncertainty estimates for ambiguous associations in dense regions.
By Annotation Interface
The final axis of our taxonomy concerns not the data or the target but the mode of interaction between the user and the segmentation system. How much guidance does the model receive at inference time? The answer ranges from none (fully automatic) to rich, iterative interaction (interactive and text-guided segmentation). This axis has gained particular importance with the recent emergence of foundation models for segmentation, such as the Segment Anything Model (SAM), which blur the boundary between automatic and interactive paradigms.
Fully Automatic Segmentation
In the fully automatic setting, the model receives an image as input and produces a segmentation mask as output with no human guidance at inference time. This is the classical formulation: train a U-Net on a labelled dataset, then deploy it to segment new images without any user interaction.
Fully automatic segmentation is appropriate when:
The target is well-defined and unambiguous (e.g., lung fields on a chest X-ray).
High throughput is required (e.g., screening thousands of CT scans for lung nodules).
Expert availability is limited and the model must operate autonomously.
The principal limitation is that the model cannot resolve ambiguity without human input. When the image is ambiguous (Is that shadow a nodule or a vessel? Should the ground-glass halo be included in the nodule boundary?), the fully automatic model must commit to a single answer. A probabilistic model can express uncertainty through multiple samples, but the user has no mechanism to guide the model toward the clinically relevant interpretation.
Most clinical deployment scenarios today use fully automatic segmentation with a human-in-the-loop verification step: the model produces a draft segmentation, a radiologist reviews and corrects it, and the corrected mask is used for clinical decisions. This workflow reduces annotation time by – compared to manual delineation from scratch but still requires expert oversight.
Interactive Segmentation
Interactive segmentation allows the user to provide spatial prompts at inference time that guide the model toward the desired segmentation. The prompts can take several forms:
Point prompts: the user clicks on the object of interest (positive point) or on the background (negative point). The model uses these sparse signals to infer the full segmentation mask.
Bounding box prompts: the user draws a bounding box around the object. The model segments the dominant object within the box.
Scribble prompts: the user draws rough strokes on the object and background. The model propagates these labels to the full mask.
Iterative refinement: after an initial segmentation, the user provides additional positive or negative clicks to correct errors, and the model updates its prediction.
Definition 7 (Interactive Segmentation).
Let be an input image and let be a set of user-provided spatial prompts, where is a pixel location and indicates a positive (foreground) or negative (background) prompt. An interactive segmentation model is a function (Interactive) mapping the image and the set of prompts to a soft segmentation mask. The model may optionally accept bounding box prompts or text prompts as additional input modalities.
The Segment Anything Model (SAM) brought interactive segmentation to the forefront of medical imaging research. SAM and its medical variants (MedSAM, SAM-Med2D, SAM-Med3D) accept point and box prompts and produce segmentation masks across a wide range of anatomical targets without task-specific fine-tuning. The interactive paradigm is transformative for medical image annotation: a radiologist can segment a new structure by providing a few clicks, and the model fills in the detailed boundary, dramatically reducing annotation time.
Weakly Supervised Segmentation
Pixel-level annotation is expensive: delineating all organs on a single abdominal CT volume can take a radiologist 30 minutes to several hours. Weakly supervised segmentation seeks to train segmentation models from cheaper, coarser forms of annotation:
Image-level labels: only the presence or absence of a pathology is annotated, with no spatial information. Class activation maps (CAMs) or attention mechanisms localise the pathology, and the model must learn to segment from these noisy localisations.
Point annotations: a single point is placed on each object of interest, providing approximate location but no boundary information.
Scribble annotations: rough strokes are drawn on the foreground and background, providing sparse but spatially distributed labels.
Bounding boxes: axis-aligned rectangles surrounding each object, providing location and approximate extent but not precise boundaries.
Generative models play a natural role in weakly supervised segmentation: they can hallucinate plausible dense masks from sparse annotations, effectively converting a weakly supervised problem into a (noisily) fully supervised one. A diffusion model conditioned on scribble annotations can sample multiple plausible full masks, providing both a pseudo-label for training and an uncertainty estimate derived from the variance across samples. The appeal of this approach is that it decouples two expensive steps: dense annotation (which requires expert time) and model training (which requires labelled data). Generative models serve as an annotation amplifier, transforming cheap, sparse labels into rich, dense supervision signals.
Text-Guided Segmentation
The most recent addition to the annotation interface taxonomy is text-guided segmentation, where the user specifies the segmentation target through a natural language description rather than spatial prompts. Instead of clicking on the liver, the user types “segment the liver” or, more usefully, “segment the hyperintense lesion in the right hepatic lobe.”
Text-guided segmentation leverages the remarkable zero-shot capabilities of vision-language models. By jointly embedding images and text into a shared representation space, models such as CLIP can match textual descriptions to visual regions, enabling open-vocabulary segmentation of targets not seen during training. Medical adaptations (BiomedCLIP, PubMedCLIP) are beginning to bridge the domain gap, though the specificity of medical terminology (“segment the enhancing tumour rim on T1ce”) remains challenging.
The connection between text-guided segmentation and generative models is deep. Text-conditioned diffusion models (Stable Diffusion, DALL-E) already perform implicit segmentation through their cross-attention maps: the attention weights connecting the text token “liver” to spatial locations in the generated image form a soft segmentation mask. Extracting and refining these attention maps provides a path to text-guided segmentation that requires no explicit segmentation annotations at all.
Historical Note.
The evolution of annotation interfaces in medical image segmentation mirrors the broader history of human-computer interaction. Early systems (1970s–1990s) were entirely manual: radiologists traced organ boundaries on film with a light pen or digitising tablet. Semi-automatic methods emerged in the 2000s, combining user-placed seed points with level-set or graph-cut algorithms to propagate boundaries. The deep learning revolution (2015–) initially focused on fully automatic segmentation (U-Net and its successors), swinging the pendulum away from interaction. The recent rise of foundation models (2023–) has brought interactivity back to the centre, but now at a dramatically higher level of capability: a single click can segment an organ that would have taken dozens of manual trace points a decade ago. The trajectory is not from manual to automatic but from manual to a partnership between human expertise and model capability, with generative uncertainty estimates forming the communication channel.
Caution.
Taxonomy Axes Are Not Exhaustive The four axes presented here (output structure, spatial dimensionality, clinical target, annotation interface) capture the most important dimensions of variation, but they are not exhaustive. Other meaningful axes include:
Number of classes: binary vs. multi-class vs. hierarchical label sets.
Open vs. closed vocabulary: whether the set of possible targets is fixed at training time or can be specified at inference time (as in text-guided segmentation).
Batch vs. streaming: whether the model processes a complete scan at once or must produce predictions incrementally as data arrives (relevant for real-time endoscopy and intraoperative imaging).
Domain generalisation requirement: whether the model is expected to work only on data from the training distribution or must generalise across institutions, scanners, and patient populations.
These additional axes become relevant when designing specific generative augmentation strategies and will be addressed in later sections as needed.
Remark 2.
There is a deep connection between the annotation interface axis and the problem of label ambiguity. Fully automatic segmentation forces the model to commit to a single interpretation; interactive segmentation allows the user to resolve ambiguity through prompts; weakly supervised methods must contend with the ambiguity inherent in coarse labels; and text-guided methods inherit the ambiguity of natural language (“segment the tumour” is less precise than a click on a specific voxel).
Generative models sit at the intersection of these concerns. A conditional generative model can sample multiple plausible segmentations for a given image and prompt, explicitly representing the residual ambiguity that the prompt does not resolve. In the fully automatic setting (no prompt), the distribution captures the full annotation variability. With a precise interactive prompt (e.g., a detailed set of positive and negative clicks), the conditional distribution collapses toward a point mass, reflecting the reduced ambiguity. The annotation interface, in this view, determines how much of the total annotation entropy is resolved by the user and how much remains for the model to express.
Exercise 6.
For each of the following clinical scenarios, identify the appropriate choice on each of the four taxonomy axes (output structure, spatial dimensionality, clinical target, annotation interface). Justify your answers.
A pathologist wishes to count the number of mitotic figures in a breast biopsy H&E slide to compute the mitotic index. The system should operate without user interaction on each tile extracted from the whole-slide image.
A radiologist is reviewing a dynamic cardiac MRI cine sequence and wants to measure the left ventricular ejection fraction. The system should segment the left ventricle across all time frames and compute the end-diastolic and end-systolic volumes.
A gastroenterologist performing a routine colonoscopy wants real-time highlighting of potential polyps in the video feed. The system should draw a boundary around each detected polyp to alert the endoscopist.
A neuroimaging researcher has a dataset of brain MRI scans with only image-level labels indicating the presence or absence of white matter lesions. They wish to train a model that can localise and delineate these lesions despite the absence of pixel-level annotations.
Hint: Consider what output structure is needed (does the scenario require counting individual objects, or only delineating regions?), what dimensionality the data has, what organ system is involved, and what level of user interaction is specified or implied.
Exercise 7.
Consider the problem of segmenting retinal vessels from fundus photographs, a 2D semantic segmentation task with extreme class imbalance (vessels occupy approximately 10–15% of the image area, and the finest capillaries are only 1–2 pixels wide).
Explain why standard pixel-wise cross-entropy loss is poorly suited to this task. What loss functions would you use instead, and why?
A GAN is trained to generate synthetic fundus images with corresponding vessel segmentation masks for data augmentation. During evaluation, you notice that the generated images look realistic, but the vessel trees occasionally contain disconnected segments (breaks in vessels that should be continuous). Explain why this is a serious problem for training a segmentation model, and propose a strategy to encourage topological correctness in the generated vessel trees.
Suppose you have access to a pre-trained diffusion model for fundus image generation. Describe how you would adapt this model to generate paired (image, vessel mask) training data. What conditioning mechanism would you use, and how would you ensure that the generated masks are pixel-aligned with the generated images?
Hint: For part (b), consider losses based on persistent homology or connectivity-based metrics. For part (c), consider joint generation, cascaded generation, or cross-attention-based conditioning.
Classical Segmentation Methods
Before deep learning reshaped the landscape of computer vision, medical image segmentation relied on a toolkit of classical algorithms, each grounded in explicit mathematical models of image appearance and geometry. These methods dominated the field for decades and produced clinically deployed systems for tasks ranging from bone segmentation in CT scans to white matter tractography in diffusion MRI\@. Understanding them is not merely a historical exercise: their mathematical formulations illuminate the assumptions that deep learning methods implicitly encode, and their failure modes motivate the architectural innovations that followed.
This section surveys the principal families of classical segmentation: thresholding and region growing, active contours and level sets, and atlas-based methods with random forests. We develop the mathematical framework for each, identify the conditions under which they succeed, and catalogue the systematic failures that ultimately drove the community toward learned representations.
Thresholding and Region Growing
The simplest approach to segmentation is thresholding: assign each pixel to a class based solely on its intensity value. If the image contains exactly two tissue types whose intensity distributions are well separated, a single threshold partitions the image into foreground and background: (Threshold) where denotes the intensity at pixel and is the resulting binary label.
Otsu's method.
The question is how to choose optimally. Otsu's method (1979) selects the threshold that maximises the between-class variance. Let the image intensities take values in with normalised histogram , where is the number of pixels with intensity and is the total pixel count. For a threshold , define the class probabilities (Probs) and the class means (Means) The between-class variance is (Variance) and the optimal threshold is .
Otsu's method works remarkably well when the intensity histogram is bimodal with well-separated peaks, as is often the case for bone segmentation in CT (where bone has Hounsfield units far above soft tissue) or for fluorescence microscopy with high signal-to-noise ratio. However, the method assumes a global threshold, which is problematic when intensity varies spatially due to bias fields, partial volume effects, or heterogeneous tissue composition.
Adaptive thresholding.
To handle spatial intensity variation, adaptive thresholding computes a local threshold for each pixel based on the statistics of a neighbourhood : (Adaptive Threshold) where is a constant offset. While more flexible than global thresholding, this approach introduces the neighbourhood size and offset as hyperparameters that must be tuned per imaging modality and acquisition protocol.
Region growing.
Region growing extends thresholding by incorporating spatial connectivity. Starting from one or more seed points placed by a human operator or detected automatically, the algorithm iteratively adds neighbouring pixels whose intensity falls within a tolerance of the current region mean: (Region Growing) where is the set of pixels neighbouring the current region, and is the mean intensity within the region at iteration . The process terminates when no new pixels satisfy the criterion.
Region growing produces connected components by construction, which is desirable for anatomical structures. However, it is exquisitely sensitive to the choice of seed points and the tolerance parameter. Too small a tolerance leads to under-segmentation; too large a tolerance causes the region to “leak” through weak boundaries into adjacent structures. In brain MRI, for example, a region growing from grey matter can leak into adjacent white matter wherever the intensity contrast is locally low.
Active Contours (Snakes)
The methods of the previous subsection treat each pixel independently (thresholding) or use only local intensity similarity (region growing). Neither encodes geometric priors about the shape of the structure being segmented. Active contours, introduced by Kass, Witkin, and Terzopoulos in their landmark 1988 paper, address this limitation by formulating segmentation as the minimisation of an energy functional that balances image evidence against geometric regularity.
Historical Note.
The Birth of Snakes. The active contour model was introduced by Michael Kass, Andrew Witkin, and Demetri Terzopoulos in their 1988 paper “Snakes: Active Contour Models” (Kass et al., 1988), published in the International Journal of Computer Vision. The paper proposed the idea of an energy-minimising spline that is attracted to image features such as edges while maintaining smoothness through internal forces. The name “snakes” came from the way the contour slithered along the image, deforming under the influence of competing forces. The model was originally developed for edge detection, image segmentation, and motion tracking. It became one of the most influential papers in computer vision, with applications extending far beyond its original scope into medical imaging, video analysis, and computational geometry. The energy minimisation framework proved so versatile that it spawned an entire family of variational methods for image analysis, including geodesic active contours, gradient vector flow, and the level set method.
Definition 8 (Active Contour Energy Functional).
An active contour (snake) is a parametric curve for that minimises the energy functional (Snake Energy) where:
is the elasticity parameter, penalising stretching of the contour (first-order smoothness);
is the rigidity parameter, penalising bending of the contour (second-order smoothness);
is the external energy derived from image features, typically defined as so that the contour is attracted to strong edges.
The internal energy acts as a regulariser, preventing the contour from developing sharp corners or oscillations. When is large, the contour behaves like a taut rubber band; when is large, it behaves like a rigid rod that resists bending. The external energy drives the contour toward image features. The balance between these two competing forces determines the final segmentation.
Euler–Lagrange equation.
The necessary condition for to minimise is given by the Euler–Lagrange equation: (Euler Lagrange) For constant and , this simplifies to (Euler Lagrange Const) This fourth-order differential equation is typically solved numerically by discretising the contour into control points and iterating a gradient descent scheme: (Snake Iteration) where is a pentadiagonal matrix encoding the discretised internal forces and is a step size.
Gradient vector flow.
A major limitation of the original snake model is its sensitivity to initialisation: the contour must be placed near the true boundary, because the external force decays rapidly away from edges. Xu and Prince (1998) addressed this with the gradient vector flow (GVF) field, which diffuses edge information throughout the image domain by solving the variational problem (GVF) where is the GVF field and controls the trade-off between smoothness and fidelity to the edge map. The GVF field replaces in the snake iteration, allowing the contour to converge from much farther away.
Level set formulation.
A fundamental limitation of parametric active contours is their inability to handle topological changes: if two separate objects merge during evolution, or a single object splits, the parametric representation breaks. The level set method, introduced by Osher and Sethian (1988) and applied to image segmentation by Caselles et al. (1993) and Malladi et al. (1995), overcomes this by representing the contour implicitly as the zero level set of a higher-dimensional function : (Level SET) The evolution of is governed by a partial differential equation that encodes both geometric regularity and image forces: (Level SET PDE) where is the mean curvature of the level set, is a constant inflation term, and is an edge-stopping function, typically , that slows the front near strong edges.
The level set formulation handles topological changes automatically: merging and splitting of regions correspond to changes in the topology of the zero level set, which occur naturally as evolves. This made level sets particularly popular for medical image segmentation, where structures can have complex topologies (e.g., blood vessel networks, brain sulci).
Random Forests and Atlas-Based Methods
While active contours encode geometric priors through energy functionals, they require careful initialisation and parameter tuning for each new image. A complementary family of methods learns to segment from labelled examples, using machine learning classifiers applied to handcrafted features.
Feature engineering for medical images.
Classical machine learning approaches to segmentation treat the problem as pixel-wise classification: for each pixel, extract a feature vector and predict a label . The feature vector typically includes:
Intensity features: raw intensity, local mean, local variance, gradient magnitude, Laplacian, computed at multiple scales using Gaussian pyramids.
Texture features: Haralick texture descriptors (contrast, homogeneity, entropy) derived from the grey-level co-occurrence matrix (GLCM), Gabor filter responses, and local binary patterns (LBP).
Context features: the intensity difference between the current pixel and randomly offset pixels, encoding long-range spatial relationships without explicit neighbourhood enumeration.
Location features: normalised coordinates encoding the spatial position within the image, which captures the prior that certain structures appear in predictable locations (e.g., the liver is always in the right upper quadrant of an abdominal CT).
Random forest classifiers.
Random forests, introduced by Breiman (2001), became the classifier of choice for medical image segmentation in the pre-deep learning era. A random forest consists of decision trees, each trained on a bootstrap sample of the training pixels with a random subset of features considered at each split. The ensemble prediction is the majority vote (or average probability) across trees: (Random Forest) where is the prediction of the -th tree.
Random forests for medical segmentation achieved remarkable success in several challenges, including the MICCAI brain tumour segmentation challenge (before deep learning methods surpassed them in 2016) and the multi-atlas segmentation challenge. Their advantages include fast training, inherent feature selection (important features appear higher in the trees), probabilistic outputs, and graceful handling of high-dimensional feature spaces. Their principal limitation is the reliance on handcrafted features: the feature engineering pipeline must be redesigned for each new modality and anatomy.
Multi-atlas label fusion.
Atlas-based methods take a different approach: rather than learning a classifier, they segment a new image by deformably registering one or more atlas images (images with known segmentations) to the target image and transferring the labels. Given atlas pairs , where is the atlas image and is the atlas label map, the segmentation of a target image proceeds in two stages:
Registration: For each atlas , compute a deformation field that maps to , typically by minimising (Registration) where is a dissimilarity metric (e.g., mutual information, normalised cross-correlation) and is a regulariser enforcing smoothness of the deformation.
Label fusion: Apply each deformation to the corresponding atlas labels, , and combine the warped labels using a fusion rule. The simplest is majority voting: (Majority VOTE) More sophisticated approaches weight each atlas by its local similarity to the target, e.g., the STAPLE algorithm or the joint label fusion method of Wang et al. (2013).
Multi-atlas segmentation was the state of the art for brain structure segmentation throughout much of the 2000s and 2010s, achieving human-level performance on structures with consistent anatomy (hippocampus, caudate, putamen) when a sufficient number of high-quality atlases were available. Its principal limitations are computational cost (each registration is an expensive optimisation problem) and dependence on the quality of the registration. When anatomical variability is high-as in the presence of large tumours, surgical resections, or congenital anomalies-registration-based methods degrade substantially.
Limitations of Classical Methods
The classical methods described above share a common structure: a human expert designs the representation (intensity features, geometric priors, atlas libraries), and an algorithm applies that representation to produce a segmentation. This paradigm has four systematic weaknesses that collectively drove the transition to deep learning.
Manual feature engineering. Every new imaging modality (CT, MRI, ultrasound, PET, OCT) and every new anatomical target (liver, kidney, retinal vessels, cardiac chambers) requires a new set of handcrafted features. The features that distinguish grey matter from white matter in T1-weighted MRI are entirely different from those that distinguish tumour from healthy tissue in contrast-enhanced CT\@. This manual design process is labour-intensive, requires domain expertise, and does not transfer across tasks.
Limited modelling capacity. Thresholding captures only intensity distributions; active contours encode only local geometry; random forests combine features linearly at each decision node. None of these methods can learn the hierarchical, multi-scale representations that are needed to distinguish structures with similar local appearance but different global context. For example, the grey-level appearance of a small liver metastasis may be indistinguishable from that of a blood vessel cross-section; distinguishing them requires understanding the broader anatomical context.
Sensitivity to initialisation and hyperparameters. Active contours require careful initialisation near the true boundary; region growing requires well-placed seed points; atlas-based methods require high-quality registration. In each case, small changes in the initial conditions or hyperparameters can lead to dramatically different segmentations, making these methods fragile in clinical deployment.
Inability to learn from large datasets. Classical methods cannot effectively leverage the growing availability of large annotated datasets. A random forest trained on annotated images is not qualitatively different from one trained on ; the improvement saturates because the handcrafted features impose a ceiling on what the classifier can represent. Deep learning methods, by contrast, benefit from additional data by learning richer representations.
These limitations set the stage for the deep learning revolution in medical image segmentation, which we describe in the next section. The key innovation was to replace handcrafted features with learned features, and to replace modular pipelines with end-to-end systems that jointly optimise representation and prediction.
The Deep Learning Revolution
The years 2015–2020 witnessed a transformation in medical image segmentation so rapid and so thorough that it is not an exaggeration to call it a revolution. In 2014, the winning entry of the MICCAI brain tumour segmentation challenge used a random forest with handcrafted features; by 2017, every top-performing method was based on deep convolutional networks. The catalyst was a deceptively simple architectural idea: take a convolutional network designed for image classification, remove the fully connected layers, and replace them with upsampling layers to produce dense, pixel-wise predictions. This idea, formalised as the fully convolutional network (FCN) by Long, Shelhamer, and Darrell in 2015, and refined into the U-Net by Ronneberger, Fischer, and Brox in the same year, became the foundation on which virtually all modern medical segmentation methods are built.
This section traces the development of deep learning architectures for medical image segmentation, from the FCN to the U-Net and its many descendants. We devote the most space to U-Net itself, because understanding its design principles is prerequisite for understanding nearly every subsequent innovation. We then cover 3D extensions (V-Net), self-configuring frameworks (nnU-Net), attention mechanisms (Attention U-Net), and the recent integration of vision transformers (TransUNet, Swin-UNet). We conclude with the evaluation metrics that the community uses to measure segmentation quality, developing their mathematical properties in some detail.
FCN: From Classification to Dense Prediction
The story of deep learning for segmentation begins with the observation that a convolutional neural network (CNN) trained for image classification already contains, in its intermediate layers, rich spatial information about the input image. A network like VGG-16 processes a image through a sequence of convolutional and pooling layers, producing feature maps that decrease in spatial resolution but increase in semantic richness. The final fully connected layers collapse all spatial information into a single class prediction.
Long, Shelhamer, and Darrell (2015) recognised that the fully connected layers are the only obstacle preventing a classification network from producing spatially dense outputs. Their key insight: a fully connected layer with outputs is mathematically equivalent to a convolution with filters. Replacing the FC layers with convolutions yields a fully convolutional network that accepts inputs of arbitrary size and produces a spatial map of predictions.
The output of a naive FCN has much lower resolution than the input because of the pooling layers. If the network contains stages of pooling, the output is downsampled by a factor of . For VGG-16 with , the output is smaller than the input. To recover the original resolution, FCN uses transposed convolutions (also called deconvolutions or fractionally strided convolutions) to upsample the prediction map: (Transposed CONV) where is the transpose of the convolution weight matrix. In practice, this inserts zeros between input elements and applies a standard convolution.
Long et al. introduced three variants with increasing sophistication:
FCN-32s: Upsample the final feature map directly by . Produces coarse segmentations with poor boundary delineation.
FCN-16s: Combine the -upsampled final prediction with predictions from the pool4 layer (stride 16), then upsample .
FCN-8s: Further combine with pool3 predictions, achieving the finest spatial detail.
This progressive fusion of predictions from different stages of the network was the precursor to the skip connections that would become central to U-Net.
U-Net: The Encoder-Decoder with Skip Connections
The U-Net architecture, proposed by Ronneberger, Fischer, and Brox at MICCAI 2015 (Ronneberger et al., 2015), is arguably the single most influential architecture in the history of medical image segmentation. A decade after its publication, it remains the baseline against which all new methods are measured, and its descendants (V-Net, nnU-Net, Attention U-Net, TransUNet) form the backbone of virtually every state-of-the-art segmentation system in medical imaging. The architecture is so pervasive that the phrase “U-Net-like” has become synonymous with encoder-decoder segmentation.
What made U-Net so successful was not any single radical innovation but rather the careful combination of three design principles into a coherent whole: (1) a symmetric encoder-decoder structure, (2) skip connections that concatenate encoder features with decoder features at matching resolutions, and (3) a training strategy based on data augmentation and weighted loss functions tailored to the small-dataset regime typical of medical imaging.
Architecture overview.
The U-Net consists of two paths: a contracting path (encoder) that captures context through successive downsampling, and an expansive path (decoder) that enables precise localisation through successive upsampling. The two paths are connected by skip connections that concatenate feature maps from the encoder with the corresponding feature maps in the decoder.
The contracting path follows the structure of a typical CNN\@. At each stage , it applies two convolutions (each followed by a ReLU activation), then a max pooling with stride 2 for downsampling. At each downsampling stage, the number of feature channels is doubled. If the input has channels and the first stage produces channels, then stage produces channels. In the original U-Net, , so the channel progression is .
Formally, let denote the feature map at the -th encoder stage, where and . The encoder operations are: (Encoder) where denotes convolution, is the ReLU activation, and are the convolution kernels at stage . Note that (the feature map before pooling) is the quantity that will be forwarded via the skip connection.
Bottleneck.
At the bottom of the U-shape, the bottleneck applies two convolutions without any pooling. In the original U-Net, this produces a -channel feature map at the coarsest spatial resolution ( for a 4-level architecture). The bottleneck captures the most abstract, global representation of the input.
Expanding path.
The expanding path mirrors the contracting path. At each stage , it applies:
A transposed convolution (“up-convolution”) that halves the number of channels and doubles the spatial dimensions.
Concatenation of the upsampled feature map with the corresponding encoder feature map from the skip connection. In the original U-Net, this required cropping the encoder feature map to match the (slightly smaller) decoder feature map, due to the loss of border pixels in unpadded convolutions. Modern implementations use padded convolutions, so no cropping is needed.
Two convolutions, each followed by ReLU\@.
Formally, the decoder operations at stage are: (Decoder) The final output is a convolution that maps the -channel feature map to channels (one per class), followed by a softmax or sigmoid activation: (Output)
Key Idea.
Skip connections preserve spatial resolution lost during encoding. The encoder progressively downsamples the input to capture high-level semantic information, but this downsampling discards fine-grained spatial details (precise boundaries, thin structures, small objects). Skip connections provide a direct pathway for these spatial details to bypass the information bottleneck and reach the decoder. Without skip connections, the decoder must reconstruct fine spatial details from the coarse bottleneck representation alone, which leads to blurry boundaries and loss of small structures. With skip connections, the decoder receives both the “what” (from the upsampled bottleneck features) and the “where” (from the high-resolution encoder features), enabling precise segmentation.
Loss function.
The original U-Net used a pixel-wise weighted cross-entropy loss designed to handle two challenges common in medical images: class imbalance (foreground structures are often much smaller than the background) and the need to separate touching objects. The loss is (LOSS) where is the one-hot ground-truth label at pixel for class , is the predicted probability, and is a weight map. The weight map is defined as (Weightmap) where compensates for class frequency, and are the distances to the borders of the two nearest cells, with and pixels in the original paper. This forces the network to learn to separate touching instances, which is critical for cell segmentation in microscopy.
Data augmentation.
A crucial ingredient of U-Net's success was its training strategy for small datasets. Medical imaging datasets often contain only tens to hundreds of annotated images, far too few to train a deep network by conventional standards. Ronneberger et al. applied aggressive data augmentation, particularly elastic deformations generated by applying random displacement fields to both the image and the segmentation mask. These deformations mimic the natural variability of biological tissue and proved far more effective than simple rotations and flips. With this augmentation strategy, U-Net achieved winning performance on the ISBI cell tracking challenge with only 30 annotated training images.
Example 6 (U-Net for Retinal Vessel Segmentation).
Retinal vessel segmentation, the task of delineating the blood vessel network from fundus photographs, is a benchmark problem in medical image segmentation. The DRIVE dataset contains 40 retinal images ( pixels) with manual vessel annotations. A standard U-Net with 4 encoder stages, trained with Dice loss and random elastic deformations, achieves a Dice coefficient of approximately on this dataset, comparable to the inter-observer agreement between human annotators ().
The key challenge is that retinal vessels span a wide range of calibres: the main arcades are – pixels wide, while capillaries may be only – pixels wide. The multi-scale nature of the U-Net encoder, which captures features at different resolutions, is naturally suited to this task. Skip connections ensure that the fine-scale features needed to detect thin capillaries are not lost during downsampling.
To process the images, patches of size are extracted with overlap and processed independently; the final segmentation is assembled by averaging the overlapping predictions. This patch-based strategy is a common pattern in medical image segmentation: it reduces memory requirements, increases the effective training set size (each image yields many patches), and allows the network to focus on local structure.
V-Net and 3D Extensions
Medical images are inherently three-dimensional: CT and MRI scans produce volumetric data, and the anatomical structures being segmented are 3D objects. Processing volumetric data slice-by-slice with a 2D U-Net discards the rich inter-slice information and can produce segmentations that are inconsistent across slices. V-Net, proposed by Milletari, Navab, and Ahmadi (2016), addresses this by extending the U-Net architecture to operate natively on 3D volumes.
The architectural changes from U-Net to V-Net are conceptually straightforward: all 2D convolutions become 3D convolutions (), all 2D pooling becomes 3D pooling (), and skip connections carry 3D feature volumes. However, the computational implications are dramatic: a convolution has more parameters than a convolution, and feature maps grow by a factor proportional to the depth of the volume. Training V-Net on a volume with the same channel dimensions as U-Net requires roughly more memory than processing a single slice.
V-Net introduced two additional innovations beyond the 3D extension:
Dice loss.
Rather than using cross-entropy, V-Net proposed training with a loss function based directly on the Dice coefficient (which we define formally in Evaluation Metrics). For a binary segmentation with predicted probabilities and ground-truth labels for voxels , the Dice loss is (DICE LOSS) where is a small constant for numerical stability. The Dice loss directly optimises the evaluation metric, and importantly, it is invariant to class imbalance: a small foreground object contributes the same gradient as a large one, because both numerator and denominator scale with the object size. This addresses one of the major challenges in medical segmentation, where the structure of interest may occupy only – of the image volume.
Residual connections.
V-Net also introduced residual (additive) connections within each encoder and decoder block, where the input to each block is added to the output before passing to the next stage. This facilitates gradient flow in the deeper 3D network and was inspired by the concurrent success of residual networks (ResNets) in image classification.
Remark 3.
A practical compromise between 2D and 3D processing is the 2.5D approach: for each target slice, provide the network with a stack of adjacent slices as multi-channel input. This captures local inter-slice context while maintaining the memory efficiency of 2D convolutions. Typical choices are or . The 2.5D approach is widely used in practice when GPU memory is limited or when the slice spacing is much coarser than the in-plane resolution (as is common in clinical CT and MRI).
nnU-Net: Self-Configuring Segmentation
A persistent challenge in applying U-Net to new medical segmentation tasks is the sheer number of design decisions: 2D or 3D? What patch size? What batch size? What learning rate schedule? What augmentation strategy? What postprocessing? These decisions interact in complex ways, and the optimal configuration varies dramatically across datasets. The nnU-Net framework (“no new net”), proposed by Isensee et al. (2021), addresses this by automating the entire pipeline through a set of heuristic rules derived from the dataset properties.
The key insight of nnU-Net is that the U-Net architecture itself is already sufficiently powerful for most medical segmentation tasks; what matters is how it is configured and trained. The framework takes a dataset as input and automatically determines:
Preprocessing: Resampling resolution, intensity normalisation scheme (z-score, percentile clipping, or CT-specific Hounsfield unit windowing), based on the dataset's voxel spacing statistics and modality metadata.
Architecture: Whether to use a 2D, 3D, or cascaded (coarse 3D followed by fine 3D) architecture, based on the voxel spacing anisotropy and the available GPU memory. The number of encoder stages, patch size, and batch size are determined by fitting the largest possible network into GPU memory using a rule-based estimator.
Training: Learning rate, number of epochs, augmentation pipeline (rotations, scaling, elastic deformations, gamma correction, mirroring), loss function (combination of Dice and cross-entropy), optimiser (SGD with Nesterov momentum).
Postprocessing: Whether to apply connected-component analysis to remove small spurious predictions, determined by cross-validation performance.
Ensembling: The final prediction is an ensemble of the 2D, 3D, and cascaded models, with the ensemble composition selected by cross-validation.
Example 7 (nnU-Net Winning Medical Segmentation Challenges).
The nnU-Net framework has won or achieved top-three performance in over 30 medical image segmentation challenges without any task-specific modifications. Notable results include:
Medical Segmentation Decathlon (MSD): nnU-Net won the overall competition across all 10 diverse segmentation tasks (brain tumour, heart, liver, hippocampus, prostate, lung, pancreas, hepatic vessel, spleen, colon), despite using a single framework with no manual tuning per task.
KiTS (Kidney Tumour Segmentation): Achieved state-of-the-art performance on kidney and tumour segmentation from contrast-enhanced CT\@.
ACDC (Cardiac Segmentation): Competitive with specialised cardiac segmentation methods on the task of delineating left ventricle, right ventricle, and myocardium from cardiac MRI\@.
The consistent success of nnU-Net across such diverse tasks provides strong evidence that architecture design matters less than careful, data-driven configuration of preprocessing, training, and postprocessing.
Attention U-Net
The skip connections in U-Net concatenate encoder features with decoder features without discrimination: all spatial positions in the encoder feature map are passed to the decoder, regardless of their relevance to the current segmentation task. This can introduce noise into the decoder, particularly when the encoder features contain responses to irrelevant background structures. The Attention U-Net, proposed by Oktay et al. (2018), addresses this by introducing attention gates that learn to suppress irrelevant encoder features and highlight salient ones before they are concatenated with decoder features.
Attention gate mechanism.
An attention gate takes two inputs: the encoder feature map from the skip connection at level , and the gating signal from the decoder at the level below (typically upsampled to match the spatial dimensions of ). The attention gate computes a spatial attention map that modulates the encoder features: (Attention GATE) where are convolution weights that project both inputs to a common intermediate dimensionality, is the ReLU activation, is a convolution that maps to a single channel, is the sigmoid function, and denotes element-wise multiplication (broadcasting over channels). The attention coefficient is close to for spatial locations that are relevant to the segmentation and close to for irrelevant locations.
The intuition is that the gating signal , which comes from the decoder and has already processed the bottleneck features, contains high-level semantic information about what and where the target structure is. The attention gate uses this semantic context to determine which spatial locations in the higher-resolution encoder features are relevant, suppressing background noise before concatenation.
Example 8 (3D Brain Tumour Segmentation with Attention U-Net).
The BraTS (Brain Tumour Segmentation) challenge provides multi-modal MRI scans (T1, T1-Gd, T2, FLAIR) with voxel-wise annotations of three tumour subregions: enhancing tumour, tumour core, and whole tumour. A 3D Attention U-Net trained on BraTS data achieves Dice scores of approximately (enhancing), (core), and (whole tumour).
The attention maps reveal interpretable behaviour: at the coarsest decoder level, attention gates activate broadly over the tumour region; at finer levels, they become increasingly focused on the tumour boundaries and substructure interfaces. This coarse-to-fine attention mimics the strategy a human radiologist uses: first locate the tumour globally, then examine its internal structure in detail. Crucially, the attention coefficients in healthy brain regions are close to zero at all levels, confirming that the gates successfully suppress irrelevant anatomical features.
Transformer-Based Segmentation
Convolutional neural networks, including U-Net and its variants, operate on local neighbourhoods: a convolution sees only its immediate context. Global context is acquired only indirectly, through successive layers of convolution and pooling. Vision transformers, which process images as sequences of patches and use self-attention to model long-range dependencies, offer an alternative that captures global context directly.
The integration of transformers into medical image segmentation has followed two main paradigms.
TransUNet: Hybrid CNN-Transformer.
TransUNet, proposed by Chen et al. (2021), replaces the U-Net bottleneck with a vision transformer. The architecture uses a CNN encoder (ResNet-50 or similar) to extract feature maps, which are then divided into non-overlapping patches and processed by a stack of transformer layers. The transformer output is reshaped back to spatial dimensions and fed into a standard U-Net decoder with skip connections from the CNN encoder. The key advantage is that the transformer bottleneck enables global self-attention, allowing the network to model long-range spatial relationships (e.g., the symmetry between left and right kidneys, or the spatial relationship between a tumour and nearby blood vessels) that are difficult for purely convolutional architectures to capture.
Formally, let be the output of the CNN encoder at the final stage. TransUNet divides this into non-overlapping patches of size , projects each to a -dimensional embedding, adds positional encodings, and processes the sequence through transformer layers: (Transunet) where is the patch embedding matrix and is the positional encoding.
Swin-UNet: Pure transformer segmentation.
Swin-UNet, proposed by Cao et al. (2022), goes further by replacing the entire U-Net architecture with Swin Transformer blocks, both in the encoder and the decoder. The Swin Transformer uses shifted windows to compute self-attention within local windows that shift across layers, achieving a balance between local detail and global context with complexity in the number of patches (versus for standard self-attention). Swin-UNet maintains the encoder-decoder structure with skip connections, but every component is based on attention rather than convolution.
Strengths and limitations.
Transformer-based segmentation methods excel at capturing long-range dependencies and have achieved state-of-the-art performance on several medical segmentation benchmarks, particularly for large structures where global context is important (e.g., abdominal organ segmentation). However, they typically require more training data than convolutional methods to achieve comparable performance, because the self-attention mechanism has weaker inductive biases than convolutions (no built-in translation equivariance, no local receptive field bias). In the low-data regime that characterises many medical imaging tasks, convolutional U-Nets and nnU-Net often outperform transformer-based methods.
Remark 4.
In practice, the best-performing architectures for medical segmentation are often hybrids that combine convolutional and transformer components. A common pattern is to use convolutional layers in the early encoder stages (where the spatial resolution is high and local features dominate) and transformer layers in the later stages (where the resolution is lower and global context becomes important). This design leverages the strong local inductive bias of convolutions and the global modelling capability of transformers while keeping computational costs manageable.
Evaluation Metrics
Evaluating the quality of a segmentation algorithm requires quantitative metrics that measure the agreement between the predicted segmentation and the ground-truth segmentation . Medical image segmentation uses a rich set of metrics, each capturing a different aspect of segmentation quality. We develop the most important ones with their mathematical properties.
Definition 9 (Dice Similarity Coefficient).
rensen–Dice coefficient|seeDice coefficient For two sets , the Dice similarity coefficient (also called the Srensen–Dice coefficient) is (DICE) where is the number of true positives, is the number of false positives, and is the number of false negatives. The Dice coefficient takes values in , where indicates perfect agreement and indicates no overlap.
The Dice coefficient is the standard metric in medical image segmentation, used in virtually every benchmark and challenge. Its popularity stems from several properties: it is symmetric, bounded, easy to interpret, and handles class imbalance naturally (unlike pixel-wise accuracy, which is dominated by the majority class).
Definition 10 (Intersection over Union).
For two sets , the Intersection over Union (IoU), also called the Jaccard index, is (IOU) The IoU takes values in , where indicates perfect agreement.
The Dice coefficient and IoU are closely related, as the following theorem shows.
Theorem 1 (Relationship Between Dice and IoU).
For any two sets , the Dice coefficient and the IoU satisfy (DICE IOU Relation) Consequently, for all , with equality only when or .
Proof.
Let , , and . Then and . We have Computing : For the inequality, observe that , with equality if and only if (both are ) or (both are ).
Definition 11 (Hausdorff Distance).
For two non-empty subsets , the Hausdorff distance is (Hausdorff) Equivalently, , where is the directed Hausdorff distance from to .
The Hausdorff distance measures the worst-case boundary error: means that every point in is within distance of some point in , and vice versa. This makes it particularly sensitive to outliers-a single grossly misplaced boundary point can dominate the Hausdorff distance. For this reason, the 95th-percentile Hausdorff distance is often preferred in practice, which replaces the with the 95th percentile.
Sensitivity, specificity, precision, recall.
In addition to overlap-based and distance-based metrics, the standard classification metrics are also used: (Class Metrics) Sensitivity measures the fraction of true positives that are correctly detected (completeness); specificity measures the fraction of true negatives that are correctly identified (absence of false alarms); and precision measures the fraction of predicted positives that are truly positive (correctness of detections). In medical imaging, sensitivity is often the most clinically important metric: a missed tumour (false negative) is typically more dangerous than a false alarm (false positive), which can be resolved by further examination.
Proposition 1 (Dice Loss Gradient and Optimisation Properties).
Consider the soft Dice loss for binary segmentation: (SOFT DICE) where are predicted probabilities and are ground-truth labels. The gradient with respect to a single prediction is (DICE Gradient) This gradient has two important properties:
Normalisation: The denominator normalises the gradient by the total foreground size, so small and large objects produce gradients of comparable magnitude. This provides implicit balancing against class imbalance.
Non-convexity: The Dice loss is non-convex in , so gradient descent may converge to local minima. In practice, this is rarely problematic because the loss landscape of deep networks is benign, but it means that combining Dice loss with cross-entropy (which is convex in logits) can stabilise training.
Proof.
Define and . Then . By the quotient rule: We have and , so For property (1), observe that where is the foreground size, so the gradient scales as , normalising for object size. For property (2), the Hessian is not positive semidefinite in general: for , the cross terms have mixed signs depending on the labels.
Caution.
High Dice does not mean clinically useful segmentation. A Dice score of on liver segmentation sounds impressive, but it may hide clinically significant errors: a segmentation that misses a ,mm tumour on the liver surface has a high overall Dice (because the tumour volume is negligible compared to the liver volume) but is clinically useless for treatment planning. Conversely, a segmentation with Dice that perfectly captures all surface details may be more useful than one with Dice that is slightly too large everywhere. The Hausdorff distance captures boundary errors better than Dice, and task-specific metrics (e.g., volumetric error for treatment planning, topological correctness for vessel segmentation) should supplement overlap metrics whenever possible.
Insight.
The Metric–Loss Alignment Principle A recurring theme in medical image segmentation is the tension between the training loss and the evaluation metric. Cross-entropy loss is well-behaved for optimisation (convex in logits, smooth gradients) but does not directly optimise Dice or Hausdorff distance. Dice loss directly optimises the Dice coefficient but is non-convex and can be unstable for small structures. Boundary-based losses (e.g., the Hausdorff distance loss of Karimi et al., 2020) optimise boundary accuracy but are computationally expensive. The most successful training strategies combine multiple losses, typically Dice plus cross-entropy, to balance optimisation stability with metric alignment.
Exercise 8 (U-Net Receptive Field Calculation).
Consider a U-Net encoder with stages. Each stage applies two convolutions (with stride 1 and no padding) followed by max pooling with stride 2. The bottleneck applies two additional convolutions.
Compute the receptive field of the encoder output (before the bottleneck) by tracking how each operation expands the effective input region. Recall that a convolution with stride 1 increases the receptive field by at the current scale, and a pooling with stride 2 doubles the scale factor.
How large is the receptive field of the bottleneck output? Compare this to the input image size of used in the original U-Net and discuss whether the bottleneck “sees” the entire image.
The decoder skip connections allow the output at each spatial position to depend on encoder features at matching resolution. What is the effective receptive field of a U-Net output pixel that receives information from all skip connections? Is it larger or smaller than the bottleneck receptive field?
Exercise 9 (Dice Loss vs. Cross-Entropy: Empirical Comparison).
Consider a binary segmentation task where the foreground occupies a fraction of the image.
Show that a trivial predictor that outputs for all pixels achieves cross-entropy loss (where is the clamped minimum probability) but Dice loss .
For (a foreground fraction, typical of small lesion segmentation), compute the cross-entropy loss of a predictor that outputs for all pixels. Compare this to the Dice loss of the same predictor. Which loss provides a stronger gradient signal for improving on this mediocre prediction?
Explain why the combination is often preferred to either loss alone. What role does each term play in early versus late training?
Exercise 10 (Attention Gate Analysis).
Consider an attention gate with encoder features , gating signal (already upsampled), intermediate dimension , and the attention computation from (Attention GATE).
Count the total number of learnable parameters in the attention gate. Express your answer in terms of and . Compare this to the number of parameters in a single convolutional layer and argue that the attention gate adds minimal computational overhead.
Suppose the attention gate learns (all ones) for all spatial positions. Show that this reduces to a standard U-Net skip connection. Under what conditions on the data and training would you expect the attention gate to converge to this trivial solution?
Now suppose the ground truth segmentation mask is available at training time. Design an auxiliary loss that encourages the attention maps to be high inside the target region and low outside. Discuss the trade-offs of adding such supervision: does it help or hurt generalisation?
Why Single Ground Truth Fails
Every supervised segmentation method studied so far in this chapter makes a quiet but consequential assumption: that each image has one correct mask. The loss function compares the network's prediction to that mask and adjusts parameters to reduce the discrepancy. This assumption is so deeply embedded in the standard training pipeline that it can be difficult to recognise as an assumption at all. Yet in clinical practice, it is often false.
When a radiologist traces the boundary of a brain tumour, a lung nodule, or a cardiac chamber, the outline she draws reflects not only what is visible in the scan but also her clinical experience, her tolerance for including ambiguous tissue, and the implicit question she is trying to answer. A different radiologist, equally skilled, may draw a different boundary-not because one is right and the other wrong, but because the image genuinely admits multiple plausible interpretations. This section examines the evidence for this claim, its mathematical consequences, and why it demands a fundamentally different approach to segmentation.
Inter-Observer Variability in Clinical Practice
Inter-observer variability is not a pathology of careless annotation; it is a structural feature of medical imaging. Consider the following scenarios that arise routinely in clinical workflows:
Infiltrative tumour margins. Glioblastoma, the most aggressive primary brain tumour, does not respect anatomical boundaries. Tumour cells infiltrate along white-matter tracts into tissue that appears radiologically normal. The visible boundary on an MRI scan therefore does not coincide with the true boundary of the disease. Different experts make different judgments about how far beyond the visible enhancement to extend the annotation.
Ground-glass opacities. In chest CT, ground-glass opacities blend gradually into normal lung parenchyma. There is no crisp edge to trace. The boundary that an annotator draws depends on the window/level settings used for viewing and on the annotator's subjective threshold for what constitutes “abnormal.”
Cardiac wall boundaries. In echocardiography, the endocardial border may be poorly visualised in certain segments due to acoustic shadowing or near-field artefacts. Annotators mentally interpolate across these gaps, and their interpolations differ.
Small lesions. For lesions near the resolution limit of the imaging modality, even the question of whether a lesion exists may be disputed among experts, let alone its precise boundary.
These examples share a common structure: the image provides partial information, and the annotator must supply the rest from domain knowledge and clinical judgment. Because domain knowledge varies across annotators, the resulting masks vary as well.
To quantify this variability, we need formal measures of agreement.
Definition 12 (Inter-Rater Agreement: Cohen's Kappa).
Given two raters who each assign items to one of categories, let denote the observed fraction of items on which the two raters agree, and let denote the expected fraction of agreement under the null hypothesis that the raters assign categories independently according to their respective marginal distributions. Cohen's kappa is (Kappa) When applied to segmentation, each pixel is treated as an “item” to be classified (foreground vs. background). A value of indicates perfect agreement, indicates agreement no better than chance, and indicates systematic disagreement.
Definition 13 (Inter-Rater Agreement: Fleiss' Kappa).
For raters (not necessarily the same pair for every item), Fleiss' kappa generalises Cohen's measure. Let be the number of raters who assign item to category . Define (PO) which is the average pairwise agreement across items. Let be the overall proportion of assignments to category , and define (PE) Then (Kappa) The interpretation is the same as for Cohen's kappa but now accounts for arbitrarily many raters.
Remark 5.
Kappa statistics have well-known pitfalls. When class prevalence is extreme-as in segmentation, where the foreground (lesion) may occupy less than 1% of the image- is very high, and even moderate observed agreement yields a low . This “prevalence paradox” means that values for segmentation tasks are typically much lower than for classification tasks, and comparing across tasks with different prevalence is misleading. Always report alongside the Dice coefficient and the raw agreement rate.
The LIDC-IDRI Dataset
The Lung Image Database Consortium and Image Database Resource Initiative (LIDC-IDRI) is the most widely studied dataset for multi-annotator segmentation. It comprises 1018 chest CT scans, each independently annotated by four experienced thoracic radiologists in a two-phase process:
Blinded read. Each radiologist independently marks nodules and traces their boundaries without knowledge of the other radiologists' annotations.
Unblinded read. Each radiologist reviews the anonymised annotations of the other three and may (but is not required to) revise her own annotation. Crucially, radiologists are not asked to reach consensus.
Even after the unblinded phase, substantial disagreement remains. For nodules in the 3–10,mm diameter range (the clinically critical “indeterminate” category), the pairwise Dice coefficient between annotators averages approximately –, depending on nodule morphology. For nodules with irregular or spiculated margins, the pairwise Dice can drop below .
To put concrete numbers on this variability: Armato et al. (Armato et al., 2011) report that among 928 nodules annotated by all four radiologists, the standard deviation of the per-nodule volume estimates across annotators is approximately 30% of the mean volume for nodules in the 6–10,mm range. For the smallest nodules (3–6,mm), where clinical management decisions hinge on whether a nodule exceeds certain size thresholds, the coefficient of variation exceeds 40%.
The key observation is not that annotators are imprecise, but that the image itself underdetermines the segmentation. The solid core of the nodule is unambiguous; every annotator includes it. The surrounding ground-glass halo is genuinely ambiguous: it may represent microscopic tumour invasion, inflammation, atelectasis, or normal parenchyma. The “correct” segmentation depends on the clinical question-staging, radiation planning, growth monitoring-which the dataset does not specify.
Historical Note.
The LIDC-IDRI dataset was assembled between 2000 and 2010 through a collaboration of seven academic centres and eight medical imaging companies, funded by the National Cancer Institute and the Foundation for the National Institutes of Health. Its explicit decision to preserve disagreement (rather than forcing consensus) was visionary: at the time, most datasets collapsed annotations into a single “gold standard.” The dataset's design has since become a template for ambiguity-aware annotation protocols in medical imaging.
The BraTS Challenge
The Brain Tumor Segmentation (BraTS) challenge has been running annually since 2012, focusing on glioma segmentation from multi-modal MRI (T1, T1-weighted with gadolinium contrast, T2, and FLAIR). Each case is annotated by one to four raters, and a consensus label is derived by majority vote or STAPLE fusion.
The BraTS annotation protocol divides the tumour into three nested subregions, each with different levels of inter-rater agreement:
Enhancing tumour (ET). The contrast-enhancing rim on T1-weighted gadolinium images. This subregion has the highest agreement ( in well-controlled studies) because the contrast agent provides a relatively sharp boundary.
Tumour core (TC). The union of enhancing tumour and necrotic core. Agreement is moderate () because the necrotic interior can be difficult to distinguish from cystic components or haemorrhage.
Whole tumour (WT). The union of tumour core and peritumoral oedema visible on FLAIR. Agreement is lowest (–) because the oedema boundary is diffuse and gradual. One rater's oedema is another rater's normal white matter.
The BraTS data thus provides a clean gradient of ambiguity: from the relatively unambiguous enhancing tumour, through the moderately ambiguous core, to the highly ambiguous whole tumour extent. Any segmentation method that treats all three subregions as equally determined is ignoring information that is present in the annotations themselves.
The gradient of ambiguity across subregions has a concrete clinical explanation. The enhancing tumour boundary is defined by contrast agent uptake, which is governed by blood-brain barrier disruption-a relatively sharp physical boundary. The tumour core boundary depends on distinguishing necrosis from haemorrhage and cystic fluid, which have overlapping signal characteristics on standard MRI sequences. The whole tumour boundary requires distinguishing vasogenic oedema from normal white matter, a distinction that is often impossible on FLAIR alone because both appear hyperintense.
This hierarchy of ambiguity has direct implications for clinical decision-making:
Radiation therapy planning. The gross tumour volume (GTV) typically corresponds to the enhancing tumour, which has high inter-rater agreement. But the clinical target volume (CTV), which includes a margin for microscopic spread, overlaps with the ambiguous oedema boundary. Different delineations of the CTV lead to different radiation doses to healthy brain tissue.
Volumetric monitoring. In longitudinal studies, changes in whole tumour volume are used to assess treatment response (the RANO criteria). If the whole tumour boundary is ambiguous, apparent volume changes may reflect annotator variability rather than genuine tumour progression or regression.
Remark 6.
The BraTS challenge evaluates submissions against a consensus label, typically derived by the STAPLE algorithm (Warfield et al., 2004). This is a reasonable pragmatic choice for a competition, but it obscures the very ambiguity we are trying to model. A method that perfectly predicts the consensus label may still disagree with individual expert annotations on the most ambiguous voxels-precisely the voxels where uncertainty information would be most clinically useful.
The Tumour Board Analogy
In clinical practice, high-stakes diagnostic and treatment decisions are not made by a single physician. They are made by a tumour board: a multidisciplinary panel that typically includes a radiologist, a pathologist, a surgeon, a radiation oncologist, and a medical oncologist. Each specialist brings a different perspective and a different tolerance for risk. The board deliberates, and the final recommendation reflects a distribution of expert opinion, not a point estimate.
This institutional structure exists precisely because medicine recognises that difficult cases have no single right answer. The value of the tumour board lies not in producing a consensus (though it often does) but in exposing the range of reasonable interpretations and the reasoning behind each.
If we take this analogy seriously, then the goal of a medical segmentation system should not be to predict “the” correct mask. It should be to produce a set of plausible masks-a virtual tumour board-together with a calibrated measure of how much the virtual experts disagree. The clinician can then examine the range of predictions, focus attention on the regions of disagreement, and make an informed decision.
This perspective also suggests a natural evaluation paradigm: a probabilistic segmentation model is good if its “virtual board” disagrees in the same way, and to the same extent, as a real board of human experts. The model should be diverse where experts are diverse and unanimous where experts agree. Formally, the predicted distribution should match the empirical distribution of expert annotations -not in the sense of predicting one “right” mask, but in the distributional sense of matching the full range of plausible interpretations.
Key Idea.
The truth is a distribution, not a point. In ambiguous medical images, the target of inference should not be a single segmentation mask but a distribution over plausible masks. A segmentation model that outputs a single deterministic prediction discards information about diagnostic uncertainty-information that is essential for downstream clinical decision-making. The remainder of this chapter develops the mathematical and architectural tools needed to learn and sample from such distributions.
Why Averaging Masks Fails
A natural first response to multi-annotator data is to average the masks: assign each pixel a “soft” label equal to the fraction of annotators who include it in the foreground. Alternatively, one can take a majority vote: a pixel is foreground if and only if more than half the annotators mark it so. Both approaches are ubiquitous in medical image segmentation benchmarks. Both are fundamentally flawed when the underlying distribution is multimodal.
The mathematical argument.
Let be the binary segmentation masks drawn by annotators, where . The averaged mask is (MASK) For a given pixel , suppose the annotators split into two camps: a fraction includes the pixel () and a fraction excludes it (). The averaged value at that pixel is . If we threshold at to recover a binary mask, the pixel is included when and excluded otherwise.
Now consider the situation where for a spatially coherent region-a connected patch of tissue about which experts genuinely disagree. The averaged mask assigns values near throughout this region. The thresholded mask either includes the entire region or excludes it, depending on tiny fluctuations in across pixels. In neither case does the result correspond to what any annotator actually drew.
To make this precise, consider the space of all binary masks for an image of resolution . The expert annotations define an empirical distribution (DIST) where is the Kronecker delta on . The averaged mask is the mean of this distribution: (MASK) But the mean of a multimodal distribution can fall in a region of low probability. Consider the simplest case: two annotators, one draws mask with a region included, the other draws with the region excluded. The mean has value in the disputed region-a mask that has zero probability under .
Caution.
Training on majority-vote masks silences minority expert opinions. When the training target is the majority-vote mask, the segmentation model learns to ignore any anatomical interpretation held by fewer than half the annotators. In a panel of four experts, this means that a region consistently annotated by one or two experts-perhaps reflecting a valid but cautious clinical perspective-is treated as background. The model not only fails to reproduce this minority interpretation; it is actively penalised for doing so. In clinical settings where the minority opinion corresponds to a rare but serious pathology, this failure mode has direct consequences for patient safety.
The problem is especially severe when the disagreement is structured-that is, when the annotators disagree about entire regions rather than individual pixels. Structured disagreement is the norm in medical imaging: experts rarely disagree pixel by pixel in a random, uncorrelated pattern. Instead, their disagreements reflect coherent anatomical or pathological hypotheses: “this region is oedema” versus “this region is normal tissue,” or “this nodule extends to the pleural surface” versus “this nodule is separated from the pleura by a thin layer of normal parenchyma.”
To summarise the argument:
Expert annotations of ambiguous medical images are multimodal: the distribution over masks concentrates on a finite number of distinct segmentations, not a smooth continuum.
The mean of a multimodal distribution may lie outside the support of the distribution, producing a mask that no expert would endorse.
Deterministic segmentation models trained with cross-entropy or Dice loss against the mean or majority-vote mask learn a blurred compromise that sacrifices spatial coherence for pixel-level accuracy.
The information lost by averaging-the structure of inter-expert disagreement-is precisely the information that clinicians need for informed decision-making.
We can quantify the information loss from averaging. Let denote the entropy of the empirical annotation distribution. The averaged mask is a sufficient statistic for the product-of-marginals approximation where . The information lost by averaging is exactly the multi-information (total correlation): (LOSS) where is the marginal distribution of pixel . This quantity is zero only when the pixels are independent under -that is, when there is no spatial structure in the disagreement. In practice, is large whenever annotators disagree about coherent regions, which is the typical case in medical imaging.
The conclusion is inescapable: to faithfully represent annotation ambiguity, we need models that output distributions over segmentation masks, not single masks. The next section develops the mathematical framework for doing so.
Probabilistic Segmentation
The preceding section established that medical image segmentation is inherently ambiguous: the correct target is a distribution over masks, not a single mask. This section builds the mathematical and architectural machinery needed to learn and sample from such distributions. We begin with the formal problem statement, expose the limitations of pixel-wise uncertainty, and then develop two landmark architectures-the Probabilistic U-Net and PHiSeg-that address these limitations through latent variable models.
From Point Estimates to Distributions
Let denote an input medical image with spatial dimensions and channels (e.g., for multi-modal MRI). Let denote a one-hot encoded segmentation mask with classes. We wish to learn the conditional distribution (Target) from which we can sample multiple plausible segmentations for the same image.
Definition 14 (Probabilistic Segmentation Model).
A probabilistic segmentation model is a parametric family over segmentation masks conditioned on images , together with an inference procedure that, given a new image , produces a set of samples . A probabilistic segmentation model is calibrated if the frequency with which a pixel is included in the foreground across samples matches the empirical frequency across expert annotators.
Why is this formulation necessary? A deterministic segmentation model maps each image to a single mask. When trained with a loss that averages over multiple annotators' masks, the model learns the conditional mean -or, for cross-entropy training, the mode of the product-of-marginals approximation. As we showed in Why Averaging Masks Fails, this conditional mean can be a poor summary of the annotation distribution when the distribution is multimodal. A probabilistic model, by contrast, can represent the full conditional distribution, including multiple modes, their relative weights, and the spatial correlation structure within each mode.
The simplest instantiation of a probabilistic segmentation model is a standard neural network (e.g., a U-Net) that outputs per-pixel class probabilities via a softmax layer: (Pixelwise) where is the logit for class at pixel . Sampling from this model means independently flipping a biased coin at each pixel. This approach has a fatal deficiency, as we now demonstrate.
Pixel-wise Uncertainty is Not Enough
When the distribution over masks is defined by independent per-pixel probabilities, sampling produces masks that are spatially incoherent: each pixel's label is drawn independently of its neighbours. The resulting masks are noisy mosaics that bear no resemblance to any expert's annotation.
Proposition 2 (Independent Pixel-wise Uncertainty Underestimates Correlations).
Let be the true conditional distribution over binary masks, and let be the best product-of-marginals approximation, where is the number of pixels. If the true distribution has non-trivial spatial correlation-i.e., there exist pixels with -then (Indep) and the variance of any linear functional (such as region volume) satisfies (Underestimate) whenever the net covariance . In particular, the variance of the predicted lesion volume is underestimated.
Proof.
The KL divergence between and any product distribution is non-negative and equals zero only when itself is a product distribution, which contradicts the assumption of non-trivial spatial correlation. For the variance inequality, note that is a product distribution, so all cross-covariance terms vanish: for . Expanding under and respectively gives the claimed inequality whenever the sum of positive covariances exceeds the sum of negative ones. In medical segmentation, expert annotations tend to agree or disagree about entire regions, so adjacent pixels are positively correlated, and the condition holds generically.
The clinical consequence is immediate: if we estimate the volume of a tumour or the area of a lesion using pixel-wise uncertainty, we systematically underestimate the range of plausible volumes. The confidence interval we report to the clinician is too narrow. It fails to account for the possibility that the entire disputed boundary region might be included or excluded en bloc.
Insight.
Sampling coherent masks reveals structure that uncertainty maps hide. A pixel-wise uncertainty map summarises the marginal at each pixel but discards the joint structure of . Two distributions with identical marginals can have radically different joint structure: one might concentrate mass on two sharp masks (bimodal), while the other spreads mass uniformly across all masks with the same marginals (maximum entropy). Only by drawing spatially coherent samples from the joint distribution can we recover this structure. The key to coherent sampling is a shared latent variable that controls the global characteristics of each sample.
The Probabilistic U-Net
The Probabilistic U-Net, introduced by Kohl et al. at NeurIPS 2018 (Kohl et al., 2018), is the first architecture to combine the spatial precision of U-Net with the distributional expressiveness of a conditional variational autoencoder (CVAE). The key insight is to introduce a low-dimensional latent variable that modulates the U-Net's output, so that different draws of produce different-but spatially coherent-segmentation masks.
Architecture.
The Probabilistic U-Net consists of four components (Figure fig:medseg:prob:punet:arch):
U-Net backbone. A standard U-Net that takes the input image and produces a feature map at the final layer (before the classification head). This feature map encodes the spatial structure of the image at full resolution.
Prior network. A convolutional encoder that maps the input image to the parameters of a Gaussian distribution in latent space: (Prior) This network sees only the image and must predict the range of plausible segmentations from the image alone.
Posterior network. A convolutional encoder that maps both the image and a ground-truth mask to the parameters of a Gaussian distribution: (Posterior) This network is used only during training; it provides the variational posterior that guides the prior to encode segmentation-relevant information.
Combining module. The latent sample is broadcast spatially and concatenated with the U-Net feature map , then passed through a convolution to produce the final logits: (Decode) Given a specific , the output is a deterministic (pixel-wise independent) segmentation; the stochasticity enters only through .
Training objective.
The model is trained by maximising the evidence lower bound (ELBO) on the log-likelihood of the observed annotations.
Definition 15 (Evidence Lower Bound for Segmentation).
Given an image and an observed segmentation drawn from the multi-annotator distribution, the ELBO for the Probabilistic U-Net is (ELBO) where is a weighting factor (set to for the standard ELBO, and for the common -VAE relaxation that encourages better reconstruction at the cost of a looser bound).
The reconstruction term encourages the model to accurately reproduce the observed mask when the latent variable is drawn from the posterior. The KL term encourages the prior to match the posterior , so that at test time-when is unavailable and we must sample from the prior-the resulting values are informative.
Remark 7.
In practice, is a critical hyperparameter. Setting often leads to posterior collapse: the model learns to ignore entirely and produces the same (deterministic) segmentation regardless of the latent sample. Setting too small produces diverse samples that are poorly calibrated. The original Probabilistic U-Net paper recommends tuning on validation data, with typical values in the range .
Inference.
At test time, to generate plausible segmentations for a new image :
Compute the U-Net feature map .
Compute the prior parameters .
For : enumerate
Sample .
Compute (or sample pixel-wise for soft masks). enumerate
Each sample selects a different “mode” of the distribution, producing a spatially coherent mask. The diversity of the samples reflects the model's learned uncertainty about the correct segmentation.
Example 9 (Probabilistic U-Net on LIDC-IDRI).
Kohl et al. (Kohl et al., 2018) train the Probabilistic U-Net on the LIDC-IDRI dataset with four annotators per nodule. During training, each image is paired with a randomly selected annotator's mask (not the averaged mask). The latent dimension is .
At test time, the model generates 16 samples per image. The key findings are:
Diversity. The samples span the range of inter-annotator variability. For ambiguous nodules, some samples include the ground-glass halo while others exclude it, mirroring the bimodal structure of the expert annotations.
Coherence. Each individual sample is a plausible, spatially connected segmentation-unlike samples from a pixel-wise independent model, which resemble random noise.
Calibration. The pixel-wise frequency of inclusion across samples correlates with the fraction of annotators who include that pixel, with a calibration error of approximately 3%.
Quantitative performance. On the Generalized Energy Distance (GED, defined below), the Probabilistic U-Net achieves , substantially better than a deterministic U-Net () and a pixel-wise dropout-based uncertainty estimate ().
PHiSeg: Hierarchical Probabilistic Segmentation
A limitation of the Probabilistic U-Net is that all stochasticity enters through a single low-dimensional latent variable . This means the model can express uncertainty only along a small number of directions in mask space. For complex, multi-scale ambiguity -where coarse shape uncertainty (“is this a large or small tumour?”) coexists with fine-grained boundary uncertainty (“is this local indentation part of the tumour?”)-a single latent vector may be insufficient.
PHiSeg (Probabilistic Hierarchical Segmentation), introduced by Baumgartner et al. at MICCAI 2019 (Baumgartner et al., 2019), addresses this by introducing hierarchical latent variables at multiple resolutions, following the architecture of a Laplacian pyramid.
Architecture.
PHiSeg extends the conditional VAE framework with a hierarchy of latent variables , where has spatial resolution matching the -th level of the U-Net decoder. The generative model factors as (Generative) where each is a conditional Gaussian whose parameters depend on the coarser latent and the image . The coarsest latent captures global shape variation; finer latents progressively refine the boundary.
The inference model (posterior) mirrors this hierarchy: (Posterior)
Training objective.
The ELBO for PHiSeg decomposes the KL divergence across levels: (ELBO) where . Each KL term encourages the prior at level to match the corresponding posterior, conditioned on all coarser latents.
Inference.
Sampling proceeds top-down: first sample from the coarsest prior, then progressively sample conditioned on the coarser latents. This produces a coarse-to-fine generation process:
Sample : determines overall tumour extent.
Sample : refines intermediate structure.
Continue until : determines fine boundary details.
Decode: .
Example 10 (PHiSeg on Ambiguous Brain Lesion Boundaries).
Baumgartner et al. (Baumgartner et al., 2019) evaluate PHiSeg on a brain lesion segmentation task derived from a dataset of FLAIR MRI scans with multiple annotators. They use latent levels and latent dimensions ranging from 1 (coarsest) to 4 (finest).
The results demonstrate the advantage of hierarchical latent variables:
Multi-scale diversity. Different samples from PHiSeg can differ at coarse scales (overall lesion extent) or fine scales (local boundary shape), or both-reflecting the multi-scale nature of annotator disagreement.
Improved GED. PHiSeg achieves on the brain lesion task, compared to for the Probabilistic U-Net, representing a relative improvement of approximately 20%.
Sharper samples. Individual samples from PHiSeg have sharper, more realistic boundaries than those from the Probabilistic U-Net, because fine-grained latent variables can capture local boundary shape independently of global structure.
Ablation. Removing the hierarchical structure (collapsing to a single latent level) degrades performance to roughly that of the Probabilistic U-Net, confirming that the hierarchy is the source of the improvement.
Remark 8.
The relationship between the Probabilistic U-Net and PHiSeg mirrors the relationship between a standard VAE and a hierarchical VAE in image generation. A single latent variable can capture global modes (“include the boundary region” vs. “exclude it”) but struggles with local variation. Hierarchical latents decompose uncertainty into scales, enabling the model to represent both “which global interpretation?” and “given that interpretation, what are the local boundary details?” The cost is increased architectural complexity and a more delicate training procedure: the KL terms at different levels must be balanced to prevent the model from ignoring fine-level latents (a hierarchical analogue of posterior collapse).
Comparison of sampling behaviour.
To build further intuition, consider sampling from the Probabilistic U-Net versus PHiSeg on an image where the tumour boundary is ambiguous at two distinct scales: the overall extent is uncertain (coarse ambiguity) and within each overall extent, the boundary has local wiggles (fine ambiguity).
With the Probabilistic U-Net, each draw of must simultaneously encode both the coarse extent and the fine boundary shape. If is small, there may not be enough capacity to represent both sources of variation faithfully. In practice, the model tends to capture the dominant mode of variation (usually the coarse extent) and produce overly smooth boundaries.
With PHiSeg, the coarse latent selects the overall extent, and the fine latents independently sample boundary details given that extent. This factorisation allows the model to produce samples that vary at multiple scales simultaneously, yielding a richer and more faithful representation of the annotation distribution.
Generalized Energy Distance
To compare probabilistic segmentation models, we need a metric that assesses the quality of a distribution of predictions, not just a single prediction. Standard metrics like the Dice coefficient compare two masks and are not designed for comparing a set of predicted masks against a set of reference masks. The Generalized Energy Distance (GED) fills this gap.
Definition 16 (Generalized Energy Distance).
Let and be two distributions over segmentation masks, and let be a distance function on masks (e.g., or ). The Generalized Energy Distance between and is (GED) In practice, is the empirical distribution of expert annotations and is the empirical distribution of model samples . The expectations are estimated by averaging over all pairs: (Empirical)
The GED has a natural interpretation. The first term measures the cross-distance between the two distributions: how far are predicted masks from reference masks on average? The second and third terms subtract the within-distribution spread, so that a model is not penalised for producing diverse samples when the reference distribution is itself diverse.
Theorem 2 (GED as a Proper Scoring Rule).
The Generalized Energy Distance is a proper scoring rule for distributional predictions in the following sense:
for all distributions over .
if and only if (assuming is a metric on ).
For any reference distribution , the minimiser of over all distributions is .
Consequently, a model that minimises the expected GED recovers the true annotation distribution.
Proof.
We prove each property in turn.
Non-negativity. Define the energy of a distribution with respect to distance as . The GED can be rewritten as (Energy) When is a metric of negative type (which includes all metrics of the form for and many common segmentation distances), the generalised energy distance is known to be non-negative. We refer to the seminal work of Székely and Rizzo (Szekely and Rizzo, 2004) for the full proof of this classical result.
Identity of indiscernibles. If , then the cross-term equals and both self-terms equal , giving . Conversely, implies when is a metric of negative type, again by the Székely–Rizzo characterisation.
Properness. For any , write (Proof) Setting makes the first parenthetical zero (since ) and the second parenthetical zero. For , non-negativity ensures , so is the unique minimiser.
Remark 9.
The empirical GED estimator in is unbiased but has variance that scales as . When the number of reference annotations is small (e.g., in LIDC-IDRI), the within-reference term has high variance. It is therefore important to use a large number of model samples (typically or ) to reduce the contribution of the within-prediction term to the overall variance.
Choosing the base distance .
The GED is parameterised by the choice of base distance on mask space, and this choice matters in practice. Common options include:
: penalises disagreement proportional to the size of the symmetric difference relative to the size of the union. Sensitive to small lesions (where even one misclassified pixel changes the Dice substantially).
: similar to the Dice-based distance but with a different normalisation. Penalises false positives and false negatives more symmetrically for large objects.
: the normalised Hamming distance. Treats all pixels equally regardless of lesion size. Simple but does not respect the clinical importance of boundary pixels.
: the 95th-percentile Hausdorff distance between the two mask boundaries. Focuses entirely on worst-case boundary discrepancies. Not a proper metric in the strict sense (it does not satisfy the triangle inequality for the 95th percentile variant), but is widely used in medical image segmentation benchmarks.
In practice, the Dice-based distance is the most common choice for the GED in medical imaging, because it aligns with the Dice coefficient used for deterministic evaluation and because it handles class imbalance (small lesions against a large background) more gracefully than the Hamming distance.
Multi-Annotator Modelling
The Probabilistic U-Net and PHiSeg learn to sample from the distribution without explicitly modelling who drew each annotation. An alternative approach is to model annotator-specific behaviour directly: learn a distribution conditioned on annotator identity . This has several advantages:
Annotator-specific predictions. Given a new image, the model can predict what each specific annotator would draw, enabling the system to emulate the style of a particular expert (e.g., the most conservative or the most liberal).
Annotator quality estimation. By comparing each annotator's style to the consensus, the model can identify outlier annotators whose annotations are systematically different from the group, which may indicate either expertise or error.
Disentangled uncertainty. The model can separate annotator-specific variation (systematic differences in annotation style) from image-specific ambiguity (regions where even the same annotator would be uncertain), providing a richer characterisation of uncertainty.
Formal setup.
Suppose we have a dataset where each image is annotated by annotator producing mask . We model (Model) where the latent variable now depends on both the image and the annotator identity. One concrete instantiation is to decompose into an image-dependent component and an annotator-dependent component: (Decompose) where are learnable parameters specific to annotator .
STAPLE and its neural extensions.
The classical STAPLE algorithm (Warfield et al., 2004) models each annotator as a noisy labeller with pixel-wise sensitivity and specificity. Modern neural extensions replace the pixel-wise noise model with a learned annotator-specific head:
(Neural) where is a shared feature extractor and is a lightweight annotator-specific module (e.g., a convolution with annotator-specific weights). The shared backbone learns the consensus representation, while each annotator head learns the systematic deviations of that annotator from the consensus.
Confusion matrix approach.
A particularly elegant formulation models each annotator as applying a learnable pixel-wise confusion matrix to the “true” segmentation produced by the shared backbone. Formally, if is the backbone's class probability at pixel , then annotator 's predicted label distribution is (Confmat) Here represents the probability that annotator labels a pixel as class when the “true” class is . The matrix is constrained to be row-stochastic (each column sums to one). A perfect annotator has ; a systematically biased annotator has off-diagonal entries that capture the direction and magnitude of the bias.
This approach has the advantage of interpretability: after training, one can inspect to understand each annotator's systematic tendencies. For instance, if is large, annotator tends to under-segment (label tumour pixels as background).
Remark 10.
The scalability of multi-annotator models depends on the number of annotators and the amount of data per annotator. When each annotator labels only a small fraction of the dataset (as in crowdsourcing), the per-annotator parameters may be poorly estimated. Hierarchical Bayesian approaches-placing a shared prior on the annotator parameters -can mitigate this by sharing statistical strength across annotators. Specifically, one can place a matrix-valued prior on the confusion matrices: for each column, with the concentration parameter shared across annotators and learned from data. This encourages annotators with few labels to behave like the “average” annotator, while allowing annotators with many labels to develop individual profiles.
Connecting multi-annotator models to probabilistic segmentation.
Multi-annotator models and probabilistic segmentation models are complementary, not competing, approaches. A multi-annotator model learns a conditional distribution that explains variation between annotators but not within a single annotator (i.e., the stochasticity that would remain even if the same annotator segmented the same image twice). A probabilistic model like the Probabilistic U-Net learns the marginal , integrating over annotator identity but not modelling it explicitly.
The richest models combine both: a latent variable captures annotator-specific style, a latent variable captures image-specific ambiguity, and the decoder produces a mask conditioned on both. Marginalising over yields the distribution over masks for an “average” annotator; conditioning on a specific annotator yields that annotator's predicted mask; and the variance of given quantifies the residual uncertainty that cannot be explained by annotator identity.
Exercises
Exercise 11 (KL Divergence in the Probabilistic U-Net).
Consider the Probabilistic U-Net with a -dimensional latent space and diagonal Gaussian prior and posterior .
- (a)
Derive the closed-form expression for in terms of .
- (b)
Show that if everywhere, then the KL divergence reduces to a scaled squared Euclidean distance between the means.
- (c)
Suppose we set in the ELBO (no KL regularisation). Explain why the prior network becomes useless at test time and the model degenerates.
Exercise 12 (GED Computation).
Consider a binary segmentation task with images of size . Three annotators provide the following masks for an image : A probabilistic model generates two samples: Using as the distance, compute between the annotator distribution and the model distribution. Comment on whether the model captures the annotator variability.
Exercise 13 (Hierarchical Sampling in PHiSeg).
Consider a simplified PHiSeg with latent levels. The coarse latent determines whether a lesion is “large” () or “small” (). The fine latent (conditioned on ) determines whether the boundary is “smooth” () or “irregular” ().
- (a)
How many distinct segmentation modes can this model represent? Describe each mode.
- (b)
Suppose the prior is and . Compute -the probability of the “large and smooth” mode.
- (c)
Compare this hierarchical sampling with a single 2D latent drawn from a joint Gaussian. Under what conditions do they produce equivalent distributions?
Challenge 1 (Implementing a Minimal Probabilistic U-Net).
Implement a Probabilistic U-Net for binary segmentation on synthetic 2D data:
Generate a synthetic dataset of images, each containing an elliptical “lesion” with ambiguous boundaries. For each image, generate annotations by randomly perturbing the ellipse parameters (centre, axes, rotation) with controlled variance.
Implement the four components: U-Net backbone (3 encoder and 3 decoder levels with skip connections), prior network (3-layer CNN outputting for ), posterior network (same architecture but taking concatenated image and mask), and combining convolution.
Train with the ELBO objective. Experiment with and report the effect on sample diversity.
Evaluate using the GED with . Compare against a deterministic U-Net trained on majority-vote masks and a U-Net with Monte Carlo dropout.
Visualise the latent space: encode all training annotations using the posterior network and plot the 2D PCA projection, coloured by annotator identity. Do annotators cluster?
Adversarial Training for Segmentation
The segmentation methods we have studied so far optimise pixel-wise losses - cross-entropy, Dice, or their combinations - that compare predicted masks against ground truth one pixel at a time. These losses treat each pixel as an independent classification problem, ignoring the rich spatial structure that radiologists instinctively recognise: organ boundaries are smooth curves, not random scatterings of pixels; tumour margins follow tissue planes; and anatomical structures obey topological constraints that pixel-wise losses cannot enforce.
Generative adversarial networks offer a fundamentally different training philosophy. Instead of specifying what makes a good segmentation through a hand-crafted loss, we train a discriminator network to learn what good segmentations look like by examining real ground truth masks. The segmentor (playing the role of the generator) is then trained not only to minimise pixel-wise error but also to fool the discriminator into believing that its output is a genuine expert annotation. This adversarial pressure encourages the segmentor to produce masks with realistic boundary smoothness, connected components, and anatomical plausibility - properties that are difficult to capture with conventional loss functions.
This section reviews the GAN framework as applied to segmentation (GAN Fundamentals Recap), introduces SegAN and its multi-scale discriminator feedback (SegAN: Adversarial Network for Segmentation), presents the Projective Adversarial Network for 3D organ segmentation (PAN: Projective Adversarial Network), and develops adversarial domain adaptation for cross-scanner segmentation (Adversarial Domain Adaptation for Segmentation).
GAN Fundamentals Recap
We briefly recall the adversarial framework that underlies all methods in this section. A comprehensive treatment appears in sec:gan; here we summarise only what is needed for the segmentation context.
A GAN consists of two networks trained in opposition:
A generator that maps a noise vector (or, in conditional settings, an input image ) to a synthetic output;
A discriminator that receives either a real sample from the data distribution or a synthetic sample from and outputs a scalar indicating “real” or “fake.”
The two networks play a min-max game: (Minmax) At the Nash equilibrium, produces samples indistinguishable from real data, and outputs for every input. In practice, training alternates between updating for steps (typically ) and updating for one step.
Remark 11.
In segmentation, the generator is the segmentation network itself. It receives an input image and produces a predicted mask . There is no noise vector ; the stochasticity comes from the training data distribution and, in some formulations, from dropout or other stochastic layers within . The discriminator then judges whether a given image–mask pair looks like a real annotation or a network prediction.
The critical advantage of adversarial training for segmentation is that learns a structured loss function. Where cross-entropy penalises each pixel independently, the discriminator sees the entire mask (or local patches of it) and can detect global implausibilities: disconnected components that should be connected, jagged boundaries where smooth ones are expected, or segmented regions that violate anatomical constraints.
Key Idea.
Adversarial losses teach models what not to generate. While pixel-wise losses specify what a good segmentation should look like at each pixel, the discriminator learns from the distribution of real masks what unrealistic segmentations look like and penalises the generator for producing them. This is particularly valuable in medical imaging, where the space of anatomically plausible segmentations is a tiny subset of all possible binary masks.
SegAN: Adversarial Network for Segmentation
SegAN (Xue et al., 2018) reframes medical image segmentation as an adversarial game between a segmentor (the generator) and a critic (the discriminator). Unlike standard GANs, where the discriminator produces a single real/fake score, SegAN's critic operates at multiple spatial scales, providing dense, spatially-resolved feedback to the segmentor.
Architecture overview.
The segmentor is an encoder–decoder network (typically a U-Net variant) that maps an input image to a predicted mask . The critic receives the concatenation of the input image and a mask - either the ground truth or the predicted - and produces feature maps at hierarchical scales: (Critic) where denotes the feature map at scale .
Multi-scale loss.
The key innovation is the multi-scale feature matching loss, which compares the critic's internal representations for real and predicted masks: (LOSS) where normalises by the total number of elements at scale , and denotes the norm.
The training objectives are: (OBJ) The segmentor minimises the feature-level discrepancy between real and predicted masks, while the critic maximises it, forcing both networks to improve.
Why multi-scale feedback helps boundary precision.
At fine scales (), the critic's feature maps preserve spatial detail and capture local boundary accuracy. At coarse scales (), the feature maps encode global structural properties such as organ shape, connectivity, and relative position. By matching features across all scales, the segmentor receives supervision that simultaneously enforces pixel-level precision and structural plausibility.
Consider a segmentor that correctly classifies of pixels but produces a small disconnected component near the liver boundary. A pixel-wise Dice loss would barely penalise this error (the Dice coefficient might drop by ), but the critic's coarse-scale features would register a significant deviation from the distribution of real masks, which never contain such artefacts. The resulting gradient signal guides the segmentor to suppress the false positive.
Proposition 3 (Multi-Scale Loss Reduces Boundary Error).
Let and denote the boundaries of the predicted and ground truth masks, respectively. The multi-scale feature matching loss provides a gradient signal whose magnitude at boundary pixels scales as , where is the spatial stride at scale , while a pixel-wise loss provides a gradient of .
Proof.
At scale , a boundary misalignment of pixels in the original resolution corresponds to a displacement of in the feature map. The critic's convolutional filters at scale have receptive fields proportional to , so a single boundary error affects approximately feature map locations, where is the receptive field radius. The norm aggregates these contributions: (Boundary) since is approximately constant across scales for typical encoder architectures with doubling receptive fields and quadrupling spatial dimensions. For a four-scale critic with strides , this yields a boundary gradient amplification of compared to a single-scale loss.
Example 11 (SegAN for Brain Tumour Segmentation).
Xue et al. (Xue et al., 2018) evaluated SegAN on the BraTS 2017 challenge dataset for brain tumour segmentation in multi-modal MRI (T1, T1ce, T2, FLAIR). Using a U-Net segmentor with a three-scale critic (), SegAN achieved:
| Method | Whole Tumour | Core | Enhancing |
| U-Net (Dice loss) | 0.878 | 0.744 | 0.681 |
| U-Net + pixel-wise | 0.885 | 0.756 | 0.698 |
| SegAN (multi-scale) | 0.901 | 0.779 | 0.726 |
The improvement is most pronounced on the enhancing tumour sub-region, which has the most irregular boundaries. Qualitative analysis showed that SegAN produced smoother, more connected enhancing tumour masks compared to pixel-wise methods, aligning better with radiologist expectations.
Insight.
The SegAN result illustrates a broader principle: in medical segmentation, the perceptual quality of a mask (as judged by a clinician) often matters more than the pixel-level accuracy. A mask with Dice and smooth, anatomically plausible boundaries may be more clinically useful than a mask with Dice but ragged edges and disconnected fragments. The multi-scale discriminator in SegAN implicitly learns this clinical preference by being trained on expert annotations, which consistently exhibit smooth boundaries and connected regions. This insight extends to any medical segmentation task: adversarial losses can encode prior knowledge about the structure of good segmentations, knowledge that is difficult to express through hand-designed loss functions.
Remark 12.
Despite its advantages, SegAN inherits the training instability of GANs. The adversarial min-max optimisation can oscillate, with the critic becoming too powerful (providing uninformative gradients) or too weak (providing no useful signal). Practical implementations require careful learning rate scheduling: the critic learning rate is typically set – higher than the segmentor's, with the critic updated time per segmentor update. Spectral normalisation of the critic weights further stabilises training. These engineering considerations are non-trivial and partly explain why adversarial segmentation methods have not fully displaced simpler Dice + cross-entropy training in clinical practice.
PAN: Projective Adversarial Network
Pancreas segmentation is among the most challenging tasks in abdominal CT analysis. The pancreas occupies less than of the abdominal volume, varies enormously in shape across patients, and has low contrast against surrounding tissues. Purely 3D networks struggle with the computational cost of volumetric convolutions, while 2D slice-by-slice approaches lose inter-slice context.
The Projective Adversarial Network (PAN) (Li et al., 2019) proposes an elegant middle ground: enforce 3D structural consistency through 2D projections. The segmentor operates on 3D volumes, but the discriminator judges the quality of the segmentation by examining 2D projections (maximum intensity projections or summed projections) along the three anatomical axes.
Formulation.
Let be the predicted 3D segmentation mask. Define the projection operators as summations along the axial, coronal, and sagittal axes, respectively: (PROJ) Three independent 2D discriminators are trained to distinguish projections of ground truth masks from projections of predicted masks.
Training objective.
The total loss combines a voxel-wise segmentation loss with the adversarial regularisation: (LOSS) where controls the strength of the adversarial regularisation and is the standard GAN loss applied to the 2D projections.
Why projections work.
Each 2D projection integrates information along an entire anatomical axis, capturing global shape properties that a 3D patch-based discriminator would miss. The axial projection reveals the overall extent and lateral shape of the pancreas; the coronal projection captures its characteristic “hook” or “tadpole” morphology; and the sagittal projection constrains its anterior–posterior extent. Together, the three projections enforce a 3D shape prior without the memory cost of a 3D discriminator.
Mathematically, the projections constrain the marginal distributions of the 3D mask along each axis. If the predicted mask has the correct marginals in all three anatomical planes, its 3D shape is highly constrained. This is analogous to the Radon transform in computed tomography: a finite set of 2D projections can reconstruct a 3D volume (or, in this case, constrain its shape). While three projections do not uniquely determine the 3D mask, they eliminate the vast majority of anatomically implausible shapes, and the voxel-wise Dice loss handles the remaining ambiguity.
Remark 13.
The computational overhead of PAN is modest. Each 2D discriminator is a standard PatchGAN with approximately parameters. Three discriminators add parameters - less than of a typical 3D segmentation network. The projection operations themselves are simple summations with negligible cost.
PAN achieved a Dice score of on the NIH pancreas dataset, compared to for 3D U-Net alone and for 3D U-Net with a voxel-level discriminator. The improvement was concentrated on the tail and uncinate process of the pancreas - the thinnest regions where shape priors are most valuable.
Example 12 (PAN for Multi-Organ Abdominal Segmentation).
Beyond the pancreas, PAN's projective adversarial regularisation generalises to multi-organ abdominal segmentation (liver, spleen, kidneys, stomach). On the BTCV multi-organ benchmark ( training volumes, test volumes), adding projective discriminators to a 3D nn-UNet baseline improves the average Dice from to , with the largest gains on small organs (gallbladder: , adrenal glands: ) where shape priors are most informative.
Adversarial Domain Adaptation for Segmentation
A segmentation model trained on images from scanner A at hospital A often fails catastrophically when applied to images from scanner B at hospital B. The intensity distributions, noise characteristics, and resolution differ enough to shift the learned feature representations out of the operating regime. Adversarial domain adaptation uses a discriminator to align the feature distributions across source and target domains, enabling a model trained on labelled source data to generalise to an unlabelled target domain.
Feature-level alignment.
Let be a shared feature encoder and a segmentation head. The source domain has labelled pairs , while the target domain has only images . A domain discriminator receives feature maps and predicts whether they come from the source or target domain: (Align) The feature encoder is trained adversarially to confuse , implemented via a gradient reversal layer (Ganin et al., 2016): (Total) The negative sign on with respect to (via gradient reversal) encourages to produce domain-invariant features: features that are discriminative for the segmentation task but indistinguishable between source and target domains.
Gradient reversal layer.
The gradient reversal layer acts as the identity during the forward pass but multiplies the gradient by during backpropagation: (GRL) This simple trick enables end-to-end training: the feature encoder, segmentation head, and domain discriminator are trained jointly with a single optimiser, and the gradient reversal layer automatically ensures that the encoder is updated to maximise domain confusion while minimising segmentation loss. In practice, is annealed from to during training using a schedule , where is the training progress and . This allows the encoder to first learn discriminative features on the source domain before the domain alignment pressure is applied.
Output-level alignment.
An alternative approach applies the discriminator not to intermediate features but to the segmentor's output probability maps. The intuition is that even if pixel intensities differ across scanners, the structure of the output segmentation should be domain-invariant: a cardiac segmentation should have the same spatial layout of left ventricle, myocardium, and right ventricle regardless of the scanner.
Tsai et al. (Tsai et al., 2018) demonstrated that multi-level output alignment - applying discriminators at multiple spatial resolutions of the segmentation output - outperforms single-level alignment, analogous to the multi-scale strategy in SegAN.
Clinical significance.
Domain adaptation is not merely an academic exercise. In a multi-centre clinical trial, a cardiac segmentation model trained at one centre and deployed at another experienced a Dice score drop from to without adaptation, but maintained with adversarial feature alignment. This recovery represents the difference between a clinically useful tool and one that requires site-specific retraining - a barrier that has delayed the deployment of many AI-based medical imaging tools.
Remark 14.
Adversarial domain adaptation assumes that a domain-invariant feature representation exists and is useful for the segmentation task. When the source and target domains differ not just in appearance but in the distribution of pathologies (e.g., the source hospital sees mostly healthy cases while the target sees advanced disease), feature alignment alone is insufficient. In such cases, the methods of Conditional GANs for Medical Imaging - particularly CycleGAN-based synthesis - offer a complementary approach by transforming images between domains at the pixel level.
Conditional GANs for Medical Imaging
The previous section used adversarial training to improve segmentation networks directly. This section takes a different perspective: we use conditional GANs to generate synthetic medical images, which serve as training data for downstream segmentation models. The motivation is simple and powerful: medical image annotation is expensive, expert-dependent, and limited by patient privacy regulations. If we can synthesise realistic medical images along with their segmentation masks, we can augment small datasets to train better segmentor networks.
We begin with the foundational paired and unpaired image translation frameworks (sec:medseg:cgan:pix2pix,sec:medseg:cgan:cyclegan), then explore specialised architectures for 4D cardiac imaging (4D MRI Reconstruction with Re-Con-GAN), haematological analysis (Synthetic Blood Cell Generation), and brain MRI synthesis (Brain MRI Synthesis). We conclude with a comparative analysis of GANs versus diffusion models for medical image generation (GANs vs Diffusion: When to Use What).
pix2pix: Paired Image-to-Image Translation
The pix2pix framework (Isola et al., 2017) established the blueprint for conditional image-to-image translation: given a paired dataset of input–output images , train a generator to produce realistic outputs conditioned on the input, supervised by both a reconstruction loss and an adversarial loss.
Definition 17 (Conditional GAN Objective).
Let be a generator conditioned on input , and let be a discriminator that receives both the conditioning input and the candidate output. The conditional GAN objective is (OBJ) where are drawn from the joint data distribution. The generator solves . The conditioning on distinguishes this from the unconditional GAN of (Minmax): the discriminator must judge not only whether the output looks realistic, but whether it is a plausible output for the given input.
Combined objective.
pix2pix augments the adversarial loss with an reconstruction loss that encourages the generator to produce outputs close to the ground truth: (LOSS) where (typically ) balances the two terms. The loss prevents mode collapse by anchoring the generator's output near the target, while the adversarial loss encourages high-frequency detail that the term alone would blur.
PatchGAN discriminator.
Instead of classifying the entire image as real or fake, the pix2pix discriminator operates on overlapping patches, producing a grid of real/fake scores. This PatchGAN architecture:
Can process images of arbitrary size (the grid adapts to the input dimensions);
Has fewer parameters than a full-image discriminator;
Focuses on local texture and structure, which is particularly effective for enforcing sharp tissue boundaries in medical images.
Application to medical data augmentation.
In medical imaging, pix2pix is typically applied in the mask-to-image direction: given a segmentation mask, generate a realistic medical image. This enables the following data augmentation pipeline:
Start with a small annotated dataset of real images and masks;
Train a pix2pix model to translate masks to images: ;
Generate new masks by applying random deformations (elastic transforms, affine warps) to existing masks;
Synthesise corresponding images: ;
Augment the training set with the synthetic pairs .
This pipeline can expand a dataset by an order of magnitude while maintaining paired supervision. Shin et al. (Shin et al., 2018) demonstrated that augmenting a brain tumour dataset from 200 to 2,000 paired examples using pix2pix improved U-Net segmentation Dice by on the enhancing tumour class.
Example 13 (Synthetic Polyp Generation for Endoscopy Training Data).
Colonoscopy-based polyp detection is limited by the scarcity of annotated training images: typical datasets contain – images, far fewer than the tens of thousands needed to train robust detectors. A pix2pix-based augmentation pipeline addresses this bottleneck:
Mask generation. Elliptical and irregular polyp masks are generated procedurally, varying size (– mm equivalent), shape eccentricity, and position within the colon lumen.
Conditional synthesis. A pix2pix generator (U-Net with downsampling blocks, trained on paired polyp images from the CVC-ClinicDB dataset) translates each mask into a realistic endoscopy image with appropriate mucosal texture, specular reflections, and vascular patterns.
Quality filtering. A pre-trained InceptionV3 classifier scores each synthetic image; samples scoring below probability of “polyp present” are discarded ( rejection rate).
Augmented training. Combining real images with synthetic images and training a YOLOv5-based detector yields a sensitivity improvement of () at specificity, compared to training on real data alone.
The synthetic images are visually convincing: in a blinded study, five gastroenterologists classified of synthetic images as real (versus for actual endoscopy images), indicating near-chance discrimination.
CycleGAN: Unpaired Domain Adaptation
pix2pix requires paired training data: for each input image, we need a corresponding output image. In many medical imaging scenarios, paired data is unavailable. We may have a collection of MRI scans and a separate collection of CT scans, but not MRI–CT pairs from the same patients. CycleGAN (Zhu et al., 2017) enables unpaired image-to-image translation by introducing a cycle consistency loss that ensures translations are mutually coherent.
Definition 18 (Cycle Consistency Loss).
Let and be two generators translating between domains and . The cycle consistency loss enforces that translating an image to the other domain and back recovers the original: (Cycle) The first term ensures that the composition approximates the identity on domain ; the second ensures approximates the identity on domain .
Full objective.
The CycleGAN training objective combines two adversarial losses (one for each translation direction) with the cycle consistency loss: (FULL) where and are discriminators for domains and , and is the default weight.
Application to cross-modality segmentation.
The standard workflow for CycleGAN-based cross-modality segmentation is:
Train a CycleGAN to translate between modalities (e.g., MRI CT);
Translate all labelled source-domain images to the target domain appearance;
Train a segmentation network on the translated images with the original labels (which are preserved since CycleGAN maintains structural content);
Apply the segmentation network directly to real target-domain images.
Example 14 (CycleGAN for Cross-Scanner Brain MRI Harmonisation).
Multi-site neuroimaging studies pool data from different scanners (e.g., Siemens Prisma at site A, GE Discovery at site B), creating systematic intensity differences that confound automated analysis. CycleGAN can harmonise these differences without requiring paired scans from the same subjects.
Setup. Two collections of T1-weighted brain MRI volumes: scans from a Siemens 3T scanner (domain ) and scans from a GE 3T scanner (domain ), with no subject overlap. Both sets have FreeSurfer-derived cortical parcellations for evaluation but these labels are not used during CycleGAN training.
Architecture. 2D CycleGAN applied slice-by-slice (axial slices, ). Each generator uses ResNet blocks; each discriminator is a PatchGAN. Training proceeds for epochs with .
Results. After harmonisation, applying a cortical parcellation model (trained on Siemens data only) to GE data achieves:
| Method | Mean Dice | Hausdorff (mm) |
| No harmonisation (direct transfer) | 0.761 | 3.42 |
| ComBat statistical harmonisation | 0.812 | 2.87 |
| CycleGAN (MRI MRI) | 0.843 | 2.31 |
| Oracle (retrained on GE data) | 0.871 | 1.98 |
CycleGAN recovers of the domain gap ( out of ), substantially outperforming the widely used ComBat statistical approach. Visual inspection confirms that the translated images preserve cortical folding patterns and ventricular morphology while adapting the intensity profile and contrast characteristics to match the target scanner.
Limitations of CycleGAN for medical translation.
While powerful, CycleGAN has well-documented failure modes in medical imaging that practitioners must be aware of:
Hallucinated pathology. CycleGAN may add or remove pathological features during translation. A tumour present in the source MRI might be attenuated or displaced in the translated CT if such lesions are rare in the target domain's training distribution.
Geometric distortion. While cycle consistency penalises large deviations, subtle geometric distortions (shifts of – pixels) can persist, particularly near tissue boundaries with strong intensity gradients.
Steganographic encoding. The generators may hide source-domain information in imperceptible high-frequency patterns, enabling near-perfect cycle reconstruction without meaningful domain translation. This can be detected by adding Gaussian noise between the forward and backward translations: if the cycle reconstruction error degrades dramatically with small noise (), steganographic encoding is likely present.
Identity loss requirement. For medical applications, an identity loss is often added to prevent the generator from unnecessarily modifying images that are already in the target domain.
4D MRI Reconstruction with Re-Con-GAN
Real-time volumetric imaging during cardiac or respiratory motion requires acquisition speeds that exceed the capabilities of standard MRI protocols. 4D MRI (three spatial dimensions plus time) typically requires under-sampling in -space, resulting in aliasing artefacts that corrupt reconstructed images and downstream segmentation.
Re-Con-GAN addresses this by incorporating an adversarial loss into the MRI reconstruction pipeline, encouraging the reconstructed images to be indistinguishable from fully-sampled references.
Problem setup.
Let denote the fully-sampled 4D -space data and the under-sampled version, where is a binary sampling mask with acceleration factor . The reconstruction network maps under-sampled zero-filled images to fully-sampled estimates: (GAN) where denotes the inverse Fourier transform.
Training objective.
The Re-Con-GAN objective combines data consistency, perceptual quality, and adversarial realism: (LOSS) where extracts VGG features and is the fully-sampled reference. The adversarial term is critical: without it, the reconstruction tends toward over-smoothed outputs that achieve low error but lose the fine anatomical detail needed for accurate segmentation.
Temporal consistency.
For cardiac applications, Re-Con-GAN adds a temporal regularisation term that penalises frame-to-frame discontinuities: (Temporal) This ensures that the reconstructed cardiac motion matches the ground-truth motion pattern, preventing temporal flickering artefacts that would corrupt functional measurements such as ejection fraction.
At an acceleration factor of (acquiring only of -space), Re-Con-GAN achieves a structural similarity index (SSIM) of on cardiac cine MRI, compared to for compressed sensing and for a U-Net without the adversarial loss. The downstream left ventricle segmentation Dice improves from (compressed sensing input) to (Re-Con-GAN input), approaching the achieved on fully-sampled data.
Remark 15.
The clinical value of Re-Con-GAN extends beyond image quality metrics. In cardiac imaging, the acquisition time for a fully-sampled 4D cine sequence is typically – seconds of breath-hold, which many patients with heart failure cannot sustain. An acceleration reduces the breath-hold to under seconds, making the examination feasible for severely ill patients who would otherwise be excluded from quantitative cardiac MRI assessment. The adversarial loss is essential to this clinical advance: without it, the reconstruction quality at acceleration is insufficient for reliable segmentation, and the examination would provide visually plausible but quantitatively unreliable measurements.
Insight.
The Re-Con-GAN paradigm reveals a recurring theme: adversarial losses are most valuable when the “quality” that matters is difficult to define mathematically but easy for a discriminator to learn. For MRI reconstruction, the and perceptual losses ensure global fidelity, but the adversarial loss ensures that the fine-grained texture and edge characteristics match those of real fully-sampled images - precisely the features that downstream segmentation networks rely on. This complementarity between explicit losses (capturing what we can formalise) and adversarial losses (capturing what we cannot) is the fundamental insight of adversarial training.
Synthetic Blood Cell Generation
Automated blood cell classification and counting underpins modern haematological analysis, but training datasets are limited by the labour-intensive process of expert annotation under a microscope. The Mixture-of-Experts conditional GAN (MoE-cGAN) generates realistic blood cell images spanning multiple cell types, with a focus on maintaining the distinctive colour and morphological characteristics that pathologists use for classification.
Architecture.
MoE-cGAN uses a class-conditional generator where a shared backbone extracts common features and class-specific expert heads produce the final output: (MOE) where is the number of cell types (typically : neutrophils, lymphocytes, monocytes, eosinophils, and basophils) and is a class-specific decoder. This mixture-of-experts structure prevents the generator from averaging across cell types, which would produce blurry or chimeric cells.
Colour histogram alignment via Wasserstein distance.
Blood cells are characterised by their staining properties: Wright–Giemsa staining produces distinctive colour profiles for each cell type. MoE-cGAN enforces colour fidelity by adding a Wasserstein distance penalty on the colour histograms:
Definition 19 (Wasserstein Distance for Image Quality).
Let and be the normalised colour histograms (computed in CIE Lab space) of real and generated images for channel . The Wasserstein colour distance is (Wasserstein) where and are the cumulative distribution functions of the respective histograms, and denotes the -Wasserstein (earth mover's) distance.
The Wasserstein colour distance is added to the MoE-cGAN objective: (Total) In practice, provides the best balance between colour fidelity and structural quality.
MoE-cGAN generates blood cell images at resolution. In a downstream classification experiment, augmenting a -image training set with synthetic images improved the classification accuracy of a ResNet-50 classifier from to , with the largest gains on the rare basophil class ( accuracy), which benefits most from synthetic oversampling.
Quality assurance for synthetic blood cells.
A critical concern with GAN-generated blood cell images is whether they preserve the morphological features that pathologists use for clinical diagnosis. Three levels of validation are employed:
Distribution-level. The Fréchet Inception Distance (FID) between real and synthetic image sets should be below (comparable to the FID between two real datasets of similar size). MoE-cGAN achieves FID on neutrophils and on basophils (the harder class due to fewer training examples).
Feature-level. Cell-specific morphometric features - nuclear-to-cytoplasm ratio, granularity index, and lobulation count for neutrophils - should match the statistical distributions of real cells (two-sample Kolmogorov–Smirnov test, ).
Expert-level. A panel of three haematologists reviews randomly mixed real and synthetic images. Classification accuracy at chance level () confirms visual indistinguishability. In MoE-cGAN evaluations, experts achieved accuracy, consistent with random guessing.
Remark 16.
The Wasserstein colour distance (Definition 19) is particularly important for haematology because staining variability is one of the primary sources of inter-laboratory discordance in blood smear analysis. By explicitly matching the colour distribution of synthetic images to real stained images, MoE-cGAN produces synthetic training data that adapts to the specific staining protocol of the target laboratory, effectively performing implicit domain adaptation at the pixel level.
Brain MRI Synthesis
Generating realistic brain MRI volumes is valuable for data augmentation in tumour segmentation, anomaly detection, and privacy- preserving data sharing. Two complementary approaches have emerged: DCGAN-based generation for creating novel whole-brain volumes, and ESRGAN-based super-resolution for enhancing low-resolution acquisitions.
DCGAN for brain tumour variants.
A 3D DCGAN adapted for brain MRI generates voxel patches centred on tumour regions. The architecture is notably compact:
Generator: transposed convolutional layers, batch normalisation, ReLU activation. Total parameters: .
Discriminator: strided convolutional layers, batch normalisation, LeakyReLU. Total parameters: .
The parameter efficiency (– parameters, compared to the of a standard 3D U-Net) is critical for medical imaging applications where training data is limited: fewer parameters means less risk of overfitting to a small training set.
ESRGAN for super-resolution.
Enhanced Super-Resolution GAN (ESRGAN) upscales -downsampled brain MRI slices to their original resolution, recovering fine anatomical detail. The key innovation over standard SRGAN is the use of Residual-in-Residual Dense Blocks (RRDB) and the relativistic discriminator (Wang et al., 2018), which computes whether a real image is “more realistic” than a fake one rather than scoring each in isolation: (REL) where is the critic output before the sigmoid .
In brain MRI experiments, ESRGAN-upscaled images achieve a peak signal-to-noise ratio (PSNR) of , compared to for bicubic interpolation and for standard SRGAN. When used as input to a tumour segmentation network, the ESRGAN-upscaled images yield Dice scores within of those obtained from original high-resolution acquisitions.
Privacy-preserving data sharing.
A compelling use case for brain MRI synthesis is generating “synthetic cohorts” that capture the statistical properties of a patient population without containing any real patient data. A DCGAN trained on a hospital's brain MRI dataset can generate an unlimited number of synthetic volumes that exhibit realistic anatomical variability, tumour characteristics, and imaging artefacts. These synthetic volumes can be shared freely across institutions for algorithm development, benchmarking, and educational purposes, circumventing the regulatory barriers (HIPAA, GDPR) that restrict sharing of real patient data.
The key requirement is that the synthetic images do not memorise or reproduce specific training examples. Evaluations using nearest-neighbour distances in a learned feature space (e.g., FID-based memorisation detection) confirm that well-trained DCGANs with parameters and training volumes produce genuinely novel images: the average distance from each synthetic image to its nearest real neighbour exceeds the average distance between real images by a factor of –, indicating interpolation in the learned manifold rather than memorisation.
GANs vs Diffusion: When to Use What
The rise of diffusion models (sec:diffusion) has raised a fundamental question for medical image generation: when should practitioners use GANs, and when should they use diffusion models? The answer depends on the specific requirements of the clinical application.
Fundamental trade-offs.
GANs and diffusion models occupy different points in the trade-off space between inference speed, sample diversity, training stability, and output sharpness. GANs generate samples in a single forward pass through the generator, making them orders of magnitude faster than diffusion models, which require hundreds or thousands of denoising steps. However, GANs are prone to mode collapse - the generator may produce only a subset of the possible outputs, missing rare but clinically important variations.
Proposition 4 (Mode Collapse and Clinical Implications).
Let be the true data distribution and the generator distribution. Mode collapse occurs when : the generator fails to cover the full support of the data distribution. In medical imaging, this manifests as:
Missing rare pathologies. A GAN trained on brain MRIs with glioblastoma and oligodendroglioma may only generate glioblastoma-like tumours, producing training data that underrepresents the minority class.
Reduced anatomical diversity. Collapsed generators may produce organs with limited shape variation, failing to capture the tails of the natural anatomical distribution (e.g., unusually shaped pancreases, rare cardiac morphologies).
Biased augmentation. If synthetic data is used to augment a training set, mode collapse biases the augmented distribution, potentially reducing rather than improving the downstream segmentor's performance on rare cases.
Proof.
The mode collapse phenomenon follows from the GAN training dynamics. When the discriminator fails to provide gradient signal in regions of where has near-zero density, the generator receives no incentive to place mass in those regions. Formally, the generator gradient is (GRAD) When (the discriminator easily identifies the fake), the denominator and the gradient magnitude is proportional to . If the generator has collapsed to a region where has small gradients (a “flat” region of the discriminator landscape), the generator receives vanishingly small updates and remains trapped.
For clinical data, the modes most vulnerable to collapse are precisely those with the fewest training examples: rare pathologies, unusual anatomies, and atypical imaging artefacts. These are also the cases where segmentation models most need augmentation, creating a destructive feedback loop where the cases that benefit most from synthetic data are least likely to be generated.
| p5.0cm p5.0cm Property | GANs | Diffusion Models |
| Core mechanism | Adversarial min-max game between generator and discriminator | Iterative denoising from Gaussian noise via learned score function |
| [4pt] Inference speed | Single forward pass (– ms per image) | Hundreds of denoising steps (– s per image); accelerated samplers reduce to – s |
| [4pt] Sample diversity | Limited by mode collapse risk; may miss rare variants | High diversity; stochastic sampling covers the full distribution |
| [4pt] Training stability | Notoriously unstable; requires careful hyperparameter tuning, architecture design, and learning rate scheduling | Stable; the denoising objective is a simple regression loss with well-understood convergence properties |
| [4pt] Output sharpness | Produces sharp, high-contrast images; excels at fine boundaries | Can produce slightly blurry outputs at low sampling steps; high-step sampling recovers sharpness |
| [4pt] Ambiguity modelling | Deterministic mapping from input to output (for conditional GANs); cannot represent segmentation uncertainty | Naturally models ambiguity through the stochastic denoising process; multiple samples capture prediction uncertainty |
| [4pt] Conditioning | Straightforward via concatenation or projection; well-established architectures (pix2pix, SPADE) | Flexible via classifier-free guidance, cross-attention, or ControlNet; rapidly evolving landscape |
| [4pt] Memory footprint | Single generator network (– parameters typical) | U-Net denoiser of comparable size, but requires storing noise schedule and running multiple forward passes |
| [4pt] Data augmentation | Fast generation enables large-scale augmentation; ideal for on-the-fly augmentation during training | Slower generation may require pre-computing synthetic datasets; higher quality per sample |
| [4pt] Best medical use cases | Real-time synthesis, on-the-fly augmentation, super-resolution, style transfer between scanners | Diverse training data generation, uncertainty-aware segmentation, inpainting, anomaly detection |
| [4pt] Key limitation | Mode collapse can miss rare but clinically critical cases; training instability wastes compute | Slow inference limits real-time applications; high computational cost for training and sampling |
Practical decision framework.
When selecting between GANs and diffusion models for a medical imaging project, consider the following heuristics:
If inference speed matters (e.g., real-time surgical guidance, on-the-fly augmentation), use GANs. Diffusion models are – slower at inference.
If sample diversity matters (e.g., generating training data for rare disease classification), use diffusion models. Their stochastic sampling naturally avoids mode collapse.
If uncertainty quantification matters (e.g., flagging ambiguous segmentations for expert review), use diffusion models. Multiple samples provide calibrated uncertainty estimates.
If training stability matters (e.g., limited computational budget, no ML engineering team to tune hyperparameters), use diffusion models. GAN training requires substantial expertise.
If output sharpness matters (e.g., generating training data for boundary-sensitive segmentation tasks), GANs and well-tuned diffusion models are comparable.
Quantitative comparison on medical benchmarks.
To ground the qualitative comparison above in numbers, we summarise representative results from the literature on medical image synthesis benchmarks. On the BraTS brain tumour dataset ( slices), a DCGAN achieves FID with generation time , while a DDPM achieves FID at ( slower). On the CheXpert chest X-ray dataset, a conditional StyleGAN2 achieves FID with notable mode collapse on rare pathologies (atelectasis underrepresented by in synthetic set), while a latent diffusion model achieves FID with balanced pathology representation (maximum underrepresentation ).
These numbers crystallise the trade-off: GANs are faster by two orders of magnitude, but diffusion models produce more diverse and representative synthetic datasets. For clinical applications where rare pathology coverage determines patient safety, the diversity advantage of diffusion models often outweighs their computational cost.
Remark 17.
The distinction between GANs and diffusion models is increasingly blurred. Consistency models (Song et al., 2023) distil diffusion models into single-step generators, achieving GAN-like speed with diffusion-like diversity. Adversarial diffusion distillation (Sauer et al., 2023) uses a GAN discriminator to guide diffusion model distillation. As of 2025, hybrid approaches are emerging as the dominant paradigm for high-quality, efficient medical image generation.
Historical Note.
GANs in Medical Imaging: A Decade of Progress (2016–2026).
The application of generative adversarial networks to medical imaging has followed a rapid trajectory:
- 2016
First applications of GANs to medical image synthesis. Costa et al. generate retinal fundus images using a DCGAN trained on the DRIVE dataset ( images), demonstrating that even tiny medical datasets can be augmented with adversarial generation.
- 2017
pix2pix (Isola et al., 2017) and CycleGAN (Zhu et al., 2017) are published, establishing paired and unpaired image translation frameworks that quickly find medical applications. Nie et al. use a 3D conditional GAN for CT synthesis from MRI.
- 2018
SegAN (Xue et al., 2018) applies adversarial training directly to the segmentation task. Shin et al. (Shin et al., 2018) demonstrate pix2pix-based data augmentation for brain tumour segmentation. Wolterink et al. use CycleGAN for cardiac CT/MRI translation.
- 2019
PAN (Li et al., 2019) introduces projective adversarial regularisation for 3D organ segmentation. Progressive GANs generate high-resolution pathology images (). The field matures with the first systematic reviews of GANs in medical imaging.
- 2020–2021
StyleGAN2-based medical image synthesis achieves photorealistic quality. Federated GAN training enables multi-hospital collaboration without sharing patient data. Privacy concerns emerge as GAN-generated medical images become indistinguishable from real ones.
- 2022–2023
Diffusion models challenge GAN dominance in medical image generation. However, GANs retain advantages in inference speed and are integrated into hybrid architectures. MoE-cGAN and related architectures specialise GAN generation for specific medical applications.
- 2024–2025
Hybrid GAN-diffusion architectures emerge: adversarial distillation of diffusion models achieves the diversity of diffusion with the speed of GANs. Regulatory frameworks begin to address the use of synthetic medical images in clinical AI development.
- 2026
Foundation models for medical image generation combine GAN discriminators with diffusion backbones, trained on millions of de-identified medical images. Synthetic data becomes a standard component of FDA-cleared medical AI pipelines, with provenance tracking to distinguish real from generated data.
Caution.
GAN-generated medical images can fool radiologists - handle with care.
Modern GAN-generated medical images are of sufficient quality to deceive expert radiologists. In controlled studies:
Radiologists classified GAN-generated chest X-rays as real with probability (near chance) (Salehinejad et al., 2018);
Pathologists could not distinguish GAN-generated histopathology patches from real ones at magnifications below ;
Dermatologists rated GAN-generated skin lesion images as “clinically plausible” in of cases.
This realism creates several risks:
Data integrity. If synthetic images infiltrate a dataset without proper labelling, models may be trained or evaluated on fake data, corrupting performance estimates.
Research fraud. GAN-generated images could be used to fabricate experimental results in medical research.
Medicolegal liability. If a clinical decision is influenced by a model trained on undisclosed synthetic data that introduced systematic biases, liability becomes unclear.
Regulatory compliance. The FDA and EMA are developing frameworks for synthetic data in medical AI, but clear guidelines remain incomplete as of 2026.
Mitigation strategies:
Always tag synthetic images with metadata indicating their generative origin;
Maintain separate data stores for real and synthetic images;
Report the fraction of synthetic data used in any training pipeline;
Apply watermarking or steganographic techniques to enable post-hoc identification of synthetic content.
Exercise 14 (SegAN Loss Analysis).
Consider a SegAN with a three-scale critic () where the feature map dimensions at each scale are , , and .
Compute the normalisation constant for each scale.
Suppose the critic's features for the ground truth mask are all-zeros at every scale (a simplification for analysis). If the features for the predicted mask are (constant at each scale), express as a function of .
A single boundary pixel error at the finest scale displaces feature map entries at scale , entries at scale , and entry at scale , each by magnitude . Compare the gradient signal from the multi-scale loss to that of a loss using only scale . By what factor is the boundary gradient amplified?
Discuss why the multi-scale loss is analogous to a Laplacian pyramid decomposition of the segmentation error.
Exercise 15 (CycleGAN Consistency Properties).
Let and be CycleGAN generators trained to translate between MRI (domain ) and CT (domain ). Assume both generators are bijective (invertible) mappings.
Show that if the cycle consistency loss reaches zero, then .
The cycle consistency loss uses distance. Derive what would change if distance were used instead. Specifically, consider the gradient with respect to the generator parameters and discuss the effect on boundary sharpness in translated images.
In practice, and are neural networks and therefore not exactly invertible. Define the cycle reconstruction error as . For a dataset of images, you observe (normalised to pixel range). Is this acceptable for downstream segmentation? Justify by estimating the Dice score impact.
A common failure mode is that CycleGAN “hides” information in high-frequency patterns imperceptible to the discriminator (steganographic encoding). Propose a regularisation strategy to prevent this.
Exercise 16 (GAN vs Diffusion for Clinical Deployment).
A hospital radiology department wants to deploy an AI system for liver tumour segmentation. They have annotated CT scans and need to augment the training set with synthetic data.
The system must generate synthetic CT slices with tumour masks. Compare the wall-clock time for GAN-based generation (single forward pass at ms/image) versus diffusion-based generation ( denoising steps at ms/step). What is the total generation time for each approach?
The department has observed that of their tumours are hepatocellular carcinoma with atypical enhancement patterns. Using the mode collapse proposition (Proposition 4), argue why a GAN might underrepresent this subtype in the synthetic data. Propose two mitigation strategies.
Design a quality control pipeline for the synthetic data that checks: (i) realism (the synthetic images look like real CT slices), (ii) diversity (the synthetic set covers the full distribution), and (iii) clinical validity (the synthetic tumours are anatomically plausible). Specify which quantitative metrics you would use for each check.
The hospital's IRB requires that synthetic images cannot be traced back to individual patients. Discuss whether GAN-generated images satisfy this requirement and propose a verification protocol.
DDPM Fundamentals for Segmentation
The preceding sections explored adversarial and variational approaches to medical segmentation. We now turn to an entirely different generative paradigm-one that has, in the span of a few years, reshaped the landscape of image synthesis and is rapidly transforming segmentation as well. Denoising diffusion probabilistic models (DDPMs) generate data by learning to reverse a gradual noising process. When applied to segmentation, the key conceptual shift is profound: rather than predicting a single deterministic mask, the model samples masks from a learned distribution conditioned on the input image. Each sample is a plausible segmentation, and the distribution over samples captures the inherent ambiguity of medical image interpretation.
This section establishes the mathematical foundations of DDPMs (Forward and Reverse Processes), explains how to condition the diffusion process on medical images (Conditioning on Medical Images), and motivates the move to latent-space diffusion for high-resolution medical data (Latent Diffusion for High-Resolution Medical Data).
Forward and Reverse Processes
A DDPM defines two Markov chains: a forward (noising) process that gradually destroys structure, and a reverse (denoising) process that learns to reconstruct it. In the segmentation setting, the data being diffused is a segmentation mask (or its continuous relaxation), rather than a natural image.
Forward process.
The forward process adds Gaussian noise over steps according to a variance schedule : (Forward STEP) Define and . A key property of the forward process is that we can sample at an arbitrary timestep directly from without iterating through intermediate steps: (Forward Marginal) This allows efficient training, as we can compute the noised version of any mask at any timestep in closed form: (Reparameterize)
Reverse process.
The reverse process is parameterized as a Gaussian with learned mean and fixed (or learned) variance : (Reverse STEP) Ho et al. (Ho et al., 2020) showed that parameterizing in terms of a noise prediction network leads to a simple training objective: (LOSS Simple) where , , , and is computed via (Reparameterize).
Noise schedule design.
The original DDPM used a linear schedule , but medical segmentation masks are typically simpler and more structured than natural images. A cosine schedule (Nichol and Dhariwal, 2021), (Cosine Schedule) with a small offset , preserves more information in the early steps and is generally preferred for segmentation masks, where low-frequency structures (overall organ shape) should persist longer than high-frequency details (boundary refinements).
Remark 18.
Binary masks are not naturally suited to Gaussian diffusion. Two common strategies address this: (i) treating the mask as a continuous-valued image in and thresholding at inference time, or (ii) encoding the mask through a small autoencoder that maps to a continuous latent space. Strategy (ii) is used in latent diffusion approaches discussed in Latent Diffusion for High-Resolution Medical Data.
Conditioning on Medical Images
In unconditional DDPMs, the reverse process generates samples from the learned data distribution . For segmentation, we need a conditional reverse process , where is the input medical image. This conditioning is the critical design choice that transforms a generative model into a segmentation engine.
Definition 20 (Conditional Diffusion for Segmentation).
A conditional diffusion segmentation model defines a reverse process of the form (COND Diffusion) where is the prior, is the input medical image, and each denoising step conditions on through a mechanism integrated into the noise prediction network . The training objective becomes (COND LOSS) At inference, a segmentation mask is obtained by sampling and iteratively denoising through the learned reverse process.
Three principal conditioning mechanisms have emerged in the medical imaging literature:
Channel concatenation.
The simplest approach concatenates the image with the noisy mask along the channel dimension before feeding into the U-Net: (COND Concat) where denotes channel-wise concatenation. This is computationally inexpensive but forces the network to disentangle image features from mask noise at every layer.
Cross-attention conditioning.
A more expressive approach encodes the image with a separate encoder and injects the resulting feature maps into the U-Net via cross-attention layers: (Cross ATTN) where comes from the U-Net features (noisy mask pathway) and come from (image pathway). This allows the denoising network to selectively attend to relevant anatomical structures at each spatial location.
Classifier-free guidance.
Classifier-free guidance (Ho and Salimans, 2022) interpolates between conditional and unconditional predictions: (CFG) where is the guidance scale. During training, the conditioning input is randomly dropped (replaced with a null embedding) with probability , typically . At inference, larger values of produce sharper, more confident segmentation masks at the potential cost of reduced diversity.
Insight.
The denoising process naturally implements coarse-to-fine segmentation refinement. At high noise levels (large ), the reverse process recovers the overall shape and location of anatomical structures. As decreases, progressively finer boundary details emerge. This multi-scale refinement mirrors the hierarchical reasoning process of expert radiologists, who first identify the region of interest before delineating precise boundaries.
Latent Diffusion for High-Resolution Medical Data
Medical images routinely reach resolutions of pixels for 2D modalities (fundoscopy, dermatoscopy) and can extend to voxels for volumetric CT or MRI. Running the diffusion process in pixel space at these resolutions is computationally prohibitive: the U-Net must process the full-resolution input at every one of the denoising steps, and the memory requirements scale quadratically with spatial resolution for attention-based architectures.
Latent diffusion models (LDMs) (Rombach et al., 2022) resolve this by separating the problem into two stages:
Stage 1: Autoencoder compression. A variational autoencoder (or VQ-VAE) maps the mask to a compact latent representation , where , , and is the spatial downsampling factor. The decoder reconstructs the mask: .
Stage 2: Latent diffusion. The DDPM operates on the latent code rather than the pixel-space mask. All forward and reverse process equations (eq:medseg:ddpm:forward-step,eq:medseg:ddpm:reverse-step) apply with replaced by .
Proposition 5 (Compute Reduction from Latent Diffusion).
Let be the spatial compression ratio of the autoencoder (i.e., the latent spatial dimensions are ). For an attention-based U-Net backbone, the per-step computational cost of latent diffusion is reduced by a factor of compared to pixel-space diffusion for self-attention layers, and by for convolutional layers. For 3D volumetric data, the savings increase to .
Proof.
Consider a self-attention layer operating on a feature map of spatial dimensions . The attention matrix has size , so the computational cost scales as .
In pixel-space diffusion, and , giving cost . In latent diffusion, and , giving cost . The ratio of pixel-space cost to latent cost is therefore for attention layers. However, U-Nets use attention only at low-resolution feature maps; at the resolution where attention is typically applied (e.g., after downsampling stages), the effective spatial reduction from latent encoding is in absolute FLOPs.
For convolutional layers with fixed kernel size , the per-layer cost is , which scales as in the spatial dimensions. Moving to latent space reduces the spatial dimensions by , yielding an reduction.
The overall per-step cost is dominated by convolutional layers in typical U-Net architectures, giving an aggregate reduction of . For 3D volumes, the spatial dimensions become , and the convolution cost scales as , so the savings are .
Remark 19.
In practice, medical latent diffusion models use or . For , a image becomes a latent, reducing per-step convolution cost by approximately . A 3D volume of compressed to yields a reduction. This makes diffusion-based segmentation tractable on clinical workstation GPUs.
Diffusion-Based Segmentation Methods
With the mathematical foundations established, we now survey the principal architectures that instantiate diffusion-based medical segmentation. Each method introduces a distinct innovation: MedSegDiff pioneers dynamic conditional coding for step-wise image-mask fusion (MedSegDiff: Dynamic Conditional Coding); MedSegDiff-V2 replaces the U-Net backbone with a vision transformer for global context (MedSegDiff-V2: Transformer Backbone); DermoSegDiff introduces boundary-aware mechanisms for dermatological applications (DermoSegDiff: Boundary-Aware Diffusion); and a noise-consistent Siamese architecture leverages diffusion for data augmentation (Noise-Consistent Siamese-Diffusion).
MedSegDiff: Dynamic Conditional Coding
MedSegDiff (Wu et al., 2024) introduced a fundamental architectural insight: in medical segmentation, the conditioning image should not simply be concatenated with the noisy mask and forgotten. Instead, the image features should be dynamically fused with the evolving mask representation at every denoising step, adapting the fusion based on the current noise level .
Definition 21 (Dynamic Conditional Coding).
Let denote the feature map extracted from the input image at layer of an image encoder, and let denote the corresponding feature map of the noisy mask at the same layer of the denoising U-Net. Dynamic conditional coding (DCC) computes a step-dependent fused feature (DCC) where are learned affine modulation parameters conditioned on the timestep via (DCC Modulation) denotes channel-wise multiplication (broadcast over spatial dimensions), and is a Feature Frequency Parser that suppresses high-frequency noise in the fused representation.
The timestep-dependent modulation is crucial. At early denoising steps (large ), the mask is mostly noise, so the network should rely heavily on image features ( large, small). At later steps (small ), the mask has taken shape and both streams carry complementary information. The learned modulation parameters automatically discover this schedule.
Feature Frequency Parser (FF-Parser).
Medical images contain both informative anatomical frequencies and uninformative noise, particularly at high denoising timesteps. The FF-Parser applies a learned frequency filter in the Fourier domain: (FF Parser) where and denote the 2D discrete Fourier transform and its inverse, and is a learnable frequency-domain weight matrix. The parser adaptively attenuates high-frequency components that correspond to diffusion noise while preserving the structural frequencies that encode boundary information.
Example 15 (MedSegDiff for Optic Cup Segmentation).
Consider the task of segmenting the optic cup from fundus photographs, a critical step in glaucoma screening. The optic cup boundary is notoriously difficult to delineate due to its gradual intensity transition and high inter-observer variability.
MedSegDiff is trained on the REFUGE challenge dataset (Orlando et al., 2020) with denoising steps. At inference, the model receives a fundus image and generates a segmentation mask through iterative denoising:
Initialize .
At each step : itemize
Extract image features from the frozen encoder at each U-Net level .
Compute timestep-modulated fusion via (DCC).
Apply the FF-Parser to suppress noise-band frequencies.
Predict noise and compute . itemize
Threshold at to obtain a binary mask.
The resulting segmentation achieves a Dice score of on the REFUGE test set, surpassing the deterministic U-Net baseline () and nnU-Net (). By running multiple sampling chains, the model produces a distribution of masks that captures the clinical ambiguity of the optic cup boundary-the standard deviation of sampled masks concentrates precisely at the cup-disc boundary, matching the zone of highest inter-grader disagreement.
MedSegDiff-V2: Transformer Backbone
While MedSegDiff demonstrated the power of diffusion for medical segmentation, its U-Net backbone inherits a fundamental limitation: convolutional architectures process information through local receptive fields, and global context emerges only after multiple downsampling stages. For large organs or diffuse pathologies, this locality can be a bottleneck.
MedSegDiff-V2 (Wu et al., 2024) addresses this by replacing the U-Net with a vision transformer (ViT) backbone, augmented with a novel anchor condition mechanism that stabilizes the diffusion process.
Transformer denoising backbone.
The noisy mask and the conditioning image are each divided into non-overlapping patches of size . The mask patches are linearly projected to -dimensional tokens (where ), and the image patches yield conditioning tokens . The transformer alternates between self-attention on and cross-attention between (queries) and (keys/values): (V2 SELF ATTN)
Anchor condition mechanism.
A known difficulty with transformer-based diffusion is training instability, particularly at high noise levels where the mask tokens carry almost no signal. The anchor condition mechanism addresses this by providing a coarse segmentation estimate from a lightweight CNN head: (V2 Anchor) where is a small encoder-decoder trained jointly with the diffusion model. The anchor prediction is concatenated with the noisy mask before tokenization: . This provides the transformer with a rough structural prior at every denoising step, preventing the attention mechanism from “wandering” in the high-noise regime.
Performance gains.
On five medical segmentation benchmarks (REFUGE optic cup, ISIC dermoscopy, BraTS brain tumor, BTCV abdominal organs, Synapse multi-organ), MedSegDiff-V2 consistently outperforms MedSegDiff by Dice points, with the largest gains on tasks requiring global anatomical understanding (multi-organ segmentation) where the transformer's long-range attention provides the greatest advantage.
Remark 20.
The transformer backbone has computational complexity for self-attention, where is the number of tokens. For a image with patch size , we have tokens, making the cost manageable. However, for 3D volumes or very high-resolution images, linear attention variants or windowed attention (as in Swin Transformer) may be necessary. The cross-attention with image tokens adds per layer but provides the critical anatomical conditioning that guides the denoising process.
DermoSegDiff: Boundary-Aware Diffusion
Dermatological lesion segmentation presents unique challenges: lesion boundaries are often irregular, diffuse, and poorly contrasted against surrounding skin. DermoSegDiff (Bozorgpour et al., 2023) addresses this by incorporating explicit boundary supervision into the diffusion process.
Boundary attention module.
The model extracts a boundary map from the ground-truth mask using a Sobel operator. During training, a boundary attention module modulates the denoising features at each U-Net layer: (Dermoseg Boundary) where is the boundary map downsampled to match layer , is the sigmoid function, and the convolution learns which boundary regions require enhanced attention. This residual gating mechanism ensures that boundary pixels receive disproportionate representational capacity.
Multi-scale boundary loss.
The training objective augments the standard diffusion loss with a boundary-focused term: (Dermoseg LOSS) where is the predicted noise at layer and weights the boundary contribution. By weighting the loss by the boundary map, the model is forced to predict noise more accurately at boundary pixels, leading to sharper delineations.
On the ISIC 2018 challenge dataset, DermoSegDiff achieves a Dice score of and a boundary F1 score of , representing a improvement in boundary quality over MedSegDiff while maintaining competitive region-level accuracy.
Remark 21.
The effective width of the boundary attention region is a critical hyperparameter. A Sobel-based boundary map produces a single-pixel-wide edge, but dilating it to a band of width pixels captures the transition zone. In practice, pixels works well for dermoscopy images at resolution, roughly corresponding to the ,mm physical scale of the lesion transition zone. Too narrow a band fails to capture gradual transitions; too wide a band dilutes the boundary signal.
Noise-Consistent Siamese-Diffusion
While the preceding methods use diffusion directly for inference, an alternative paradigm uses diffusion for data augmentation: generating synthetic image-mask pairs to train a separate, fast segmentation network. The key challenge is ensuring that the generated image and mask remain spatially aligned-that the synthetic lesion in the image corresponds precisely to the synthetic mask.
The Noise-Consistent Siamese-Diffusion framework (Chen et al., CVPR 2025) addresses this through a dual-branch architecture that generates image-mask pairs simultaneously while enforcing morphological consistency.
Architecture.
The model consists of two diffusion branches sharing a common noise schedule: an image branch and a mask branch . At each denoising step, the branches exchange information through a cross-consistency module: (Siamese IMG) where each branch conditions on the other's noisy state.
Noise consistency loss.
To ensure spatial alignment, the model enforces that the noise patterns are consistent between branches. Specifically, at each timestep, the noise applied to corresponding spatial locations in image and mask must be correlated: (Siamese Consist) where computes spatial gradients. This loss ensures that structural transitions (edges, boundaries) appear at the same locations in both the generated image and the generated mask.
Morphological consistency.
Beyond pixel-level alignment, the framework enforces morphological properties: generated lesion masks must have realistic area, convexity, and boundary smoothness. A morphological regularizer penalizes masks whose shape statistics deviate from the training distribution: (Siamese Morph) where are differentiable morphological descriptors (area, perimeter, compactness).
Experiments demonstrate that training a lightweight segmentation network on the augmented dataset (real + synthetic pairs) improves Dice scores by across three dermatological and two cardiac segmentation tasks, with the largest gains in low-data regimes ( training samples).
Ambiguity Modeling with Diffusion
The most compelling advantage of diffusion models for medical segmentation is not their accuracy on a single prediction, but their capacity to model the distribution of plausible segmentations. In clinical practice, segmentation is rarely unambiguous: different radiologists draw different boundaries, and the “true” segmentation may not exist as a single mask. Diffusion models, as learned samplers from a conditional distribution , are naturally equipped to capture this ambiguity.
Key Idea.
Diffusion models don't predict one mask-they sample from the space of plausible masks. Each run of the reverse process, starting from a different noise sample , produces a different but valid segmentation. The variance across samples is not a deficiency; it is an accurate reflection of the inherent uncertainty in medical image interpretation. Regions where samples agree are unambiguous; regions where they disagree are precisely the areas where clinical judgment diverges.
This section explores architectures that explicitly model and control this ambiguity: CIMD, which introduces dedicated ambiguity networks (CIMD: Collectively Intelligent Medical Diffusion); DiffAug, which uses text-guided synthesis for data augmentation (DiffAug: Text-Guided Synthetic Augmentation); self-supervised and unsupervised approaches (Self-Supervised and Unsupervised Diffusion); and the GMS framework for parameter-efficient diffusion segmentation (Generative Medical Segmentation (GMS) Framework).
CIMD: Collectively Intelligent Medical Diffusion
While vanilla conditional diffusion can produce diverse masks through different noise initializations, the diversity is uncontrolled: there is no mechanism to ensure that the sampled masks correspond to the specific modes of annotator disagreement. CIMD (Collectively Intelligent Medical Diffusion) (Rahman et al., 2023), presented at CVPR 2023, addresses this limitation with a principled probabilistic framework that decomposes ambiguity into an explicit latent variable.
Problem formulation.
Given a medical image and a set of annotator masks (one per annotator), CIMD learns to model the full conditional distribution , capturing the collective intelligence of the annotator panel. The key architectural innovation is the introduction of two auxiliary networks alongside the core diffusion model.
Definition 22 (Ambiguity Modeling Network).
The Ambiguity Modeling Network (AMN) is a conditional encoder that maps an image-mask pair to a distribution over a latent ambiguity code : (AMN) where and are neural networks that take as input the concatenation of image and mask features. The AMN acts as a posterior approximation: given a specific annotation , it encodes the “style” of that annotator into , capturing what makes this particular annotation different from others.
Ambiguity Controlling Network (ACN).
The ACN is a prior network that models the distribution of ambiguity codes given only the image (without seeing any mask): (ACN) At inference time, when no ground-truth mask is available, the ACN provides the latent codes that guide the diffusion process.
Conditioned reverse process.
The diffusion model's noise prediction network takes the ambiguity code as an additional conditioning signal: (CIMD Denoise) where is sampled from during training and from during inference.
Theorem 3 (ELBO Decomposition for CIMD).
The CIMD training objective decomposes into three terms: (CIMD ELBO) where is the standard conditional diffusion loss with the ambiguity code , and are hyperparameters.
Proof.
We derive the bound from the log-marginal likelihood of the annotated data. For a training pair , the marginal likelihood is (CIMD Marginal) Introducing the approximate posterior and applying Jensen's inequality: (CIMD ELBO Derive1) The first term is the expected reconstruction quality. For the diffusion model, is lower-bounded by the negative diffusion loss (from the standard DDPM variational bound), giving term (i) in (CIMD ELBO). The KL divergence between the approximate posterior and prior is term (ii).
Term (iii) arises from a hierarchical prior construction. We decompose through a regularizer that prevents the ACN from collapsing to a delta distribution. Specifically, we add a penalty that encourages the prior to maintain diversity. Since both and are Gaussian, this KL divergence has a closed-form expression: (CIMD KL Closed) Combining all three terms and negating gives the ELBO in (CIMD ELBO).
Training procedure.
For each training image with annotator masks :
Sample an annotator index .
Encode ambiguity: .
Sample timestep and noise .
Compute from (CIMD ELBO).
Update jointly.
Inference.
At test time, the AMN is discarded (it requires a ground-truth mask). To sample diverse segmentations:
Compute the prior: .
For : itemize
Sample .
Sample .
Run the reverse process conditioned on . itemize
Report the sample mean and per-pixel variance.
Example 16 (CIMD on LIDC-IDRI Lung Nodule Ambiguity).
The LIDC-IDRI dataset provides CT scans of lung nodules, each annotated independently by four radiologists. For small, sub-solid (ground-glass) nodules, inter-annotator agreement is notoriously low: the four-annotator intersection-over-union (IoU) can be as low as , meaning the radiologists agree on only of the pixels they collectively label as nodule.
CIMD is trained on LIDC-IDRI with annotators. At test time, the model generates masks per image by sampling different values from the ACN prior. The evaluation uses two metrics:
Generalized Energy Distance (GED): Measures how well the distribution of sampled masks matches the distribution of annotator masks. CIMD achieves a GED of , improving over the probabilistic U-Net () and the stochastic segmentation network ().
Sample Diversity: The per-pixel variance of the sampled masks. CIMD's variance map closely mirrors the spatial pattern of annotator disagreement: high variance at the fuzzy boundary of ground-glass nodules, low variance at the solid core.
Qualitatively, different samples produce masks that resemble the “styles” of individual annotators: some are conservative (tight boundaries around the solid core), while others are liberal (including the full ground-glass halo). The AMN has learned to disentangle these annotation styles into the latent space.
DiffAug: Text-Guided Synthetic Augmentation
A persistent challenge in medical AI is the scarcity of training data for rare pathologies. Standard data augmentation (flips, rotations, elastic deformations) cannot create new pathological patterns that were absent from the original dataset. DiffAug (DiffAug, 2024) addresses this by using a pre-trained text-to-image diffusion model to synthesize realistic pathological images together with their segmentation masks, guided by textual descriptions of the desired pathology.
Pipeline overview.
The DiffAug pipeline operates in three stages:
Inpainting with text guidance. Given a healthy image and a spatial mask indicating where the pathology should appear, a text-conditioned diffusion model performs inpainting: (Diffaug Inpaint) where is the CLIP text embedding of a description such as “flat sessile polyp with subtle mucosal discoloration.”
Mask refinement. The initial spatial mask is coarse. A refinement step adjusts the mask to match the actual extent of the generated pathology using a lightweight boundary detector: (Diffaug Refine) where is a small CNN and is the sigmoid function.
Quality filtering. A latent-space validation network scores each synthetic pair : (Diffaug Validate) where is an autoencoder. Pairs with are discarded as unrealistic.
Latent-space validation.
The validation network is trained on real pathological images to distinguish realistic from unrealistic pathology. By operating in latent space rather than pixel space, it captures semantic plausibility (“does this look like a real polyp?”) rather than superficial texture matching. The validation step is critical: without it, approximately of synthetic images contain artifacts (discontinuities at inpainting boundaries, anatomically impossible lesion shapes) that would degrade downstream segmentation performance.
Example 17 (DiffAug for Rare Flat Polyps in Colonoscopy).
Flat (sessile) polyps are a high-risk subtype of colorectal lesion that account for fewer than of cases in standard colonoscopy datasets but have elevated malignancy rates. Their rarity creates a severe class imbalance that standard augmentation cannot resolve.
Using DiffAug, the authors generate synthetic flat polyps with text prompts such as:
The spatial mask is sampled from a learned shape prior fitted to real flat polyp contours.“Sessile serrated lesion, 8mm diameter, subtle mucosal discoloration on normal colonic mucosa, en-face view.”
Starting from a training set of real flat polyp images, DiffAug generates synthetic pairs, of which pass the latent-space validation filter (acceptance rate: ). Training a segmentation model on the combined dataset yields:
Dice improvement: on flat polyps ( points).
False-negative reduction: fewer missed flat polyps at a fixed false-positive rate.
Negligible degradation on pedunculated (protruding) polyps: Dice.
The false-negative reduction is particularly clinically significant, as missed flat polyps are a leading cause of interval colorectal cancers (cancers that develop between screening colonoscopies).
Self-Supervised and Unsupervised Diffusion
All methods discussed so far require labeled training data-pairs of images and segmentation masks. Yet medical annotation is expensive, requiring expert clinicians who are in short supply. A natural question arises: can diffusion models segment medical images without any labeled data?
Two complementary research directions address this question: (i) exploiting the internal representations of pre-trained diffusion models for zero-shot segmentation, and (ii) self-supervised training strategies that learn segmentation from the diffusion process itself.
Zero-shot segmentation from U-Net features.
A remarkable property of diffusion U-Nets is that their intermediate feature maps encode rich semantic information about the image being denoised. At different layers and timesteps, these features capture different levels of abstraction: early timesteps (high noise) produce features sensitive to global structure, while late timesteps (low noise) produce features encoding fine-grained details.
Given a pre-trained unconditional or class-conditional diffusion model, zero-shot segmentation proceeds as follows:
Forward-diffuse the input image to an intermediate timestep : .
Pass through the denoising U-Net and extract feature maps at a selected set of layers .
Upsample all feature maps to the input resolution and concatenate:
Apply unsupervised clustering (e.g., -means or spectral clustering) on to obtain a segmentation.
GenSelfDiff-HIS.
GenSelfDiff-HIS (Generative Self-Supervised Diffusion for Histopathology Image Segmentation) extends the zero-shot approach with a self-training loop. The method uses the initial unsupervised segmentation as pseudo-labels to fine-tune a lightweight decoder on top of the frozen diffusion features. After fine-tuning, the decoder produces improved pseudo-labels, and the process iterates. Formally, at iteration : (Genselfhis Decode) where is the cross-entropy loss and comes from the initial clustering.
DARL: Diffusion-Augmented Representation Learning.
DARL takes a different approach: it uses the diffusion model as a data augmentation engine for representation learning. The key observation is that partially denoising a noised medical image produces a semantically similar but visually different version-a natural augmentation pair for contrastive learning: (DARL) where is the denoised reconstruction from timestep , is an encoder to be trained, and is the contrastive temperature. The learned representations can then be used with a small number of labeled examples for few-shot segmentation.
Generative Medical Segmentation (GMS) Framework
The methods described above train diffusion models from scratch on medical data, requiring substantial compute and data. The Generative Medical Segmentation (GMS) framework (GMS, 2024) takes a fundamentally different approach: it leverages a pre-trained vision foundation model (such as Stable Diffusion or SDXL) and adapts it for segmentation through a lightweight latent mapping, dramatically reducing the number of trainable parameters.
Architecture.
GMS consists of three components:
Frozen foundation model. A pre-trained latent diffusion model provides the generative backbone. Its encoder , decoder , and U-Net are all frozen-their weights are never updated during medical adaptation.
Latent mapper. A small network transforms the image latent into a conditioning signal suitable for the segmentation task: (GMS Mapper) The mapper has only million parameters, compared to the hundreds of millions in the frozen backbone.
Mask decoder. The diffusion process generates a latent mask code , which is decoded back to pixel space via the frozen decoder: .
Training.
Only the latent mapper is trained. The objective is: (GMS LOSS) where is the noised latent mask code and is the frozen U-Net.
Parameter efficiency.
The dramatic reduction in trainable parameters has practical consequences. On the Synapse multi-organ segmentation benchmark:
MedSegDiff: M trainable parameters, Dice .
MedSegDiff-V2: M trainable parameters, Dice .
GMS: M trainable parameters, Dice .
GMS achieves accuracy between the two MedSegDiff variants while training fewer parameters. This makes the framework particularly appealing for clinical deployment, where computational resources are often limited and adaptation to new imaging protocols must be rapid.
Remark 22.
The success of GMS demonstrates that pre-trained vision foundation models capture transferable structural priors (edges, textures, spatial relationships) that are valuable for medical segmentation, even though these models were trained on natural images. The latent mapper serves as a “translator” between the natural-image feature space and the medical-image segmentation space. This finding aligns with broader trends in foundation model adaptation, where task-specific fine-tuning of a small number of parameters consistently matches or outperforms training from scratch.
| llccc@ Method | Key Innovation | Backbone | Ambiguity | Labels |
| MedSegDiff | Dynamic conditional coding | U-Net | Implicit | Full |
| MedSegDiff-V2 | Transformer + anchor cond. | ViT | Implicit | Full |
| DermoSegDiff | Boundary attention | U-Net | Implicit | Full |
| Siamese-Diff | Noise-consistent aug. | Dual U-Net | N/A | Full |
| CIMD | AMN + ACN | U-Net | Explicit | Full |
| DiffAug | Text-guided inpainting | LDM | N/A | Partial |
| GenSelfDiff | Self-supervised features | Frozen U-Net | Implicit | None |
| GMS | Foundation model adapter | Frozen LDM | Implicit | Full |
Historical Note.
The application of diffusion models to medical segmentation is a remarkably compressed timeline. DDPMs were introduced by Ho et al. in June 2020 (Ho et al., 2020). The first medical segmentation application appeared less than two years later, with MedSegDiff (December 2022) (Wu et al., 2024). CIMD followed at CVPR 2023, introducing explicit ambiguity modeling. By 2024, the field had diversified into self-supervised methods (GenSelfDiff-HIS), text-guided augmentation (DiffAug), and foundation model adaptation (GMS). The Noise-Consistent Siamese-Diffusion at CVPR 2025 represents the latest evolution, using diffusion not for direct inference but as a sophisticated data generation engine. This two-year trajectory from basic application to mature ecosystem mirrors the broader pattern of diffusion model adoption across computer vision, compressed by the urgency of clinical need.
Caution.
A critical limitation of diffusion-based segmentation for clinical deployment is inference speed. While a standard U-Net produces a segmentation mask in a single forward pass (ms on a modern GPU), a diffusion model requires sequential denoising steps, each involving a full U-Net pass. Even with accelerated sampling (DDIM, DPM-Solver), inference times of seconds per image are typical. For real-time clinical applications (e.g., intraoperative guidance, live endoscopy), this latency may be prohibitive. Distillation of diffusion segmentation models into single-step networks is an active area of research.
Exercise 17.
Consider a linear noise schedule with and over steps.
- (a)
Compute and show that is approximately standard Gaussian for any .
- (b)
Now consider a cosine schedule with the same . At what timestep does the cosine schedule reach of the linear schedule? What does this imply about information preservation?
- (c)
For binary segmentation masks, argue whether the linear or cosine schedule is preferable, and explain your reasoning in terms of the signal-to-noise ratio at intermediate timesteps.
Exercise 18.
In the CIMD framework (Theorem 3), suppose the AMN outputs and , while the ACN outputs and .
- (a)
Compute the KL divergence in closed form, given that both distributions are diagonal Gaussians.
- (b)
Compute .
- (c)
If and , which regularization term contributes more to the total loss? Discuss the implications for the diversity of sampled masks.
Exercise 19.
A 3D MRI volume has dimensions . A latent diffusion model uses a 3D autoencoder with spatial compression ratio .
- (a)
What are the latent dimensions? How many latent “pixels” (voxels) does the diffusion model operate on, assuming channels?
- (b)
If the U-Net uses self-attention at the lowest resolution (after 2 additional downsampling stages of factor 2), what is the attention matrix size in pixel-space diffusion vs. latent-space diffusion?
- (c)
Estimate the total memory savings (in GB) for a single denoising step, assuming 32-bit floating-point and a batch size of 1. State your assumptions clearly.
Challenge 2.
(Diffusion Ensemble for Uncertainty-Calibrated Segmentation.) Design and implement a complete pipeline that combines CIMD-style ambiguity modeling with DiffAug-style data augmentation:
Train a CIMD model on a multi-annotator medical segmentation dataset (e.g., LIDC-IDRI or QUBIQ).
Use the trained model to generate synthetic training pairs by: (a) sampling diverse masks from the model, and (b) using the mask-to-image direction of a paired diffusion model to generate corresponding images.
Train a fast deterministic segmentation network (e.g., nnU-Net) on the augmented dataset.
Compare the uncertainty calibration (reliability diagrams, expected calibration error) of: (i) the CIMD model's sample variance, (ii) Monte Carlo dropout on the nnU-Net, and (iii) a deep ensemble of nnU-Nets trained on different synthetic subsets.
Analyze whether diffusion-generated diversity provides better-calibrated uncertainty than standard stochastic methods.
Report Dice, GED, and calibration metrics on a held-out test set. Discuss the computational tradeoffs: inference-time sampling (CIMD) vs. training-time augmentation (DiffAug) vs. test-time ensembling.
Segment Anything Model (SAM)
In April 2023, Meta AI released a model and a dataset that rewrote the rules of image segmentation. The Segment Anything Model (SAM) (Kirillov et al., 2023) was not the most accurate segmentation model on any single benchmark; it was not even designed to be. Instead, SAM introduced a fundamentally new paradigm: a single model, trained once on a colossal dataset, that could segment any object in any image when given a suitable prompt. No fine-tuning, no task-specific training, no per-dataset annotation protocol. A radiologist could click on a liver and get a liver mask. A pathologist could draw a bounding box around a tumour and get a tumour mask. A dermatologist could provide a text description and get a lesion boundary. The model did not need to know what a liver, tumour, or lesion was in advance; it needed only to understand the spatial relationship between the prompt and the visual content.
This paradigm, called promptable segmentation, represents a philosophical shift as profound as the move from handcrafted features to learned representations a decade earlier. Traditional segmentation models are specialists: each one is trained from scratch on a specific dataset, for a specific organ or pathology, in a specific imaging modality. SAM is a generalist. It separates the what to segment question (answered by the prompt) from the how to segment question (answered by the model's learned visual understanding). This separation of concerns is the key insight that makes SAM both powerful and limited, as we shall discover when we turn to medical imaging applications.
Key Idea.
SAM democratises segmentation: anyone can segment anything with a click. By shifting from task-specific training to a universal promptable interface, SAM transforms segmentation from a specialist skill requiring curated datasets, custom architectures, and weeks of training into an interactive tool accessible to any domain expert. The cost of producing a segmentation mask drops from thousands of annotated examples to a single mouse click.
The development of SAM was enabled by a virtuous cycle between data and model. Meta AI first built a data engine that used an early version of the model to assist human annotators, who then corrected the model's outputs, producing higher-quality annotations that were fed back to train a better model. This three-stage process-manual annotation, semi-automatic annotation, and fully automatic annotation-yielded the SA-1B dataset, containing over 11 million images and more than 1.1 billion masks, making it the largest segmentation dataset ever assembled by a factor of 400 over the previous record holder. The scale and diversity of SA-1B are critical to SAM's generalisation: the model has seen so many objects, textures, boundaries, and spatial configurations that it develops a robust understanding of what constitutes a “segment” in the visual world.
The Promptable Segmentation Paradigm
Before defining the paradigm formally, let us contrast it with the conventional approach. In the traditional pipeline, a medical segmentation project proceeds through four stages: (1) collect and curate a dataset of medical images, (2) recruit domain experts to annotate each image with pixel-level masks, (3) design and train a segmentation network (e.g., a U-Net variant) on this dataset, and (4) evaluate on a held-out test set from the same distribution. If the imaging modality changes (e.g., from CT to MRI), or the target anatomy changes (e.g., from liver to pancreas), the entire pipeline must be repeated from scratch. The resulting model is a narrow specialist, excellent within its training distribution but brittle outside it.
The promptable segmentation paradigm inverts this workflow. The expensive part-training a model with general visual understanding-is done once, on a massive and diverse dataset. The cheap part-specifying what to segment-is done at inference time through interactive prompts. This “train once, prompt anywhere” philosophy mirrors the revolution that large language models brought to natural language processing: GPT-3 was not trained to answer medical questions, write poetry, or translate between languages, but it could do all three when given appropriate prompts.
Definition 23 (Promptable Segmentation).
A promptable segmentation model is a function that maps an image and a prompt to a binary mask , where denotes the space of all valid prompts. The prompt space is a union of heterogeneous modalities: (Prompt Space) where is the set of positive and negative point prompts, denotes bounding box prompts, denotes soft mask prompts, denotes text descriptions, and denotes arbitrary combinations thereof. The model must satisfy the ambiguity-aware property: when the prompt is ambiguous (e.g., a single point on a nested structure), the model produces multiple valid masks ranked by confidence.
Remark 23.
The ambiguity-aware property is particularly important in medical imaging. A click on the liver parenchyma could reasonably refer to the entire liver, a specific liver segment (Couinaud classification), or a lesion within the liver. SAM addresses this by producing three output masks at different granularity levels (whole, part, and subpart), each with an associated confidence score. The clinician selects the appropriate level, effectively resolving the ambiguity through an implicit second prompt.
The formal definition captures the essential novelty: the prompt serves as a lightweight, real-time specification of the segmentation task, decoupling the visual understanding (encoded in ) from the task specification (encoded in ). This decoupling is what enables zero-shot transfer: the model's parameters encode general segmentation knowledge, and the prompt redirects this knowledge to a specific object of interest without modifying .
SAM Architecture
SAM consists of three components: a heavyweight image encoder that processes the image once, a lightweight prompt encoder that processes each prompt in real time, and a lightweight mask decoder that fuses the two representations to produce output masks. This asymmetric design is deliberate: the image encoder is expensive (a ViT-H with 632 million parameters), but it runs only once per image and its output can be cached; the prompt encoder and mask decoder are cheap (together less than 10 million parameters), allowing interactive prompting at real-time rates.
Image encoder.
The image encoder is a Vision Transformer (ViT-H) pre-trained with Masked Autoencoding (MAE) (He et al., 2022). The input image is resized to pixels and divided into non-overlapping patches of size . Each patch is linearly embedded into a -dimensional token, and the sequence of 4096 tokens is processed through 32 transformer blocks with global attention. The output is a spatial feature map of size , obtained by projecting the final transformer output from dimension 1280 to 256 via a convolution followed by a convolution.
Let denote the input image. The image encoder produces (Image ENC) where is a dense feature map that captures the spatial structure of the image at a resolution of downsampling. This feature map is the foundation upon which all subsequent prompt interactions are built.
Prompt encoder.
The prompt encoder converts each prompt type into a common embedding space of dimension 256 that is compatible with the image feature map. The encoding strategy depends on the prompt type:
Point prompts. Each point is mapped to a 256-dimensional embedding by summing a learned positional encoding with a learned embedding for the label ( for foreground, for background): (Point ENC)
Box prompts. A bounding box is represented as two point embeddings (top-left corner and bottom-right corner), each with a learned corner-type embedding.
Mask prompts. A dense mask is downsampled and processed through two convolutions with stride 2, producing a spatial embedding that is added element-wise to the image feature map.
Text prompts. Text descriptions are encoded using a text encoder (e.g., from CLIP) and projected to the 256-dimensional prompt space.
All sparse prompts (points, boxes) produce a set of prompt tokens , while dense prompts (masks) are fused directly with the image features.
Mask decoder.
The mask decoder is a lightweight transformer that takes the image embedding and the prompt tokens as input and produces output masks. The decoder consists of two transformer layers, each performing four types of attention:
Self-attention among the output tokens (including prompt tokens and learned mask tokens).
Cross-attention from output tokens to the image embedding .
Cross-attention from the image embedding to the output tokens (allowing the image features to be updated by the prompt).
A token-to-image attention step using the updated image embedding.
The decoder produces three output masks , corresponding to whole, part, and subpart segmentations, along with three associated confidence scores (Intersection over Union predictions) . Each mask is produced by taking the dot product of an output token with the spatially upsampled image embedding, followed by a sigmoid activation: (MASK Decode) where is the -th output token and is the updated image embedding from the decoder.
The SA-1B dataset.
The training dataset, SA-1B, was collected through a three-stage data engine:
Assisted-manual stage (120K images). Human annotators labeled masks by clicking on objects, assisted by an early SAM prototype that provided automatic suggestions. The average annotation time was 34 seconds per mask.
Semi-automatic stage (180K images). The improved model automatically detected confident objects, and annotators focused on labeling the remaining unannotated regions, increasing mask diversity.
Fully automatic stage (11M images). The nearly final model was applied to 11 million images with a grid of point prompts per image, generating masks automatically. Non-maximum suppression and quality filtering removed duplicates and low-confidence predictions.
The final dataset contains 11 million images and 1.1 billion masks, with an average of 100 masks per image. The images were sourced from a licensed provider and span a broad distribution of natural scenes, though notably not medical images. This distributional gap between the training data and medical imaging applications is a central theme of the sections that follow.
Prompt Types and Their Effects
The choice of prompt type has a profound effect on segmentation quality, and the relationship between prompt quality and mask quality is not always intuitive. We examine each prompt type in turn, with particular attention to the medical imaging context.
Point prompts.
A single positive point prompt tells the model “segment the object at this location.” The model must infer the entire object boundary from this minimal specification, relying entirely on its learned visual features. In natural images, where objects have clear boundaries (a dog against a grassy background), a single point often suffices. In medical images, where tissue boundaries are subtle and objects are nested (a tumour within a lobe within an organ), a single point is frequently ambiguous.
The effectiveness of point prompts depends critically on point placement. A point near the centre of a large, high-contrast organ (e.g., the liver in a CT scan) typically produces a good mask because the visual features around the point unambiguously indicate the organ boundary. A point near the edge of a small, low-contrast structure (e.g., the pancreas) often produces a poor mask because the local features are ambiguous.
Multiple positive and negative points can be combined to refine the segmentation. The negative point tells the model “this location is not part of the target object,” providing exclusion information that helps resolve ambiguity. In practice, a prompt of 3–5 positive points plus 1–2 negative points typically achieves 80–90% of the quality of a full bounding box prompt on natural images.
Box prompts.
A bounding box is the strongest geometric prompt type because it constrains both the location and the approximate extent of the target object. Box prompts consistently produce the highest-quality masks among the standard prompt types, particularly for objects with irregular shapes that are poorly captured by a single point.
In medical imaging, bounding boxes are particularly effective because most clinical workflows already involve drawing regions of interest (ROIs) around structures of interest. A radiologist who draws a box around a suspicious lung nodule on a CT slice effectively provides a box prompt that SAM can use to generate a precise segmentation mask. The box removes much of the ambiguity inherent in point prompts: a box tightly containing a liver segment unambiguously specifies which segment is intended, even if the segment's boundary is visually subtle.
Mask prompts.
A prior mask provides the model with a rough initial segmentation that should be refined. This prompt type is particularly useful in iterative workflows: the output of one SAM invocation can be used as a mask prompt for a subsequent invocation, progressively refining the segmentation. Mask prompts are also central to SAM's application in 3D medical volumes, where the segmentation of one slice can serve as a mask prompt for the adjacent slice (see Adapting SAM for 3D Volumes).
Text prompts.
Text prompts (e.g., “segment the left kidney”) leverage a CLIP text encoder to produce semantic embeddings. While text prompts are the most intuitive for clinicians who think in anatomical terms, they are also the least precise because text descriptions are inherently ambiguous about spatial extent. The phrase “left kidney” specifies what to segment but gives no spatial information about where the kidney is in the particular image. In practice, text prompts in the original SAM are less developed than geometric prompts and are significantly enhanced in later variants such as SAM 3.
Prompt quality and segmentation quality.
The relationship between prompt quality and segmentation quality follows a diminishing-returns curve. A box prompt achieves approximately 75% of the quality of a fully supervised model, and adding points within the box captures most of the remaining gap. Formally, if we denote the Dice score as a function of prompt informativeness , we observe empirically that (Prompt Quality) where is the asymptotic Dice score achievable with perfect prompts and controls the rate of saturation. This exponential saturation means that the first prompt element (a single point or box) provides the largest marginal improvement, with additional prompt elements yielding progressively smaller gains.
SAM's Strengths and Limitations for Medical Imaging
The release of SAM generated immediate excitement in the medical imaging community. Researchers rushed to evaluate its zero-shot performance on clinical tasks, and the results painted a nuanced picture: SAM excelled in some settings and failed dramatically in others. Understanding this pattern of success and failure is essential for deploying SAM responsibly in clinical workflows.
Caution.
Zero-shot SAM on medical images requires careful prompt engineering. Unlike natural images, where object boundaries are typically defined by texture and colour discontinuities, medical image boundaries are often defined by subtle intensity gradients, anatomical context, and prior knowledge of tissue properties. SAM's visual features, learned entirely from natural images, may not capture these domain-specific cues. A zero-shot SAM deployment without appropriate prompting strategies can produce dangerously inaccurate segmentations that appear superficially plausible.
Where SAM succeeds.
SAM performs well on medical structures that share visual characteristics with natural-image objects: high contrast against the background, clear and well-defined boundaries, relatively large size, and simple (convex or near-convex) shapes. Specific examples include:
Liver in CT. The liver is the largest abdominal organ, with relatively homogeneous parenchyma and clear boundaries against surrounding fat and adjacent organs. Zero-shot SAM with a bounding box prompt achieves Dice scores of 85–90% on many CT datasets.
Lungs in chest X-ray and CT. The air-filled lungs provide strong contrast against the mediastinum and chest wall. SAM segments lungs with Dice even with a single point prompt.
Large tumours. Tumours above approximately 3,cm in diameter with clear enhancement on contrast-enhanced CT or MRI are often segmented adequately, particularly when a bounding box prompt is provided.
Bones and calcifications. High-density structures on CT have extreme contrast and are easy for SAM to delineate.
Where SAM fails.
SAM struggles with structures that lack the visual cues present in natural images:
Pancreas. The pancreas is small, irregularly shaped, and has poor contrast against surrounding retroperitoneal fat. Zero-shot SAM achieves Dice scores below 30% for pancreas segmentation, compared to 80–85% for supervised models.
Small lesions. Lesions below 1,cm in diameter are often missed entirely or merged with adjacent structures. SAM's patch size of pixels means that a 5,mm lesion in a standard CT volume may occupy only 1–2 patches, providing insufficient local context.
Low-contrast boundaries. The boundary between grey matter and white matter in brain MRI, or between tumour and surrounding oedema, relies on subtle intensity differences that SAM's natural-image features do not capture.
3D structures. SAM processes each 2D slice independently, with no mechanism for enforcing consistency across slices. This leads to jagged, discontinuous 3D segmentations.
Multi-class segmentation. SAM is inherently a binary segmenter (foreground vs. background) and has no native support for multi-class segmentation tasks common in medical imaging (e.g., segmenting all abdominal organs simultaneously).
Proposition 6 (SAM Performance vs. Organ Complexity).
Let be a set of organs evaluated with zero-shot SAM using bounding box prompts. For each organ , let denote its average volume (in cm), denote its boundary contrast (measured as the average absolute intensity gradient across the organ boundary in Hounsfield units), and denote the achieved Dice score. The empirical relationship follows (Complexity) where indicate that Dice increases with both organ volume and boundary contrast. Fitting this model to a multi-organ abdominal CT dataset yields (a 10 increase in volume improves Dice by 6 percentage points) and (a 10 increase in boundary contrast improves Dice by 9 percentage points). The residual captures organ-specific shape complexity: organs with tortuous or branching morphologies (e.g., the portal vein, pancreatic duct) have systematically negative residuals.
Empirical validation.
The log-linear model in (Complexity) was fitted to the evaluation of SAM on the BTCV (Beyond the Cranial Vault) multi-organ segmentation benchmark, which includes 13 abdominal organs spanning a wide range of sizes (from the aorta at 20,cm to the liver at 1500,cm) and contrasts. The fitted model explains approximately of the variance in organ-level Dice scores, confirming that size and contrast are the dominant predictors of zero-shot SAM performance. The largest residuals occur for the pancreas () and the gallbladder (), reflecting the former's irregular shape and the latter's fluid-filled, high-contrast nature.
The proposition formalises the intuitive observation that SAM's performance degrades with organ complexity: small, low-contrast, irregularly shaped structures are systematically harder. This degradation is not a fixable bug but a fundamental consequence of SAM's training distribution: natural images rarely contain objects with the visual properties of a pancreas or a renal pelvis. Closing this gap requires either adapting SAM to medical data or building medical-specific foundation models, a topic we address in the next section.
SAM 2 and Medical Adaptations
The limitations of SAM for medical imaging spawned a prolific ecosystem of adaptations, extensions, and medical-specific foundation models. This section traces the evolution from SAM to its successors (SAM 2, SAM 3) and the parallel development of medical variants (MedSAM, H-SAM, Medical SAM Adapter, SegVol). The central narrative is one of progressive specialisation: starting from a general-purpose model and incrementally adding the capabilities needed for medical imaging, including temporal awareness, 3D volumetric reasoning, hierarchical decoding, and parameter-efficient domain adaptation.
Historical Note.
The SAM ecosystem has evolved at remarkable speed:
April 2023: SAM released by Meta AI. The promptable segmentation paradigm is introduced with the SA-1B dataset (11M images, 1.1B masks).
Late 2023: First medical adaptations appear. MedSAM is fine-tuned on 1.5M medical image-mask pairs. Medical SAM Adapter introduces parameter-efficient adaptation.
2024: H-SAM proposes hierarchical decoding for medical images. SegVol tackles volumetric segmentation. Dozens of papers explore SAM for specific clinical applications.
January 2025: SAM 2 released, introducing streaming memory for video segmentation with temporal consistency.
2025–2026: SAM 2 is rapidly adopted for 3D medical volumes by treating the -axis as the time dimension. SAM 3 introduces concept-level prompting with text phrases and exemplars.
This timeline illustrates a pattern common in foundation model development: the general-purpose model is released first, followed by a wave of domain-specific adaptations, followed by the next generation that incorporates lessons from the adaptation wave.
SAM 2: Streaming Memory for Video
SAM 2 (Ravi et al., 2024) extends the original SAM from static images to video by introducing a streaming memory mechanism that maintains temporal context across frames. The key insight is elegant: a video is a sequence of images, and segmentation in video requires not just spatial understanding (which SAM already has) but also temporal correspondence-the ability to track the same object as it moves, deforms, and changes appearance across frames.
Definition 24 (Streaming Memory Mechanism).
A streaming memory mechanism for video segmentation is a tuple where:
is a memory bank storing image features , predicted masks , and prompt information from a subset of previously processed frames;
is a memory encoder that converts the current frame's features and predicted mask into a compact memory representation;
is a memory attention module that conditions the next frame's features on the stored memories, producing context-aware features .
The mechanism operates in a streaming fashion: at each time step , the memory bank is updated with the current frame's information, and the next frame's segmentation is conditioned on the accumulated memory. The bank has a fixed capacity , with older or less-informative memories evicted when the capacity is reached.
The SAM 2 architecture modifies the original SAM decoder by inserting a memory attention layer between the image encoder and the mask decoder. This layer performs cross-attention between the current frame's features and the stored memory representations: (Mematt) where denotes concatenation and the cross-attention allows each spatial position in the current frame to attend to all spatial positions in all stored memory frames. The memory-conditioned features are then passed to the mask decoder, which operates identically to the original SAM decoder.
The memory bank uses a fixed-size first-in-first-out (FIFO) strategy with one exception: frames where the user provided an explicit prompt are always retained (never evicted), ensuring that the user's intent is preserved throughout the video. Concretely, the memory bank maintains slots, typically set to in the default configuration. When the bank is full and a new frame must be encoded, the oldest non-prompted frame is evicted. The retained prompted frames serve as anchor memories that prevent the model from drifting away from the user's original intent over long sequences.
This design choice has important implications for medical applications: in a 3D CT volume, the user can prompt on a single slice, and the model propagates the segmentation to all other slices while always conditioning on the originally prompted slice. Furthermore, the user can provide additional prompts on intermediate slices if the propagation quality degrades, and each prompted slice becomes a new anchor memory that improves subsequent propagation. In practice, prompting 2–3 slices (rather than just one) can improve Dice by an additional 3–6 percentage points for challenging organs, at the cost of minimal additional interaction time.
SAM 3: Concept Prompts
SAM 3 represents the next evolutionary step, moving beyond geometric prompts (points, boxes) and simple text to concept-level prompting. The key innovation is that a user can specify a segmentation target not just by pointing or describing, but by providing examples: “segment objects that look like this.”
SAM 3 introduces two new prompt types:
Text phrase prompts. Rather than encoding text through a frozen CLIP model, SAM 3 trains a text encoder jointly with the segmentation model, producing richer semantic embeddings that capture fine-grained distinctions between similar concepts (e.g., “hepatocellular carcinoma” vs. “liver metastasis”).
Exemplar-based prompts. The user provides one or more image-mask pairs as examples of the target concept, and SAM 3 learns to extract the common visual features that define the concept. This is a form of in-context learning adapted to the segmentation setting: the exemplars serve as a “few-shot” specification of the task.
The move from geometric to semantic prompts is significant for medical imaging. A radiologist does not think in terms of points and boxes; they think in terms of anatomical concepts (“segment the hepatic veins”) and visual patterns (“segment all lesions that look like this one”). SAM 3's concept prompts align the model's interface more closely with clinical reasoning, potentially reducing the cognitive overhead of interactive segmentation.
Exemplar-based prompting in detail.
The exemplar-based prompt mechanism works as follows. Given exemplar pairs , SAM 3 computes a concept embedding by:
Encoding each exemplar image through the image encoder to obtain features .
Masking the features with the exemplar mask to isolate the target concept: .
Averaging the masked features across exemplars to form a concept prototype: (Prototype)
Using the concept prototype as a prompt token in the mask decoder, analogous to how point embeddings are used.
This mechanism enables a clinician to show the model three examples of hepatocellular carcinoma lesions from different patients and then segment similar lesions in a new patient's scan, without any text description or geometric prompt. The model learns to extract the visual commonalities across examples and match them in the target image.
Combining prompt types.
SAM 3 allows arbitrary combinations of concept, text, and geometric prompts. A powerful workflow for medical applications is to use a text prompt (“liver lesion”) for initial localisation, followed by an exemplar prompt (showing specific lesion examples) for refinement. The text prompt activates a broad semantic prior, and the exemplar prompt narrows it to the specific visual pattern of interest. This two-stage prompting achieves 5–8 Dice points higher than either prompt type alone on heterogeneous lesion segmentation tasks.
MedSAM: Medical Foundation Model
While SAM 2 and SAM 3 improved the general SAM architecture, MedSAM (Ma et al., 2024) tackled the domain gap directly by fine-tuning SAM on medical data. The approach is conceptually simple: take the original SAM architecture, replace the natural-image training data with medical images, and fine-tune. The devil, as always, is in the details.
Dataset curation.
MedSAM was trained on a curated dataset of approximately 1.5 million image-mask pairs spanning 10 imaging modalities:
Computed tomography (CT)
Magnetic resonance imaging (MRI)
Positron emission tomography (PET)
X-ray
Ultrasound
Mammography
Optical coherence tomography (OCT)
Endoscopy
Dermoscopy
Fundus photography
The dataset was assembled from 30 publicly available medical segmentation datasets, with careful preprocessing to standardise image formats, intensity ranges, and mask representations. This cross-modality coverage is essential: a true medical foundation model must generalise across the diverse imaging technologies used in clinical practice.
Training strategy.
MedSAM fine-tunes the entire SAM model (image encoder + prompt encoder + mask decoder) using bounding box prompts. The choice of box prompts, rather than point prompts, was deliberate: boxes are less ambiguous than points and provide a more consistent supervision signal across the diverse training data. During training, bounding boxes are generated automatically from ground-truth masks by computing the tight bounding box and adding random perturbation (jitter) of up to 20 pixels to simulate realistic user inputs.
The training loss combines a weighted sum of binary cross-entropy and Dice loss: (LOSS) where is the predicted mask, is the ground truth, and are the loss weights.
Example 18 (MedSAM for Cross-Modality Segmentation).
MedSAM's cross-modality capability is demonstrated by its ability to segment the same anatomical structure across different imaging modalities without modality-specific fine-tuning. Consider liver segmentation: the liver appears as a bright, homogeneous region in contrast-enhanced CT, a variable-intensity region in MRI (depending on the pulse sequence), and a moderately echogenic region in ultrasound. Despite these dramatic differences in visual appearance, MedSAM achieves Dice scores of:
CT (LiTS dataset): 94.2%
MRI (CHAOS dataset): 90.8%
Ultrasound: 83.6%
with a single set of model weights and bounding box prompts derived from the same annotation protocol. For comparison, zero-shot SAM (without medical fine-tuning) achieves Dice scores of 89.1%, 78.3%, and 64.2% on the same three modalities, with the performance gap widening as the modality departs further from natural images. The gap is smallest for CT (which resembles natural images in terms of contrast and spatial resolution) and largest for ultrasound (which has speckle noise, low resolution, and acoustic shadows that are absent from natural images).
Adapting SAM for 3D Volumes
Medical imaging is inherently three-dimensional. A CT or MRI scan produces a stack of 2D slices that together form a 3D volume, and the structures of interest (organs, tumours, vessels) are 3D objects that span many slices. Adapting SAM, which was designed for 2D images, to 3D volumes is one of the most important practical challenges in the medical SAM ecosystem.
The key insight is deceptively simple: a 3D volume is a sequence of 2D slices, and a sequence of 2D images is a video. SAM 2's streaming memory architecture, designed for video object tracking, can therefore be repurposed for 3D volumetric segmentation by treating the -axis (the slice direction) as the time axis. The user prompts a single slice, and the model propagates the segmentation to adjacent slices using the memory mechanism, exactly as it would propagate an object mask across video frames.
Example 19 (SAM 2 for 3D Abdominal CT Segmentation).
A comprehensive evaluation of SAM 2 for 3D abdominal CT segmentation was conducted across 21 publicly available datasets covering 78 segmentation targets (organs, tumours, vessels, and other structures). The evaluation protocol used a single bounding box prompt on a user-selected slice, with bidirectional propagation to the remaining slices via SAM 2's memory mechanism.
The results revealed three tiers of performance:
High-performing targets (Dice ): large, high-contrast organs including the liver (91.3%), spleen (89.7%), kidneys (88.4%), and lungs (93.1%). These structures have consistent cross-sectional appearance across slices, making memory-based propagation reliable.
Moderate-performing targets (Dice 50–80%): medium organs with variable contrast, including the stomach (72.1%), gallbladder (68.5%), and adrenal glands (59.2%). Performance was sensitive to the choice of initial prompt slice.
Low-performing targets (Dice ): small or diffuse structures including the pancreas (41.6%), pancreatic duct (22.3%), and small vessels (31.8%). These structures change shape dramatically across slices, causing the memory mechanism to lose track.
Across all 78 targets, the average Dice was 68.4%, compared to 45.2% for slice-by-slice SAM without memory propagation. The 23-point improvement demonstrates the value of temporal (spatial) consistency provided by the streaming memory mechanism.
The success of the -as-time trick rests on an analogy between video object tracking and 3D segmentation that is stronger than it might initially appear. In both cases:
The target object appears in consecutive frames/slices with gradual changes in shape and appearance.
The object may be temporarily occluded (by other structures in the volume or by motion in the video).
The model must maintain a consistent identity for the target across all frames/slices.
The analogy breaks down in one important respect: in video, objects move through space, so spatial position changes across frames; in 3D volumes, the “object” (e.g., an organ) does not move, but its cross-sectional shape changes as the slice plane sweeps through the volume. The memory mechanism handles both cases because it attends to visual features rather than spatial coordinates.
H-SAM: Hierarchical Decoding
While MedSAM improves SAM through full fine-tuning on medical data, H-SAM (Cheng et al., 2024) takes a different approach: it augments the SAM architecture with a second decoding stage that refines the initial mask output. The core idea is that SAM's frozen decoder, while imperfect for medical images, produces a useful prior mask that captures the approximate location and shape of the target. A learnable second-stage decoder then refines this prior into a more accurate segmentation.
The H-SAM architecture operates in two stages:
Stage 1: Frozen SAM decoder. The original SAM decoder (with frozen weights) processes the image embedding and the user's prompt to produce a coarse prior mask . This mask captures the approximate location and extent of the target structure but may have inaccurate boundaries, miss small substructures, or include false-positive regions.
Stage 2: Learnable refinement decoder. The prior mask is fed to a second decoder that employs two novel attention mechanisms: itemize
Mask-guided cross-attention. The prior mask is used to create a spatial attention map that focuses the second decoder on the boundary regions where refinement is most needed. Formally, let be a learned attention map derived from the prior mask. The cross-attention is: (Maskcross) where denotes element-wise multiplication and the mask attention map upweights boundary regions.
Class-balanced self-attention. To address the class imbalance between foreground and background (which is extreme for small organs), the self-attention in the second decoder rebalances the attention weights: (Classbal) where is a learned bias matrix that increases attention to foreground tokens relative to the overwhelmingly more numerous background tokens. itemize
The H-SAM training procedure freezes the image encoder and the Stage 1 decoder, training only the Stage 2 decoder. This design has two advantages: (1) it preserves SAM's general visual understanding, and (2) it dramatically reduces the number of trainable parameters (the Stage 2 decoder has 4M parameters, compared to 632M in the full model).
Results.
On the Synapse multi-organ segmentation benchmark (13 organs from abdominal CT), H-SAM achieves an average Dice improvement of 4.78 percentage points over single-stage SAM with the same prompts, with the largest improvements on small, challenging organs: pancreas (+9.2%), adrenal glands (+7.8%), and gallbladder (+6.3%). The improvement is smallest for large, high-contrast organs (liver +1.2%, spleen +1.5%) where the Stage 1 prior is already accurate. This pattern confirms that the primary value of hierarchical decoding lies in boundary refinement for difficult structures.
Medical SAM Adapter (Med-SA)
Full fine-tuning of SAM on medical data, as in MedSAM, is effective but expensive: the entire 632M-parameter model must be updated and stored for each downstream task or modality. An alternative approach, inspired by the success of adapter methods in natural language processing, is to insert small trainable modules into the frozen SAM architecture and train only these modules on medical data. This is the strategy adopted by Medical SAM Adapter (Med-SA) (Wu et al., 2023).
Definition 25 (Parameter-Efficient Adaptation).
Given a pre-trained model with parameters , parameter-efficient adaptation modifies the model to by introducing a small set of additional parameters (with ) while keeping frozen. The adapted model satisfies (PEA) where represents the task-specific modification introduced by the adapter parameters. The adaptation is parameter-efficient if for some small threshold (typically , meaning fewer than 5% additional parameters).
Med-SA inserts adapter modules into each transformer block of SAM's image encoder. Each adapter consists of a down-projection, a nonlinearity, and an up-projection: (Adapter) where is the hidden representation, projects to a low-rank bottleneck of dimension , and projects back. The residual connection ensures that the adapter starts as an identity function (when is initialised to zero), preserving SAM's pre-trained features at the beginning of training.
Adapter placement.
Med-SA places adapters at two locations within each transformer block:
After the multi-head self-attention (MHSA) layer. This adapter modifies the spatial relationships captured by attention, allowing the model to attend to medical-image-specific patterns (e.g., organ boundaries that are invisible in natural images).
After the feed-forward network (FFN) layer. This adapter modifies the per-token feature transformations, enabling the model to recognise medical-image-specific textures and intensity patterns.
With and (SAM ViT-H dimensions), each adapter adds parameters. With two adapters per transformer block and 32 blocks, the total adapter parameter count is M, which is only 1.7% of SAM's total parameter count.
Comparison with full fine-tuning.
On the Synapse multi-organ benchmark, Med-SA achieves 97.2% of the Dice score of full fine-tuning (MedSAM) while training only 1.7% of the parameters. The gap is largest for the most challenging organs (pancreas: 2.1% lower Dice than MedSAM) and smallest for easy organs (liver: 0.3% lower). The parameter-efficient approach has a practical advantage: multiple Med-SA adapters (one per imaging modality or clinical task) can be stored and swapped while sharing a single frozen SAM backbone, reducing storage requirements by an order of magnitude compared to maintaining separate fine-tuned models.
Prompt Engineering for Medical SAM
The performance of SAM and its medical variants depends critically on how the user provides prompts. This subsection addresses three practical prompting strategies that have been shown to significantly affect segmentation quality in medical applications.
Bidirectional vs. unidirectional propagation.
When using SAM 2 for 3D volumes, the user prompts a single slice, and the model propagates the segmentation in one or both directions. Unidirectional propagation (from the prompted slice towards one end of the volume) accumulates errors: each slice's segmentation is conditioned on the previous slice's prediction, and small errors compound across many slices. Bidirectional propagation (from the prompted slice towards both ends of the volume simultaneously) reduces this error accumulation by halving the maximum propagation distance.
Empirically, bidirectional propagation improves average Dice by 3–5 percentage points over unidirectional propagation, with the improvement increasing for longer volumes (more slices). For a volume with slices and a prompt on slice , the maximum propagation distance is for unidirectional and for bidirectional (when the prompt is on the central slice). The error accumulation follows approximately (Propagation Error) where is the propagation distance (in slices), is the per-slice error rate, and is an empirical exponent. Bidirectional propagation from the optimal central slice minimises , compared to for the worst-case unidirectional propagation.
Optimal initial slice selection.
Not all slices are equally informative as starting points. The optimal initial slice is the one where the target organ has its largest cross-sectional area, for three reasons:
The organ is most clearly visible and distinguishable from surrounding structures.
A bounding box prompt on the largest cross-section provides the strongest spatial constraint.
Bidirectional propagation from the centre of the organ's extent ensures that the organ is fully covered in both directions.
In practice, this corresponds to the slice approximately at the organ's centroid in the -direction. For the liver, this is typically 2–3,cm below the dome of the diaphragm; for the kidneys, this is near the renal hilum.
The negative prompt paradox.
One of the most counterintuitive findings in medical SAM prompting concerns negative prompts. In the original SAM, negative point prompts are used to exclude background regions from the segmentation, and they generally improve results on natural images. However, for small organs in medical images, removing negative prompts entirely can improve segmentation quality.
Insight.
Removing negative prompts can paradoxically improve small organ segmentation with SAM. The mechanism is as follows: for small organs (e.g., the adrenal glands, the pancreas), the bounding box prompt already tightly constrains the segmentation region. Adding negative prompts within the box-intended to exclude background voxels-can inadvertently exclude foreground voxels near the organ boundary, because SAM's point-level spatial resolution is limited by its patch size. A negative prompt placed 5,mm from the organ boundary may fall within a patch that overlaps the organ, causing the model to suppress the organ's own boundary pixels. For organs where the bounding box is tight and the organ fills most of the box, the negative prompts are redundant at best and harmful at worst. This paradox does not occur for large organs where the bounding box contains substantial background area and negative prompts provide genuinely useful exclusion information.
The magnitude of this effect is nontrivial. For pancreas segmentation, removing negative prompts improved Dice by an average of 3.1 percentage points. For adrenal glands, the improvement was 4.7 points. For the liver (a large organ), removing negative prompts decreased Dice by 1.8 points, consistent with the explanation above. This finding has important practical implications: prompt strategies should be organ-size-aware, with negative prompts used selectively rather than uniformly.
Let be the organ area in the prompted slice and be the bounding box area. The box fill ratio predicts whether negative prompts help or hurt: (Negprompt) This threshold can be estimated from the bounding box annotation alone, without requiring the ground-truth segmentation, making it applicable in a fully interactive setting.
SegVol: 3D Foundation Segmentation
While the “-as-time” approach adapts a 2D model to 3D data through clever inference-time engineering, SegVol (Du et al., 2024) takes the more direct approach of building a 3D foundation model from scratch. SegVol processes entire 3D volumes natively, with a 3D image encoder, 3D prompt encoder, and 3D mask decoder.
Architecture.
SegVol adapts the SAM architecture to 3D:
3D image encoder. A 3D Vision Transformer processes the input volume (where is the depth/number of slices) by dividing it into 3D patches of size and embedding each patch as a token. The encoder produces a 3D feature volume .
Zoom-in mechanism. To handle the computational cost of processing full 3D volumes at high resolution, SegVol employs a two-stage “zoom-in” strategy: (1) the full volume is processed at low resolution to identify the region of interest, and (2) the identified region is cropped and processed at full resolution for precise segmentation.
Multi-modal prompts. SegVol supports point prompts (in 3D), bounding box prompts (3D cuboids), and text prompts, all encoded through appropriate 3D prompt encoders.
Training data.
SegVol is trained on 90K CT volumes with over 6,000 segmentation classes, assembled from 200+ public datasets. The sheer diversity of training targets-from large organs to small vessels, from tumours to surgical instruments-is designed to endow the model with a comprehensive understanding of 3D medical anatomy.
Text-prompted volumetric segmentation.
A distinctive feature of SegVol is its support for text-prompted segmentation in 3D. A clinician can type “segment the left kidney” and receive a full 3D segmentation without any geometric interaction. This is achieved by training the text encoder jointly with the segmentation model on anatomical text labels, enabling the model to map anatomical terms to spatial locations within the volume.
SegVol represents a different philosophy from the SAM 2 -as-time approach: rather than adapting a 2D model through inference-time tricks, it builds native 3D understanding into the model architecture and training. The trade-off is computational: SegVol's 3D encoder is significantly more expensive than SAM's 2D encoder, requiring specialised GPU hardware for inference on full-resolution clinical volumes. However, the native 3D approach avoids the error-accumulation problem of slice-by-slice propagation and can capture 3D spatial relationships (e.g., the relative positions of the aorta, inferior vena cava, and vertebral body) that are invisible to any 2D method.
The zoom-in mechanism in detail.
The zoom-in strategy addresses a fundamental memory bottleneck. A typical abdominal CT volume at full resolution has dimensions , which, when divided into patches, produces approximately 19,200 tokens-far too many for standard self-attention. The zoom-in mechanism proceeds in two phases:
Coarse localisation. The volume is downsampled by a factor of 4 in each spatial dimension, producing a manageable input. The 3D encoder processes this coarse volume and the prompt encoder converts the user's text or geometric prompt into tokens. The decoder produces a coarse mask that identifies the approximate location and extent of the target structure.
Fine segmentation. The coarse mask is used to crop a region of interest from the original full-resolution volume, with a margin of 20 voxels on each side. This cropped region is processed through the 3D encoder at full resolution, producing the final high-resolution segmentation mask.
The zoom-in mechanism reduces peak memory usage by approximately compared to processing the full volume at native resolution, making SegVol deployable on GPUs with 24,GB of memory for most clinical volumes.
Comparison with slice-by-slice methods.
On the TotalSegmentator benchmark (104 anatomical structures), SegVol achieves an average Dice of 82.3%, compared to 74.1% for SAM 2 with bidirectional propagation and 68.4% for slice-by-slice MedSAM. The advantage of native 3D processing is most pronounced for structures with complex 3D morphology: the portal vein (SegVol: 71.2% vs. SAM 2: 48.7%), the pancreatic duct (SegVol: 55.3% vs. SAM 2: 22.3%), and the oesophagus (SegVol: 76.8% vs. SAM 2: 61.4%). For large, simple organs like the liver, the difference is smaller (SegVol: 95.1% vs. SAM 2: 91.3%), confirming that 3D reasoning provides the greatest benefit for geometrically complex structures.
The foundation model landscape.
The SAM ecosystem for medical image segmentation can be organised along two axes: the degree of architectural modification (from zero-shot SAM to fully redesigned models like SegVol) and the degree of domain adaptation (from no adaptation to full fine-tuning on millions of medical images). The optimal choice depends on the specific clinical application:
For quick prototyping on high-contrast structures, zero-shot SAM with box prompts may suffice.
For interactive clinical workflows, SAM 2 with bidirectional propagation and organ-aware prompt engineering offers a good balance of accuracy and usability.
For production deployments requiring reliable multi-organ segmentation, fine-tuned models (MedSAM, H-SAM) or native 3D models (SegVol) are preferred.
For resource-constrained settings where multiple tasks must share a single backbone, parameter-efficient adaptation via Med-SA offers the best storage-accuracy trade-off.
The rapid pace of development in this space, with major new models appearing every few months, suggests that the landscape will continue to evolve. The general trend is toward models that combine SAM's universal prompting interface with the domain-specific knowledge needed for reliable medical segmentation, bridging the gap between general-purpose vision and the demanding requirements of clinical practice.
Exercise 20.
Consider a 3D abdominal CT volume with slices containing the liver and pancreas. You have access to SAM 2 with bidirectional propagation and a single bounding box prompt per organ.
- (a)
The liver's largest cross-section is at slice and the pancreas's largest cross-section is at slice . Using the error model with (liver) and (pancreas), compute the maximum propagation error for each organ under bidirectional propagation. Compare to the unidirectional case where propagation starts from slice 1.
- (b)
The liver has a box fill ratio and the pancreas has . Based on (Negprompt), should you use negative prompts for each organ? Explain the reasoning in terms of the patch size–organ boundary interaction.
- (c)
Suppose you can prompt on two slices per organ instead of one. Propose a strategy for selecting the two slices that minimises the maximum propagation distance, and derive the resulting maximum error as a function of the organ's -extent.
Exercise 21.
H-SAM uses a two-stage architecture where Stage 2 has a mask-guided cross-attention mechanism ((Maskcross)).
- (a)
Suppose the prior mask from Stage 1 has a Dice score of 0.72 with respect to the ground truth for a pancreas segmentation. The mask attention map assigns weight 3.0 to boundary pixels and weight 0.5 to interior and exterior pixels. Compute the effective attention ratio between boundary and non-boundary regions. Why is this upweighting beneficial for refinement?
- (b)
Med-SA uses adapter modules with bottleneck dimension and hidden dimension . Compute the exact parameter count for adapters placed after both MHSA and FFN in all 32 transformer blocks of ViT-H. Express this as a percentage of SAM's total parameters (632M). How does this compare to the parameter count of the full mask decoder (4M)?
- (c)
Discuss the trade-offs between H-SAM (which adds a second decoder stage) and Med-SA (which adds adapters to the image encoder). Under what conditions would you prefer one approach over the other?
Exercise 22.
Using the log-linear model from Proposition 6, with , , and :
- (a)
Predict the zero-shot SAM Dice score for the following organs: (i) liver (,cm, ,HU), (ii) kidney (,cm, ,HU), (iii) pancreas (,cm, ,HU), and (iv) aorta (,cm, ,HU).
- (b)
Which organ has the most favourable combination of volume and contrast? Which has the least favourable? Do the model's predictions match your clinical intuition?
- (c)
The model predicts the same Dice for two organs with and when . Derive the iso-Dice curve in the plane and plot it for Dice . Interpret this curve: for a given target Dice, how much additional contrast compensates for a halving of volume?
- (d)
The residual term captures shape complexity. Propose a quantitative measure of shape complexity (e.g., based on surface-to-volume ratio, fractal dimension, or convexity) and explain why it should appear in the residual rather than the main model.
Cell Segmentation Methods
Cells are the fundamental unit of life, yet they are among the most difficult structures to segment in biomedical imaging. Unlike organs, which occupy well-defined anatomical positions and exhibit stable morphology across individuals, cells present a combinatorial explosion of challenges: they cluster in dense colonies where boundaries blur, they divide and migrate over time, they deform under mechanical stress, and their optical appearance depends on the imaging modality-bright against a dark background in fluorescence, nearly invisible in phase-contrast, and somewhere in between in histological stains.
The semantic segmentation methods we developed in earlier sections are insufficient here. Semantic segmentation assigns each pixel a class label but cannot distinguish individual cells when hundreds of them tile the field of view. What we need is instance segmentation: every pixel must receive both a class label (cell vs. background) and an instance identifier that uniquely associates it with one particular cell. When cells touch-as they almost always do in confluent cultures-the boundary between two instances may be a single pixel wide, demanding sub-pixel precision from the model.
The difficulty is compounded by the sheer diversity of cell types. A round lymphocyte in suspension bears little resemblance to a branching neuron in culture, yet both are “cells.” Epithelial cells in tissue form tight sheets with shared boundaries; mesenchymal cells in 3D gels extend long, thin protrusions that can be confused with imaging artefacts. Red blood cells are uniform and convex; macrophages are amoeboid and constantly changing shape. Any method that hopes to be general must handle this morphological diversity without task-specific engineering.
Key Idea.
Cell tracking = segmentation + temporal association + lineage reconstruction. The complete cell analysis pipeline consists of three stages: (1) segment individual cells in each frame, (2) associate detected cells across consecutive frames to form tracks, and (3) reconstruct lineage trees by detecting division events and assigning mother–daughter relationships. Each stage introduces its own error modes, and errors propagate downstream: a missed segmentation becomes a broken track, and a broken track corrupts the entire lineage. The methods in this section address stage (1); Cell Tracking tackles stages (2) and (3).
The Cell Segmentation Challenge
The community has invested heavily in standardised benchmarks. The Cell Tracking Challenge (CTC), hosted since 2013 and published in Nature Methods (2023), provides over twenty 2D and 3D time-lapse datasets spanning diverse cell types, imaging modalities, and levels of cell density. Each dataset comes with expert-annotated ground truth for both segmentation and tracking. Two primary metrics measure performance:
Definition 26 (Segmentation Accuracy - SEG Metric).
Let be the set of ground-truth cell masks and the set of predicted masks. For each ground-truth mask , let be the predicted mask with maximal Jaccard overlap: (SEG Metric) The SEG metric is the average Jaccard index over all ground-truth instances: (SEG Value) A score of indicates perfect overlap for every cell; indicates no overlap. Note that may map multiple ground-truth masks to the same prediction if cells are under-segmented, which correctly penalises merging errors.
Definition 27 (Tracking Accuracy - TRA Metric).
Let be the ground-truth tracking graph, where vertices represent cell detections across all frames and edges encode temporal links (including parent–child edges for divisions). Let be the predicted tracking graph. The tracking accuracy is defined as (TRA Metric) where ranges over all sequences of graph-edit operations (insertions, deletions, splits, merges) that transform into , each operation type has weight , and counts the number of operations of type . This is the normalised acyclic oriented graph matching (AOGM) distance. A score of indicates a perfect tracking graph.
Remark 24.
The combined Cell Tracking Challenge score is the geometric mean , reflecting the equal importance of spatial accuracy (segmentation) and temporal accuracy (tracking). Methods that excel at one but fail at the other receive a deservedly low combined score.
Beyond the CTC, several other benchmarks have emerged. The Data Science Bowl 2018 (DSB-2018) provided a large and diverse collection of nuclei images, catalysing interest in generalist cell segmentation. The LIVECell dataset offers over 1.6 million annotated cells from label-free phase-contrast microscopy. TissueNet provides paired whole-cell and nuclear annotations across multiple tissue types. These benchmarks share a common theme: scale and diversity are essential for evaluating generalist methods.
Cellpose: Gradient Flow Representation
The central insight of Cellpose (Stringer et al., 2021) is a representation that decouples what belongs to a cell from which cell it belongs to. Rather than predicting instance masks directly-which requires the network to output a variable number of channels, one per instance-Cellpose predicts smooth gradient flow fields that point every pixel toward the centroid of its parent cell.
Formally, let be the image domain and let be the set of cell regions with centroids . Cellpose defines two flow fields, horizontal and vertical: (Cellpose Flows) where is a smooth potential whose gradient points from every pixel in cell toward its centroid . In practice, is constructed by solving a diffusion equation on the cell mask: (Cellpose Diffusion) The resulting gradient is a smooth vector field that converges to from every point inside the cell.
At inference, the network predicts three outputs: the horizontal flow , the vertical flow , and a cell-probability map . Instance masks are recovered by gradient tracking: starting from every pixel with , follow the predicted flow for steps using Euler integration: (Cellpose Euler) Pixels that converge to the same fixed point are assigned to the same instance. Convergence is guaranteed for sufficiently smooth flows because the Laplacian potential has a unique maximum at the centroid.
The elegance of this representation lies in its generality. The flow fields are defined purely by cell geometry-the shape of the mask and the location of the centroid-and are independent of cell appearance, imaging modality, or magnification. A network trained on fluorescence images of neurons can generalise to phase-contrast images of bacteria, because both cell types induce the same kind of smooth, convergent flow field despite looking entirely different in pixel space.
The Cellpose architecture uses a modified U-Net with a residual backbone. The network predicts three channels: horizontal flow, vertical flow, and cell probability. Training uses a combination of mean squared error for the flow fields and binary cross-entropy for the cell probability: (Cellpose LOSS) where and are the ground-truth flows and cell mask, respectively.
Cellpose 2 (Pachitariu and Stringer, 2022) extended the original with human-in-the-loop training, allowing users to correct segmentations and retrain the model on their specific cell type. Cellpose 3 (2024) introduced a one-click fine-tuning interface and improved the generalist model with training on over 100,000 manually curated images.
StarDist: Star-Convex Polygons
StarDist (Schmidt et al., 2018) takes a complementary approach to instance segmentation. Rather than predicting flow fields, StarDist directly predicts the shape of each cell as a star-convex polygon centred at every pixel.
A polygon is star-convex with respect to a point if every ray emanating from intersects the polygon boundary exactly once. This is a weaker condition than convexity: star-convex polygons can have mild concavities, as long as the centre has line of sight to every boundary point.
Formally, for each pixel in the image, StarDist predicts:
An object probability indicating whether is inside a cell.
A vector of radial distances , where is the predicted distance from to the cell boundary along direction .
The polygon vertices are then (Stardist Vertices) Pixels with are candidate centres, each proposing a polygon. Non-maximum suppression (NMS) removes redundant proposals, retaining the polygon with highest probability when two proposals overlap beyond a Jaccard threshold.
The StarDist loss combines a classification term and a regression term: (Stardist LOSS)
StarDist works particularly well for cells that are approximately convex-round nuclei, spherical yeast, compact lymphocytes. For cells with complex protrusions (neurons, astrocytes), the star-convex assumption breaks down, and methods like Cellpose that make no shape assumptions are preferred. StarDist 3D extends the approach to volumetric data by replacing 2D polygons with 3D star-convex polyhedra defined by radial distances on a tessellation of the unit sphere.
SAMmuSAM: Segment Anything for Microscopy
The Segment Anything Model (SAM) demonstrated that a vision transformer trained on a billion masks can segment virtually any object from a single prompt-a click, a bounding box, or a text description. But SAM was trained predominantly on natural images: photographs of people, animals, cars, and buildings. When applied to microscopy images without adaptation, SAM struggles with the unique visual characteristics of cells: low contrast, dense packing, and unfamiliar textures.
SAM (Archit et al., Nature Methods, 2025) addresses this gap by fine-tuning SAM specifically for microscopy. The key contributions are:
Microscopy-specific pre-training. The SAM image encoder (a ViT-Huge) is fine-tuned on a curated collection of microscopy images spanning fluorescence, electron, and light microscopy. This adapts the learned features from natural-image statistics to microscopy-image statistics: replacing sensitivity to textures and colours with sensitivity to membrane boundaries and intensity gradients.
Interactive segmentation tools. SAM integrates with napari, the popular Python-based image viewer for microscopy. Users can segment cells with point clicks, refine boundaries with additional prompts, and propagate segmentations through time-lapse sequences using SAM's mask decoder in a tracking-by-propagation loop.
Automatic instance segmentation. An automatic mask generator (AMG) tiles the image with a grid of point prompts, collects all predicted masks, and resolves overlaps through confidence-weighted NMS. This converts the interactive SAM into a fully automatic instance segmenter, competitive with Cellpose on many benchmarks.
Specialised model zoo. Pre-trained models are provided for specific modalities: light microscopy (LM), electron microscopy (EM), and whole-slide histopathology. Users can further fine-tune on their own data with as few as five annotated images.
Example 20 (SAM for 3D Embryo Development Tracking).
Consider tracking cells in a developing C. elegans embryo imaged by light-sheet microscopy at -minute intervals over 8 hours, producing a 4D dataset (3D time) with approximately 600 cells at the final time point. Traditional segmentation methods require retraining for each imaging condition. With SAM:
The user annotates 5 cells in the first 3D volume using point clicks in the napari plugin.
SAM fine-tunes the decoder on these annotations in approximately 2 minutes on a single GPU.
The automatic mask generator segments all cells in each volume (approximately 30 seconds per volume).
The tracking-by-propagation module links cells across time by using the mask from frame as a prompt for frame .
The resulting 4D tracks achieve and , comparable to methods specifically designed for embryo tracking but requiring orders of magnitude less manual annotation. The interactive refinement loop allows biologists to correct the 5–10% of errors that matter most for their analysis.
Cellpose-SAM: Beyond Human Agreement
A natural question arises: can we combine the strengths of Cellpose (flow-based instance recovery, generalist training) with the strengths of SAM (massive pre-training, flexible prompting)? Cellpose-SAM answers affirmatively.
The key observation is that the SAM backbone provides rich feature representations trained on far more data than any microscopy-specific model. By replacing the Cellpose encoder with a frozen SAM image encoder and training only a lightweight flow-prediction head, one inherits SAM's representational power while retaining Cellpose's gradient-flow decoding strategy.
The architecture is straightforward: the SAM ViT-Huge encoder processes the input image and produces a spatial feature map. A lightweight decoder head (three convolutional layers with skip connections from intermediate encoder layers) predicts the horizontal flow, vertical flow, and cell probability channels. The SAM encoder weights are frozen during training, and only the decoder head is optimised. This reduces the trainable parameter count from 600M to 5M, making training feasible on a single GPU with modest microscopy datasets.
The resulting model achieves segmentation accuracy that approaches the human-consensus bound-the inter-annotator agreement among expert biologists. On the Cellpose evaluation set, Cellpose-SAM achieves an average precision (AP) at IoU of 0.93, while the average inter-annotator AP among trained biologists is 0.95. This 2-percentage-point gap represents the residual difficulty of cells where even experts disagree: ambiguous boundaries in dense clusters, cells partially out of the focal plane, and mitotic cells whose boundaries are transiently disrupted.
Remark 25.
Approaching the human-consensus bound does not mean the problem is solved. It means that further improvements require either better ground truth (consensus annotations from many experts) or a redefinition of the task (e.g., probabilistic segmentation that represents boundary uncertainty). The bound itself is a moving target: as annotation tools improve, human agreement increases.
CellSAM: Foundation Model for Cell Segmentation
CellSAM (Israel et al., 2024) takes a different approach to combining detection and segmentation. Rather than replacing the SAM encoder, CellSAM adds a detection module-CellFinder-that automatically generates the prompts SAM needs.
The pipeline has two stages:
CellFinder: detection. A DETR-style transformer detector processes the image and outputs a set of bounding boxes , each containing one cell. CellFinder is trained on a diverse collection of microscopy images and learns to detect cells regardless of their appearance or density.
SAM: segmentation. Each bounding box is fed to SAM as a box prompt. SAM's mask decoder produces a high-quality segmentation mask for the cell within the box. Because SAM was designed for box-prompted segmentation, this is the use case where it excels.
The detection-to-prompt pipeline has a compelling advantage: it completely decouples the “where are the cells?” question (answered by CellFinder) from the “what shape is this cell?” question (answered by SAM). This modularity means that improvements to either component translate directly to improvements in the full pipeline.
The training procedure is also modular. CellFinder is trained with a standard detection loss (a combination of classification loss for “cell vs. background” and regression loss for bounding box coordinates), while SAM's mask decoder is used without modification. At inference, the two stages run sequentially: CellFinder processes the full image once to produce all bounding boxes, then SAM processes each box independently. The computational cost scales linearly with the number of detected cells, making CellSAM efficient even for images with hundreds of cells.
CellSAM achieves state-of-the-art performance across multiple benchmarks, including TissueNet, LIVECell, and the Data Science Bowl, without any fine-tuning on the target domain. The detection stage is the bottleneck: when cells are extremely dense (more than 500 per field of view), CellFinder occasionally misses cells or merges adjacent bounding boxes. But for moderate densities, the detection-then-segment strategy is remarkably robust.
Cell Tracking
Segmenting cells in a single frame is only the first step. In most biological experiments, the quantity of interest is not where cells are at one moment but how they behave over time: how fast they migrate, how often they divide, how they respond to drugs, and how their lineage unfolds across generations. These questions demand cell tracking-the temporal linking of segmented cells across frames to form continuous trajectories.
Cell tracking is one of the oldest problems in bioimage informatics, yet it remains unsolved in the general case. The reason is a combinatorial explosion: with cells in frame and cells in frame , there are possible associations, and the correct one depends on information that may not be available in the image-cells may look identical, move unpredictably, enter or leave the field of view, or divide into daughter cells.
Definition 28 (Cell Tracking).
Let be a time-lapse image sequence and let be the set of cell detections (positions or segmentation masks) in frame . A cell tracking is a mapping that assigns to each detection at most one detection in the next frame, subject to the constraints:
Uniqueness: Each detection in frame is assigned to at most one detection in frame (no merging of distinct cells).
Division: A detection may be assigned to exactly two detections in frame if cell undergoes mitosis.
Appearance/disappearance: Unassigned detections in frame correspond to cells leaving the field of view (or dying); unassigned detections in frame correspond to cells entering the field of view (or being born from a division event elsewhere).
The full tracking result is the collection , which defines a directed acyclic graph (tracking graph) whose connected components are cell tracks, potentially branching at division events to form lineage trees.
The Cell Tracking Challenge
Historical Note.
The Cell Tracking Challenge: a decade of community benchmarking (2013–2025). The Cell Tracking Challenge (CTC) began in 2013 as a modest competition at the IEEE International Symposium on Biomedical Imaging (ISBI), with six datasets and a handful of participating teams. By 2017, it had grown to include 14 datasets spanning 2D and 3D time-lapse sequences of diverse cell types: epithelial cells, muscle stem cells, developing embryos, and migrating cancer cells.
The landmark 2023 Nature Methods publication surveyed ten years of submissions and revealed striking trends. Deep learning methods, first appearing in 2016, had by 2019 displaced all classical approaches on the leaderboard. The top methods achieved on datasets with well-separated, slowly moving cells-essentially solving those instances. But on dense, rapidly dividing populations (such as the Fluo-N2DH-SIM+ dataset of simulated nuclei), the best methods still achieved only , revealing that dense-population tracking remains an open problem.
The challenge evolved its metrics over time. The original SEG and TRA metrics were supplemented with DET (detection accuracy, measuring the fraction of cells correctly detected regardless of segmentation quality) and the combined score. In 2024, a “methods robustness” track was introduced, evaluating how well methods generalise from one dataset to another without retraining-a direct response to the observation that many top-performing methods were heavily overfitted to specific datasets.
The CTC remains the definitive benchmark for cell tracking, with active submissions from over 50 groups worldwide and an online leaderboard updated quarterly. Its greatest legacy may be the standardised data format and evaluation code, which have become the de facto standard for cell tracking evaluation in the field.
The CTC datasets are carefully chosen to span the space of biological and imaging variability:
2D fluorescence: GFP-labelled HeLa cells (Fluo-N2DL-HeLa), GFP-labelled muscle stem cells (Fluo-N2DH-GOWT1), simulated nuclei (Fluo-N2DH-SIM+).
3D fluorescence: Developing C. elegans embryos (Fluo-N3DH-CE), Drosophila wing disc (Fluo-N3DH-CHO).
Phase contrast: U373 glioblastoma cells (PhC-C2DL-PSC), Pancreatic stem cells (PhC-C2DH-U373).
Differential interference contrast (DIC): HeLa cells on polyacrylamide substrates (DIC-C2DH-HeLa).
Bright-field: Mouse embryonic stem cells (BF-C2DL-MuSC).
Each dataset has a “silver truth” annotation created by fusing multiple expert annotations. The silver truth is more reliable than any single annotation and provides a fair evaluation target that accounts for inter-annotator variability. The CTC also provides a gold corpus (GT) for a subset of datasets where annotations have been exhaustively verified, serving as the definitive ground truth for method comparison.
Tracking-by-Detection vs Tracking-by-Segmentation
Two fundamental paradigms structure the cell tracking literature:
Tracking-by-detection.
First, detect (or segment) cells independently in each frame. Then, solve an association problem to link detections across frames. This is the dominant paradigm, used by most CTC-winning methods. Its advantage is modularity: any improvement to the detector immediately improves tracking, and the association step can leverage temporal information that the per-frame detector cannot access. Its disadvantage is that errors in the detection stage propagate to tracking: a missed detection creates a gap in the track, and a false merge creates a spurious association.
Tracking-by-segmentation.
Use the segmentation from frame as a prior for frame . Concretely, propagate the mask from to (using optical flow, a learned warping, or a mask-conditioned segmentation model), refine it using image evidence at , and iterate. This paradigm is natural for SAM-style models, which accept a mask prompt: the mask from serves as the prompt for . Its advantage is temporal consistency-the mask evolves smoothly rather than being reconstructed from scratch in each frame. Its disadvantage is drift: small errors accumulate over time, and the model has no mechanism to recover from a badly propagated mask.
Caution.
Tracking errors cascade: one wrong association corrupts an entire lineage. Consider a single identity swap at frame : cell is assigned cell 's identity, and vice versa. Every subsequent frame inherits this error. If cell later divides, its daughters are now incorrectly attributed to cell 's lineage. Any quantitative analysis-migration speed, division rate, drug response-computed from the corrupted lineage is wrong. Unlike segmentation errors, which are localised in space and time, tracking errors propagate forward in time and downward through lineage trees. The practical consequence is that tracking systems must either be extremely accurate (sub-percent error rates) or provide efficient tools for human verification and correction.
Association Methods
Given detections and in consecutive frames, the association problem is to find the optimal mapping that links each cell to its successor (or to if the cell disappears).
Definition 29 (Lineage Tree).
A lineage tree is a rooted directed tree where:
Each vertex represents a cell detection at a specific time point, labelled .
Each edge with represents a temporal link (the cell persisted from frame to ).
A vertex with two children (both at time ) represents a mitosis event: cell divided into daughter cells and .
The root of is the first detection of the founding cell of the lineage.
A complete tracking result partitions all detections into a forest of lineage trees, one per founding cell.
Definition 30 (Mitosis Event).
A mitosis event at time is a triple where the mother cell divides into two daughter cells and . In the lineage tree, this corresponds to a vertex with out-degree 2. Formally, for a mitosis event to be valid:
The mother cell must exist at time : .
Both daughters must exist at time : .
The daughters must be spatially close to the mother: and .
The mother cell must not appear at time (it has been replaced by its daughters).
Proposition 7 (Optimal Assignment as Bipartite Matching).
Consider the assignment problem between detections and . Define a cost matrix where: (COST Matrix) with the cost of linking detection at time to detection at time (e.g., Euclidean distance between centroids, or negative IoU between masks), and the costs of track termination and initiation, respectively. The augmented rows and columns represent dummy detections for appearance and disappearance.
Then the optimal one-to-one assignment over all permutations of can be computed in time using the Hungarian algorithm.
Proof.
The cost matrix is square (by augmentation) with non-negative entries. The assignment problem is a special case of minimum-weight bipartite matching, which is solved exactly by the Hungarian algorithm (Kuhn, 1955; Munkres, 1957). The complexity follows from the algorithm's iterative construction of augmenting paths. The augmentation with dummy rows and columns ensures that every detection has a valid assignment (either to a real detection or to a dummy), correctly modelling appearance and disappearance without requiring the number of detections to be equal across frames.
In practice, the cost function can be much richer than Euclidean distance. Modern methods use learned embeddings: each detection is mapped to a vector , and the cost is the embedding distance . The encoder is trained with a contrastive loss to produce similar embeddings for the same cell across frames and dissimilar embeddings for different cells.
Graph neural networks for association.
Recent methods replace hand-crafted cost functions with graph neural networks (GNNs). A graph is constructed with detections as nodes and candidate associations as edges. Node features encode appearance and position; edge features encode spatial displacement and temporal gap. The GNN applies message passing to propagate information between neighbouring detections, then classifies each edge as “active” (part of a track) or “inactive.” The advantage over frame-by-frame bipartite matching is that the GNN can reason about multi-frame context: it can, for instance, learn that a cell temporarily occluded at frame reappears at frame with consistent appearance, enabling gap closing without explicit heuristics.
Tracking graphs.
For longer-range associations (bridging gaps where a cell is temporarily undetected), the frame-by-frame bipartite matching can be extended to a global optimisation over a tracking graph. The tracking graph has a vertex for each detection across all frames and edges connecting potentially matching detections within a temporal window. The optimal tracking is a minimum-cost flow or integer linear programme on , which can be solved efficiently using network simplex or relaxation methods.
CytoTracker: Diffusion-Guided Cell Association
CytoTracker (MIDL 2026) introduces a fundamentally different approach to cell association: rather than computing costs based on static features, it uses a diffusion model to predict where cells will move, then uses these predictions to guide association.
The architecture has three components:
CytoEmbedding: attention-based feature fusion.
Each cell detection is represented by fusing appearance features (from a CNN or ViT applied to the image crop), positional features (centroid coordinates, bounding box), and contextual features (a cross-attention summary of neighbouring cells within a spatial radius). The fusion module uses multi-head cross-attention: (Cytoembedding) where is the query from cell 's appearance, are keys and values from neighbouring cells , and is a positional encoding. The cross-attention allows each cell's embedding to capture information about its local neighbourhood, which is crucial for disambiguation in dense clusters.
Diffusion-based motion predictor.
Given the embeddings at time , a conditional diffusion model predicts the displacement vectors that map each cell to its position at time . The diffusion model is conditioned on the CytoEmbeddings and trained to denoise displacement vectors: (Cytotracker Diffusion) where is the noised displacement at diffusion step and is the denoising network.
Insight.
Diffusion models can predict where cells will move, even when they look identical. In a confluent monolayer, neighbouring cells are visually indistinguishable-same morphology, same fluorescence intensity, same texture. Classical appearance-based matching fails in this regime. But the dynamics are not identical: cells at the wound edge migrate toward the gap, cells in the interior remain relatively stationary, and cells near a dividing neighbour are pushed aside. The diffusion-based motion predictor captures these context-dependent dynamics through the CytoEmbedding's neighbourhood attention, enabling accurate association even when appearance alone provides no signal.
Transformer association engine.
The predicted positions are compared with the actual detections using a transformer-based matcher. The matcher takes as input the predicted embeddings and actual embeddings at , applies cross-attention between the two sets, and outputs a soft assignment matrix: (Cytotracker Assignment) where collects the predicted embeddings and collects the actual embeddings. The soft assignment is discretised using the Sinkhorn algorithm to produce a doubly stochastic matrix, then rounded to a permutation.
A critical advantage of CytoTracker is that it requires no ground-truth segmentation masks at inference time. It operates on detections (bounding boxes or centroids), making it applicable even when high-quality segmentation is unavailable. The diffusion motion predictor provides a probabilistic forecast of cell positions, naturally handling the uncertainty inherent in biological motion.
Example 21 (CytoTracker on Mitosis-Heavy Time-Lapse).
Consider a 48-hour time-lapse of HeLa cells captured at 5-minute intervals (576 frames). HeLa cells divide approximately every 22 hours, so each founding cell produces 4–8 descendants by the end of the sequence. With 200 cells initially, the final frame contains 1200 cells, and there are 800 mitosis events.
The CytoTracker diffusion motion predictor learns that dividing cells round up (become spherical) approximately 30 minutes before cytokinesis, shift slightly, then split into two adjacent daughters. This morphological cue, captured through the CytoEmbedding's temporal context, allows the model to predict division events before they occur, pre-allocating two association slots in the transformer matcher.
On the Fluo-N2DL-HeLa dataset from the Cell Tracking Challenge, CytoTracker achieves and , improving over the previous state-of-the-art by 0.8 percentage points on TRA. The largest gains come from mitosis-rich regions where classical methods frequently swap daughter identities.
SAM2 for Zero-Shot Cell Tracking
SAM2 (Ravi et al., 2024) extended the Segment Anything Model to video, introducing a streaming memory mechanism that maintains a fixed-size buffer of recently processed frames and their mask predictions. This makes SAM2 a natural fit for cell tracking: given a segmentation in the first frame (provided interactively or automatically), SAM2 propagates it forward using the memory-conditioned mask decoder.
The sam4celltracking framework (2025) applies SAM2 to cell tracking in a fully unsupervised setting:
Initialisation. Run the SAM2 automatic mask generator on the first frame to detect all cells without any user prompts.
Propagation. For each detected cell, propagate the mask forward through subsequent frames using SAM2's streaming memory. The memory bank stores feature maps from the last frames, providing temporal context.
New cell detection. Periodically (every frames), run the automatic mask generator to detect cells that entered the field of view after initialisation.
Division handling. When a propagated mask suddenly covers two distinct connected components, register a division event and initialise two new tracks from the components.
The streaming memory is the key innovation. At each frame , SAM2's memory attention module attends to the stored features from frames : (SAM2 Memory) where is the query from the current frame's features and are keys and values stored in the memory bank. This provides temporal consistency without requiring the model to process all previous frames simultaneously.
On CTC datasets, sam4celltracking achieves competitive tracking performance ( on several datasets) despite requiring zero training on microscopy data. The method is particularly effective on datasets with clearly separated, slowly moving cells where SAM2's mask propagation can easily follow each instance. Performance degrades on dense populations and fast-moving cells, where the frame-to-frame displacement exceeds the receptive field of SAM2's mask decoder.
Remark 26.
The zero-shot nature of SAM2-based tracking is both its strength and its limitation. Because no microscopy-specific training is required, the method can be deployed instantly on any new cell type or imaging modality. However, the lack of domain adaptation means that SAM2's internal representation does not encode microscopy-specific priors: it does not know that cells are approximately convex, that they cannot teleport, or that they divide rather than merge. These priors, which are implicit in trained methods like Cellpose and CytoTracker, must be supplied externally through heuristic post-processing rules in the sam4celltracking framework.
The practical recommendation is to use SAM2 for rapid prototyping and for datasets where annotated training data is unavailable, then switch to a domain-adapted method when training data becomes available or when the highest possible accuracy is required.
Mitosis Detection and Lineage Tracking
Cell division is the most biologically important event in a cell tracking experiment, and the most difficult to detect computationally. A cell undergoing mitosis changes morphology dramatically over a span of 20–60 minutes: it rounds up, aligns its chromosomes, and splits into two daughter cells that initially overlap before separating. During the separation phase, the two daughters may be indistinguishable from a single elongated cell, creating a transient ambiguity that challenges both segmentation and tracking.
Mitosis detection approaches fall into three categories:
Morphology-based. Detect the characteristic rounding-up and splitting morphology using shape features (circularity, area change, aspect ratio). These methods are fast but fragile: not all cells round up visibly, and other events (cell death, imaging artefacts) can mimic the morphological signature.
Classification-based. Train a CNN or transformer to classify short temporal windows (3–7 frames) as “mitosis” or “non-mitosis.” The classifier receives either raw image patches or pre-extracted features. This approach is effective when sufficient annotated mitosis events are available for training.
Integrated tracking. Build mitosis detection directly into the tracking framework. At each frame, the tracker considers both continuation hypotheses (cell at becomes cell at ) and division hypotheses (cell at becomes cells and at ). The optimal hypothesis is selected by global optimisation over the tracking graph. This approach avoids the brittleness of separate detection by considering the full temporal context.
Lineage tracking extends single-generation tracking to multi-generational analysis. The goal is to reconstruct the complete family tree of each founding cell, recording when each division occurred, which daughter inherited which properties, and how the lineage diverges over time. This is essential for studying asymmetric cell division (where daughters inherit different fates), stem cell self-renewal (where one daughter remains a stem cell and the other differentiates), and clonal expansion in tumour biology.
Mathematically, lineage tracking augments the tracking graph with division edges. Let where contains temporal-link edges (one-to-one) and contains division edges (one-to-two). The optimal lineage is the minimum-cost subgraph of that covers all detections and satisfies the constraint that each detection has at most one incoming link edge and each mother has exactly two outgoing division edges. This is an integer linear programme that can be solved by relaxation or specialised solvers.
Synthetic Microscopy Video Generation
The bottleneck for cell tracking is not algorithmic but data-driven: annotating ground-truth tracks in dense, dividing populations is extraordinarily labour-intensive. A single 500-frame time-lapse with 200 cells requires approximately 100,000 individual annotations (one per cell per frame), plus careful identification of every mitosis event. At a cost of several seconds per annotation, this amounts to weeks of expert time per dataset.
Diffusion models offer a way to break this bottleneck by generating synthetic microscopy videos with perfect ground-truth annotations. The approach combines two components:
Physics-based simulation.
A biophysical model simulates cell motion, growth, and division. Cells are modelled as soft particles interacting via repulsive potentials (to prevent overlap), adhesive potentials (to model cell junctions), and stochastic forces (to model active migration). Division is triggered stochastically with rates drawn from measured cell-cycle distributions. The simulator outputs a sequence of cell masks and the ground-truth tracking graph-perfect annotations that are free by construction.
Diffusion-based image synthesis.
A conditional diffusion model transforms the simulated masks into realistic-looking microscopy images: (Synthetic Diffusion) where is a mask-conditioned diffusion model trained on paired real images and their annotations. The stochastic noise introduces realistic variability: different samples from the same mask produce images with different noise patterns, intensity fluctuations, and minor artefacts, mimicking the variability in real microscopy.
Flow-field conditioning.
To ensure temporal consistency (cells should look similar across consecutive frames), the diffusion model can be conditioned on optical flow fields derived from the simulated cell motion. This guides the image synthesis process to produce temporally coherent videos where cell appearance evolves smoothly rather than being re-synthesised independently in each frame.
The synthetic data is used for pre-training or data augmentation: models trained on a mixture of real and synthetic data consistently outperform those trained on real data alone, particularly on rare events (mitosis, cell death, cell–cell fusion) that are under-represented in real datasets.
The quality of synthetic data depends critically on the domain gap between synthetic and real images. Several strategies reduce this gap:
Style transfer at training time. Apply a CycleGAN or unpaired image translation model to map synthetic images into the style of a target real dataset, preserving cell layout while matching intensity statistics, noise characteristics, and optical aberrations.
Physics-informed rendering. Model the microscope point spread function (PSF), detector noise (Poisson photon noise plus Gaussian read noise), and illumination non-uniformity. These physics-based degradations produce more realistic images than purely learned generators when the imaging parameters are known.
Curriculum mixing. Begin training on synthetic data, then gradually increase the proportion of real data as training progresses. This curriculum ensures the model learns basic cell geometry from the abundant synthetic data before fine-tuning on the distribution shift present in real images.
On the Fluo-N2DH-SIM+ dataset of the Cell Tracking Challenge (which is itself synthetic), models pre-trained on diffusion-generated data and fine-tuned on the target domain achieve and , compared to and for models trained only on the (small) real training set. The 7-point improvement in SEG and TRA demonstrates that synthetic data generation is no longer merely a proof of concept but a practical tool for improving tracking performance.
Label-Free Tracking
The methods discussed so far assume that cells are visible-labelled with fluorescent markers that make them bright against a dark background. But fluorescent labelling has costs: it requires genetic modification or dye loading, it produces phototoxicity under prolonged imaging, and the fluorescent signal bleaches over time. For long-duration experiments (days to weeks), label-free imaging is essential.
Phase-contrast and differential interference contrast (DIC) microscopy produce images of unlabelled cells, where contrast arises from differences in optical path length rather than fluorescence. These images are much harder to segment: cells appear as subtle intensity variations with bright halos and dark cores (in phase contrast) or as 3D-relief features (in DIC). The boundaries between cells are ambiguous, and the background is not uniformly dark.
Example 22 (Tracking Immune Cells in Nanowells for Cancer Immunotherapy).
Nanowell arrays are microfluidic devices containing thousands of small wells (20–50 m diameter), each holding a small number of immune cells (typically 1–5 T cells) together with a target cancer cell. By imaging the array with phase-contrast microscopy over 12–24 hours, researchers can observe which T cells kill their targets, how long the killing takes, and whether the T cell goes on to kill additional targets (serial killing).
Label-free tracking in nanowells requires segmenting and tracking cells that are:
Nearly transparent (no fluorescent label).
In close proximity (well diameter is only 2–3 cell diameters).
Rapidly moving (T cells migrate at 5–15 m/min).
Morphologically dynamic (T cells deform during target engagement).
A Cellpose model fine-tuned on 50 annotated nanowell images achieves on phase-contrast data, compared to for the generalist Cellpose model and for classical thresholding. When combined with CytoTracker for temporal association, the pipeline achieves , enabling automated quantification of serial killing rates across thousands of T cell–target interactions in a single experiment.
The clinical application is direct: nanowell-based tracking is used to identify the most potent T cells from a patient's blood for adoptive cell therapy. Automated tracking replaces the manual review of microscopy videos, which previously required 2–3 human hours per nanowell plate.
Recent advances in label-free segmentation leverage the same foundation models discussed earlier. SAM includes light microscopy as a pre-training modality and achieves competitive performance on phase-contrast datasets. Virtual staining methods use generative models (typically cGANs or diffusion models) to predict what a phase-contrast image would look like if the cells were fluorescently labelled, then apply standard fluorescence-based segmentation to the virtual stain. This “predict-then-segment” pipeline is effective but adds a potential source of error: artefacts in the virtual stain can create phantom cells or erase real ones.
Quantitative phase imaging.
An emerging alternative to traditional label-free modalities is quantitative phase imaging (QPI), which measures the optical phase shift induced by the cell rather than just the intensity contrast. The phase shift is proportional to the product of the cell's refractive index and thickness, providing a quantitative measure of cell dry mass. QPI images have higher contrast than phase-contrast images, making segmentation easier, and the dry mass measurement provides a biophysically meaningful feature for tracking: cells increase their dry mass before division, providing a natural predictor of upcoming mitosis events.
Diffusion-based virtual staining models trained on paired QPI and fluorescence images can generate high-quality “virtual fluorescence” from QPI inputs, achieving a Pearson correlation of with real fluorescence on held-out samples. This enables the use of fluorescence-trained segmentation models on label-free data, effectively bridging the modality gap without any physical fluorescent labelling.
Exercise 23 (Cellpose Flow Field Computation).
Consider a circular cell of radius centred at the origin, so .
Write down the boundary conditions for the Cellpose potential : and for . Using the radial symmetry, show that the Laplace equation in 2D polar coordinates yields for (with the convention ).
Compute the gradient flow field and verify that it points radially inward toward the centroid at every interior point.
Now consider two circular cells of radius with centres at and , separated by a gap of width . Explain qualitatively why the gradient flows remain well-separated as long as but fail catastrophically when (cells touching). How does Cellpose handle this in practice?
Derive the Euler integration update ((Cellpose Euler)) and show that for a circular cell, the number of steps required for a boundary pixel to reach the centroid scales as .
Exercise 24 (Bipartite Matching for Cell Tracking).
A time-lapse sequence contains 3 cells at time with centroid positions , , , and 4 cells at time with positions , , , .
Compute the Euclidean distance matrix for all , .
Augment the cost matrix as in (COST Matrix) with . Write out the full matrix (padding with appropriate dummy rows/columns).
Solve the assignment problem by inspection or by applying the Hungarian algorithm. Which cell at is identified as a newly appearing cell?
Suppose cell 3 at time actually divided, producing cells 3 and 4 at (with instead of ). The standard bipartite matching cannot represent one-to-two assignments. Describe how you would modify the cost matrix to allow division hypotheses. Hint: Create a “virtual copy” of the mother cell.
Exercise 25 (Tracking Metric Sensitivity Analysis).
Consider a simple tracking scenario with 2 cells over 5 frames. Cell A is present in all frames; cell B appears at frame 3 (a new cell entering the field of view).
Draw the ground-truth tracking graph with 7 vertices (5 for cell A, 2 for cell B) and the appropriate edges.
Suppose the predicted tracking graph is identical to except that cell B is incorrectly linked to cell A at frame 3 (an identity swap). Compute the AOGM operations needed to transform into . How many operations are required?
Now suppose instead that cell B is missed entirely in the predicted graph (not detected in frames 3–5). How many AOGM operations are needed in this case?
Compare the TRA scores from parts (b) and (c). Which error is penalised more heavily: an identity swap or a complete miss? Discuss whether this aligns with biological priorities (where knowing which cell did what is often more important than detecting every cell).
Challenge 3 (Design a Cell Tracking Evaluation Metric).
The SEG and TRA metrics, while standard, have known limitations: SEG does not penalise false positive detections (extra predicted cells that do not correspond to any ground truth), and TRA uses uniform weights for different graph-edit operations that may not reflect biological importance.
Propose a new evaluation metric for cell tracking that addresses at least two of the following shortcomings: (i) SEG ignores false positives; (ii) TRA treats all identity swaps equally regardless of duration; (iii) neither metric directly evaluates lineage accuracy; (iv) both metrics are computed per-frame and do not capture long-range track coherence.
Formalise your metric mathematically, defining the inputs, the computation, and the range of values.
Compute your metric on a small example (at least 3 cells over 5 frames) with specific error patterns (e.g., one identity swap, one missed division).
Discuss the computational complexity of your metric. Can it be computed efficiently for large-scale tracking results (thousands of cells over hundreds of frames)?
Identify one potential failure mode of your metric: a scenario where it gives a misleadingly high or low score.
This exercise is suitable for a course project. A strong solution will compare the proposed metric against SEG and TRA on the Cell Tracking Challenge datasets, demonstrating cases where the new metric provides more informative evaluation.
Medical Vision-Language Models
For decades, segmentation algorithms have operated in a curious silence. They consume pixel arrays and produce label maps, never once asking what they are segmenting or why. A U-Net trained to delineate liver tumours has no concept of “liver” or “tumour”; it has merely learned a mapping from intensity patterns to binary masks. If asked to segment a different organ, it is helpless-not because it lacks computational power, but because it lacks language.
The emergence of vision-language models (VLMs) has fundamentally altered this landscape. By learning joint representations of images and text, VLMs enable segmentation systems that can interpret natural language instructions (“segment the hypointense lesion on the left lateral lobe”), reason about anatomical context (“this bright region is likely a cyst because of its location adjacent to the kidney”), and communicate uncertainty in human-readable terms (“the boundary between tumour and oedema is ambiguous in slices 42–47”). The transition from pixel-only to language-aware segmentation is not merely a technical upgrade; it represents a paradigmatic shift in how we conceive of the segmentation task itself.
Key Idea.
Language transforms segmentation from “where is the boundary?” to “what should I segment and why?” A purely visual segmentation model answers only the first question. A vision-language model can answer all three, enabling interactive, explainable, and context-aware segmentation that aligns with clinical reasoning.
This section develops the mathematical foundations and architectural principles of vision-language models as they apply to medical image segmentation. We begin with the motivation for incorporating language, then build up from contrastive pretraining (CLIP) through domain-specific adaptations (BiomedCLIP) to full multimodal reasoning systems (LLaVA-Med), and finally systematise the architectural design space into three canonical types.
Why Language Matters for Segmentation
Consider the instruction “segment the tumour.” To a human radiologist, this five-word sentence triggers a cascade of reasoning: What imaging modality am I looking at? What kind of tumour is expected given the clinical context? What are its typical appearance characteristics-hypo- or hyperintense, homogeneous or heterogeneous, well-circumscribed or infiltrating? Where in the anatomy is it most likely to appear? What structures might mimic it?
A conventional segmentation network receives none of this reasoning. It sees a matrix of pixel values and must produce a matrix of class labels. The “meaning” of the task is encoded entirely in the training labels, which are themselves silent. This creates several fundamental limitations:
Rigidity.
A network trained to segment liver tumours cannot segment kidney tumours without retraining. The task specification is baked into the training data, not communicated at inference time. In clinical practice, the desired segmentation target varies from case to case and from question to question. A radiologist reviewing a single CT scan might need to delineate the tumour, the surrounding vasculature, and the resection margin, each requiring a different “understanding” of what to segment.
Ambiguity.
Many segmentation tasks are inherently ambiguous without context. In a brain MRI, a bright region on a FLAIR sequence could be a tumour, oedema, demyelination, or an artefact. The correct label depends on clinical history, other sequences, and prior knowledge-information that is naturally expressed in language but inaccessible to a pixel-only model.
Explainability.
Clinicians do not trust black-box predictions. A segmentation model that can explain its reasoning (“I identified this region as tumour because it shows ring enhancement on post-contrast T1 and corresponding FLAIR hyperintensity”) is far more useful than one that silently produces a mask. Generating such explanations requires the model to operate in the space of language, not just pixels.
Rare conditions.
For rare pathologies with few training examples, purely visual models struggle. But a VLM can leverage textual descriptions of the condition (“a phaeochromocytoma typically appears as a well-defined, heterogeneously enhancing adrenal mass”) to guide segmentation even with minimal visual training data. This is the promise of zero-shot and few-shot segmentation: the model reads about what to look for, rather than being shown thousands of examples.
Remark 27.
In clinical practice, radiology reports accompany every imaging study. A typical report contains 100–500 words describing findings, impressions, and recommendations. This text is a rich source of supervision that traditional segmentation pipelines entirely ignore. Vision-language models can exploit this naturally occurring text as a training signal, turning millions of clinical reports into a form of “free” annotation that supplements or replaces expensive pixel-level labels.
CLIP and Contrastive Vision-Language Pretraining
The modern era of vision-language models began with CLIP (Contrastive Language–Image Pre-training), introduced by Radford et al. in 2021. CLIP demonstrated that a simple contrastive objective applied to 400 million image–text pairs scraped from the internet could produce visual representations that rival or exceed those learned by supervised training on ImageNet. More remarkably, these representations exhibited zero-shot transfer: the model could classify images into categories it had never seen during training, guided solely by natural language descriptions of those categories.
The architecture of CLIP is elegantly simple. Two separate encoders-an image encoder (typically a Vision Transformer or ResNet) and a text encoder (typically a Transformer)-map their respective inputs into a shared embedding space . The training objective pulls matched image–text pairs together and pushes unmatched pairs apart.
Definition 31 (Vision-Language Model for Medical Imaging).
A vision-language model (VLM) for medical imaging is a parameterised system consisting of:
An image encoder that maps a medical image (which may be 2D, 3D, or a video sequence) to a -dimensional visual embedding;
A text encoder that maps a natural language description (a radiology report, clinical prompt, or anatomical description) to the same -dimensional space;
A fusion mechanism that combines visual and textual embeddings to produce a task-specific output (a segmentation mask, classification label, or generated text).
The model is trained so that semantically corresponding images and texts are mapped to nearby points in , enabling cross-modal retrieval, zero-shot classification, and language-guided segmentation.
The training objective at the heart of CLIP is the InfoNCE loss, a contrastive objective that originated in the self-supervised learning literature and has since become ubiquitous in multimodal learning.
Definition 32 (Contrastive Learning Objective (InfoNCE)).
Given a batch of matched image–text pairs , let and denote the -normalised image and text embeddings, respectively. The InfoNCE loss is the symmetric cross-entropy (Infonce) where is a learnable temperature parameter. The first term encourages each image embedding to be closest to its matched text; the second term encourages each text embedding to be closest to its matched image. The denominator sums over all items in the batch, treating the non-matching pairs as negative examples.
The InfoNCE loss has an elegant information-theoretic interpretation. Minimising (Infonce) is equivalent to maximising a lower bound on the mutual information between the image and text embedding random variables. Specifically, if the optimal critic achieves the maximum of the bound, then where is the minimum achievable loss. This means that larger batch sizes permit tighter bounds on mutual information, which is why CLIP was trained with batch sizes of 32,768.
Zero-shot classification with CLIP.
The remarkable property of CLIP is that after pretraining, it can classify images into arbitrary categories without any task-specific training. Given a set of class names , one constructs text prompts such as “a photo of a ” and computes the text embeddings . For a new image , the predicted class is (CLIP Zeroshot) where . This zero-shot mechanism is powerful because the class vocabulary is unbounded: one can classify images into any set of categories describable in natural language, without retraining the model.
Remark 28.
Despite its remarkable zero-shot capabilities on natural images, CLIP performs poorly on medical images out of the box. The reason is distributional mismatch: CLIP was trained on internet image–text pairs (photographs, illustrations, memes), which bear little resemblance to radiological images paired with clinical reports. A chest X-ray captioned “bilateral pleural effusions” lives in a completely different region of image–text space than a photograph captioned “a dog playing in the park.” This distributional gap motivates domain-specific adaptations such as BiomedCLIP.
BiomedCLIP: Domain-Specific Contrastive Pretraining
BiomedCLIP addresses the distributional mismatch of general-purpose CLIP by pretraining on domain-specific data. Developed by Zhang et al., BiomedCLIP was trained on PMC-15M, a dataset of approximately 15 million biomedical image–text pairs extracted from 4.4 million scientific articles in PubMed Central. The images span the full range of biomedical visual data: radiology (X-rays, CT, MRI, ultrasound), pathology (histological slides), microscopy (fluorescence, electron), clinical photography (dermatology, ophthalmology), and scientific figures (plots, diagrams, molecular structures).
The architecture follows the CLIP blueprint: a Vision Transformer (ViT-B/16) serves as the image encoder, and a domain-adapted text encoder (PubMedBERT) processes the textual descriptions. The key differences from general CLIP are:
Domain-specific visual vocabulary. Biomedical images contain structures (alveoli, tumour margins, cell nuclei) that never appear in natural photographs. By pretraining on 15 million such images, BiomedCLIP learns visual features attuned to these structures.
Domain-specific textual vocabulary. Medical text uses specialised terminology (“hepatocellular carcinoma,” “ground-glass opacity,” “anechoic cyst”) that is rare or absent in general web text. PubMedBERT was pretrained on biomedical literature, providing a text encoder that understands this vocabulary.
Fine-grained image–text alignment. Scientific articles often contain figure captions that describe specific regions of an image (“arrow indicates the lesion”), providing more fine-grained supervisory signal than the loose image–caption pairs found on the internet.
Example 23.
BiomedCLIP for zero-shot radiology finding detection. Consider a chest X-ray that a radiologist has not yet reviewed. Using BiomedCLIP, we can perform zero-shot classification by constructing text prompts for common findings:
= “chest X-ray showing pneumothorax”
= “chest X-ray showing pleural effusion”
= “chest X-ray showing cardiomegaly”
= “chest X-ray showing pulmonary nodule”
= “normal chest X-ray with no acute findings”
For each prompt , we compute the cosine similarity between the image embedding and the text embedding . On the CheXpert benchmark, BiomedCLIP achieves zero-shot AUC scores of – across 14 pathology categories, compared to – for general CLIP. This – percentage point improvement demonstrates the value of domain-specific pretraining.
Critically, this zero-shot capability extends to findings that were not explicitly part of the pretraining task. Because BiomedCLIP learned from millions of diverse scientific image–text pairs, it can recognise findings described in novel text prompts, such as “chest X-ray showing Kerley B lines” or “chest X-ray showing tracheal deviation,” even if these exact phrases appeared infrequently in the training corpus. The model has learned a compositional understanding of medical visual-textual semantics.
The success of BiomedCLIP demonstrates a broader principle: domain adaptation of vision-language models is not merely helpful for medical applications; it is essential. The gap between general and domain-specific performance is so large that deploying unadapted CLIP in a clinical setting would be not just suboptimal but potentially dangerous.
Quantitative improvements.
The improvements of BiomedCLIP over general CLIP are consistent across a wide range of tasks:
Image–text retrieval: On the ROCO (Radiology Objects in Context) benchmark, BiomedCLIP achieves Recall@10 of for image-to-text retrieval and for text-to-image retrieval, compared to and for general CLIP.
Visual question answering: On the VQA-RAD benchmark (radiology visual question answering), BiomedCLIP's embeddings used as input features achieve accuracy, compared to for general CLIP features.
Cross-modal retrieval for segmentation: When used as a feature extractor for text-conditioned segmentation, BiomedCLIP embeddings improve Dice scores by – percentage points compared to general CLIP across five organ segmentation benchmarks.
These improvements arise not from architectural innovation but purely from training on domain-appropriate data, underscoring the importance of data curation in VLM development.
LLaVA-Med: From Alignment to Reasoning
BiomedCLIP excels at alignment-mapping images and text to a shared space-but it does not reason. It can tell you that a chest X-ray is similar to the description “pleural effusion,” but it cannot explain what a pleural effusion is, describe its clinical significance, or recommend follow-up imaging. For these capabilities, we need models that can generate language, not merely match it.
LLaVA-Med (Large Language-and-Vision Assistant for Biomedicine) bridges this gap by combining a pretrained vision encoder with a large language model (LLM), enabling free-form visual question answering and medical reasoning. The architecture consists of three components:
A vision encoder (typically a CLIP ViT-L/14) that produces a sequence of visual tokens from the input image, where is the number of image patches;
A projection layer that maps visual tokens into the input space of the language model: ;
A large language model (Vicuna, LLaMA, or similar) that takes as input the interleaved sequence of projected visual tokens and text tokens, and generates a textual response autoregressively.
The training of LLaVA-Med proceeds in two stages:
Stage 1: Biomedical concept alignment.
The vision encoder and LLM are frozen, and only the projection layer is trained. The training data consists of biomedical image–caption pairs from PMC-15M, and the objective is standard next-token prediction on the captions conditioned on the visual tokens. This stage teaches the projection layer to translate visual features into the “language” that the LLM understands.
Stage 2: Instruction tuning.
The projection layer and the LLM are fine-tuned jointly on instruction-following data. Each training example is a conversation between a user and an assistant about a biomedical image, with questions such as “What abnormality is visible in this CT scan?” and detailed, clinically accurate responses. The instruction-tuning data is generated using GPT-4 prompted with figure captions and contextual information from scientific articles, then filtered for accuracy.
The result is a model that can engage in multi-turn dialogue about medical images:
User: What do you see in this MRI scan?
LLaVA-Med: This is an axial T2-weighted MRI of the brain showing a well-circumscribed, hyperintense lesion in the right temporal lobe, measuring approximately 3.2 cm in greatest dimension. The lesion demonstrates homogeneous signal intensity with no surrounding oedema or mass effect, which is most consistent with an arachnoid cyst. Differential considerations include an epidermoid cyst, which would typically show restricted diffusion on DWI sequences.
User: Would you recommend any follow-up?
LLaVA-Med: Given the benign appearance and lack of mass effect, this is likely an incidental finding. I would recommend comparison with prior imaging if available. If this is a new finding or if the patient is symptomatic, a short-interval follow-up MRI in 6–12 months would be appropriate to confirm stability. DWI sequences should be included to differentiate from an epidermoid cyst.
This capability-generating clinically relevant, contextually appropriate text from medical images-opens new avenues for segmentation. Rather than producing a silent mask, a VLM-based segmentation system can explain what it segmented, why it drew the boundaries where it did, and how confident it is in the result.
Limitations of LLaVA-Med.
Despite its impressive conversational abilities, LLaVA-Med has significant limitations. First, the two-stage training pipeline means that the vision encoder is never fine-tuned on medical data; it retains the general-purpose features learned during CLIP pretraining, which may miss subtle medical findings. Second, the instruction-tuning data is generated by GPT-4, introducing a “student-teacher” gap: if GPT-4 makes errors in the synthetic training data, LLaVA-Med inherits those errors. Third, the model operates on single images and cannot reason across multiple views or sequences (e.g., comparing a lesion across arterial, portal venous, and delayed phases of a contrast-enhanced CT), which is essential for many diagnostic tasks. These limitations motivate ongoing research into multi-view, multi-sequence VLMs that can reason across the full complement of data available in a clinical imaging study.
Three VLM Architecture Types
The space of VLM architectures for medical segmentation can be organised into three canonical types, each representing a different strategy for combining visual and textual information. Understanding these types is essential for choosing the right architecture for a given application.
Type 1: Encoder-based cross-modal alignment.
Separate encoders process the image and text independently, producing fixed-length embeddings that are compared via cosine similarity or a lightweight matching head. CLIP and BiomedCLIP are canonical examples. The key property is that the image and text encoders operate independently: at inference time, one can precompute all text embeddings and perform efficient retrieval. However, the interaction between modalities is limited to a single similarity score, which restricts the model's ability to capture fine-grained cross-modal relationships.
Formally, given image and text , the similarity score is (Type1)
Type 2: Encoder-based multimodal attention.
A unified encoder processes both modalities simultaneously, using cross-attention layers to enable fine-grained interaction between image patches and text tokens. Models in this category include ALBEF (Align before Fuse) and its medical adaptations. The cross-attention mechanism computes (Type2) where are query vectors derived from text tokens and are key and value vectors derived from image patches. This enables each text token to “attend” to relevant image regions, and vice versa, creating a rich cross-modal representation.
Type 3: Encoder-decoder integration.
An image encoder produces visual tokens that are fed into a decoder-only language model, which generates text autoregressively. LLaVA-Med is the canonical example. The decoder generates the output token by token: (Type3) This type has the greatest expressive power-it can generate arbitrary text about the image-but is also the most computationally expensive, as each output token requires a full forward pass through the language model.
The choice among these three types depends on the application. For large-scale retrieval (finding similar cases in a database of millions of images), Type 1 is preferred because image and text embeddings can be precomputed and compared via efficient nearest-neighbour search. For tasks requiring fine-grained spatial reasoning (locating a specific finding within an image), Type 2 provides the cross-modal attention necessary to align text tokens with image regions. For interactive clinical assistants that must generate explanations and engage in dialogue, Type 3 is necessary despite its computational cost.
Remark 29.
In practice, many modern systems combine elements of multiple types. For example, a system might use Type 1 alignment for initial retrieval (finding relevant cases), Type 2 attention for detailed analysis (localising findings), and Type 3 generation for producing the final report. This “cascade” strategy balances efficiency and expressiveness by applying computational resources where they are most needed.
Pretraining Objectives: ITM, CL, and MLM
Beyond the InfoNCE contrastive loss, VLMs are typically trained with a combination of pretraining objectives that capture different aspects of the image–text relationship. The three most common objectives are contrastive loss (CL), image–text matching (ITM), and masked language modelling (MLM).
Contrastive loss (CL).
This is the InfoNCE loss defined in Definition 32. It operates on global image and text embeddings and provides the coarsest level of supervision: it teaches the model that an image and its corresponding text should be more similar than random pairings. CL is efficient to compute and provides a strong training signal, especially in the early stages of pretraining.
Image–text matching (ITM).
While CL operates on separate encoders, ITM operates on the fused representation produced by a multimodal encoder (Type 2 architecture). The model is presented with an image–text pair and must predict whether they are matched (positive pair from the dataset) or mismatched (negative pair constructed by random pairing).
Definition 33 (Image–Text Matching Score).
Given an image and text processed through a multimodal encoder to produce a fused representation , the image–text matching score is (ITM) where is the sigmoid function and , are learnable parameters. The ITM objective is the binary cross-entropy where for matched pairs and for mismatched pairs. Negative pairs are typically constructed via hard negative mining: selecting texts that are similar but not matching to the image (based on contrastive similarity) to provide a more informative training signal.
Masked language modelling (MLM).
Adapted from BERT, MLM randomly masks a fraction of the text tokens
and trains the model to reconstruct them given the remaining text and
the image. This forces the multimodal encoder to ground language
understanding in visual content. In a medical context, masking the
word “pneumothorax” in the sentence “The chest X-ray shows a
right-sided [MASK]” requires the model to examine the image and
identify the finding. The MLM loss is
(MLM)
where is the set of masked positions and
denotes the text with masked tokens
replaced by a special [MASK] token.
Remark 30.
These three objectives are complementary. CL provides global alignment between modalities (“this image and this text describe the same thing”). ITM provides binary matching with hard negatives (“this specific image matches this specific text, but not that similar text”). MLM provides token-level grounding (“the missing word in this sentence can be inferred from the image”). Training with all three objectives simultaneously produces representations that are aligned at the global level, discriminative at the instance level, and grounded at the token level.
Text-Guided Segmentation and Retrieval-Augmented Generation
The vision-language models introduced in the previous section learn to understand the relationship between medical images and clinical text. In this section, we turn that understanding into action: using text to guide segmentation decisions, retrieving relevant medical knowledge to ground model outputs, and quantifying uncertainty in the resulting predictions. The central theme is that language serves not merely as an annotation mechanism but as a control interface for segmentation-a way to steer the model toward clinically relevant outputs and away from hallucinated artefacts.
TGSAM-2: Text-Guided SAM 2
The Segment Anything Model 2 (SAM 2), introduced in sec:medseg:sam2 for interactive medical segmentation, accepts points, boxes, and masks as prompts but notably lacks a text interface. A clinician cannot type “segment the hypointense lesion on the left lateral lobe” and receive a mask; instead, they must click on or draw a box around the target structure. TGSAM-2 (Text-Guided SAM 2) addresses this limitation by injecting a text-conditioned visual perception module into SAM 2's streaming memory pipeline, enabling natural language instructions to guide both frame-level segmentation and temporal propagation in video sequences.
The architecture of TGSAM-2 consists of five components arranged in a pipeline:
Text encoder. A frozen BiomedCLIP text encoder processes the clinical instruction to produce a text embedding and a sequence of token-level features .
Image encoder. SAM 2's Hiera image encoder extracts multi-scale visual features at scales .
Text-conditioned perception module (TCPM). This is the key novel component. The TCPM performs cross-attention between text token features and multi-scale visual features: (TCPM) where is a learnable gating parameter initialised to zero (ensuring the model starts from SAM 2's pretrained behaviour). The cross-attention enables visual features to be modulated by the text instruction: features corresponding to the described structure are amplified, while irrelevant features are suppressed.
Streaming memory. SAM 2's memory bank stores per-frame embeddings for temporal propagation. In TGSAM-2, the text-conditioned features are used to update the memory bank, so that the text instruction persists across frames without needing to be re-encoded at each time step.
Mask decoder. SAM 2's mask decoder produces the final segmentation mask from the text-conditioned features and streaming memory, unchanged from the original architecture.
The training of TGSAM-2 is efficient because only the TCPM parameters and the gating scalar are trained; the BiomedCLIP text encoder, SAM 2 image encoder, and mask decoder all remain frozen. This parameter-efficient strategy avoids catastrophic forgetting of SAM 2's pretrained segmentation capabilities while adding text understanding.
Example 24.
TGSAM-2 for endoscopic polyp segmentation with text guidance. Consider an endoscopy video in which the gastroenterologist is looking for polyps. Without text guidance, SAM 2 requires the clinician to click on each polyp as it appears in the video-a tedious process that interrupts the examination flow. With TGSAM-2, the clinician provides a single text instruction at the start of the video:
“Segment all sessile polyps with irregular surface patterns.”
The TCPM processes this instruction and conditions the visual features to be sensitive to the described appearance: sessile (flat-based) morphology with irregular mucosal patterns. As the endoscope moves through the colon, the streaming memory propagates this text-derived attention across frames. When a polyp matching the description enters the field of view, the model automatically segments it without requiring any clicks.
On the SUN-SEG benchmark for video polyp segmentation, TGSAM-2 with text guidance achieves a Dice score of compared to for point-prompted SAM 2 and for fully automatic (no prompt) baselines. More importantly, the text-guided approach reduces false positives by compared to the automatic baseline, because the text instruction specifies what kind of polyp to segment, filtering out benign mucosal folds and other confounders that visually resemble polyps.
The clinical value is clear: text guidance transforms SAM 2 from a tool that requires constant interaction into one that can operate semi-autonomously, guided by a single natural language instruction that captures the clinician's intent.
Retrieval-Augmented Generation for Clinical Reasoning
Vision-language models are powerful but imperfect. They can hallucinate-generating confident but false clinical assertions that have no basis in the input image or in medical knowledge. A VLM might describe a “suspicious mass in the right lower lobe” when the image actually shows a normal variant, or recommend a biopsy for a finding that current guidelines classify as benign. In a medical context, such hallucinations are not merely annoying; they are potentially lethal.
Retrieval-augmented generation (RAG) addresses this problem by grounding model outputs in verified external knowledge. Instead of relying solely on the VLM's internal representations (which may contain errors or outdated information), RAG retrieves relevant documents from a curated knowledge base and incorporates them into the generation process.
Definition 34 (Retrieval-Augmented Generation).
A retrieval-augmented generation (RAG) system for medical segmentation consists of:
A query encoder that maps an image–text query pair (the medical image and an optional clinical question) to a query embedding;
A knowledge base consisting of indexed entries, where is the embedding and is the content (a clinical guideline, case report, textbook passage, or annotated prior case);
A retriever that returns the top- documents whose embeddings are closest to the query embedding;
A generator (typically a VLM) that produces an output conditioned on both the original input and the retrieved documents: (RAG)
The output may be a segmentation mask, a clinical report, or a structured decision (e.g., BI-RADS category for a mammographic finding), depending on the downstream task.
The power of RAG lies in its ability to dynamically inject context that the model's fixed parameters cannot provide. Consider a radiologist encountering an unusual finding that resembles a rare condition. Without RAG, the VLM must rely on whatever it learned about this condition during pretraining, which may be inaccurate or incomplete if the condition was underrepresented in the training data. With RAG, the system retrieves the relevant clinical guideline, recent case reports describing similar findings, and annotated examples from the knowledge base. This retrieved context is prepended to the VLM's input, giving it access to verified, up-to-date information at inference time.
Proposition 8 (RAG Reduces Hallucination Rate).
Let denote a vision-language model generating clinical text from medical images, and let denote the same model augmented with retrieval. Define the hallucination rate as the fraction of generated clinical assertions that are factually incorrect: where is the set of clinical assertions produced by . Under the assumption that the knowledge base is accurate and the retriever returns relevant documents with probability at least , the hallucination rate of the RAG-augmented model satisfies (RAG Hallucination) where is the residual hallucination rate when relevant documents are retrieved (i.e., the probability that the model hallucinates despite having access to correct information). When is high and , RAG substantially reduces the hallucination rate.
Proof.
Partition the generated assertions into two cases: those for which the retriever returns at least one relevant document (probability ), and those for which it does not (probability ). In the first case, the model has access to correct information and hallucinates with probability . In the second case, the model operates without relevant retrieved context and hallucinates at its baseline rate . By the law of total expectation, which is exactly (RAG Hallucination). Since whenever the retrieved documents are informative, we have .
Remark 31.
A critical advantage of RAG over parameter-based knowledge storage is freshness. Medical knowledge evolves rapidly: new treatment guidelines, updated staging criteria, and revised diagnostic thresholds are published continuously. A VLM trained in 2024 may contain outdated information by 2025. A RAG system, by contrast, can incorporate new knowledge simply by updating the document index, without any model retraining. This property is especially valuable in oncology, where treatment protocols and staging systems change with every major conference cycle.
RAG for segmentation decisions.
How does RAG concretely improve segmentation? Consider a liver CT scan showing a lesion with ambiguous imaging characteristics. The segmentation model produces a mask, but the clinical question is whether this lesion should be classified as hepatocellular carcinoma (HCC), a benign haemangioma, or focal nodular hyperplasia (FNH). The correct classification affects the segmentation boundary (HCC often has irregular margins with satellite nodules; haemangiomas are typically well-circumscribed) and the clinical management (HCC requires staging and possibly resection; haemangiomas require no treatment).
A RAG-augmented system retrieves:
The LI-RADS (Liver Imaging Reporting and Data System) criteria, which define a scoring system based on arterial phase hyperenhancement, washout, capsule appearance, and threshold growth;
Three annotated cases from the knowledge base showing similar imaging features, with their final pathological diagnoses;
The patient's prior imaging studies (if available), enabling assessment of interval growth.
With this retrieved context, the VLM can generate a structured report that applies the LI-RADS criteria to the current case, references the similar prior cases, and produces a segmentation mask whose boundary reflects the expected morphology for the most likely diagnosis.
Uncertainty-Aware VLM Outputs
Even with RAG grounding, segmentation models produce uncertain predictions, particularly at ambiguous boundaries between tissue types. Traditional segmentation models express uncertainty numerically (e.g., via softmax probabilities or Monte Carlo dropout variance), but these numbers are opaque to clinicians. A probability map showing at the tumour boundary tells the radiologist that the model is uncertain, but not why it is uncertain or what should be done about the uncertainty.
UAU-Net (Uncertainty-Aware U-Net) and related architectures address this gap by interfacing with large language models to generate semantic uncertainty summaries-natural language descriptions of where and why the model is uncertain.
The process works as follows:
Pixel-level uncertainty estimation. The segmentation model (e.g., a U-Net variant with Monte Carlo dropout or deep ensembles) produces a spatial uncertainty map , where high values indicate uncertain predictions.
Uncertainty region extraction. Connected components of the thresholded uncertainty map are extracted and characterised by their location (anatomical region), size (number of uncertain pixels), shape (elongated boundary vs. diffuse patch), and context (which classes are confused).
Semantic summary generation. The extracted uncertainty characteristics are formatted as a structured prompt and passed to an LLM, which generates a natural language summary. For example:
“The tumour boundary is uncertain in the inferolateral region (slices 38–45), where the contrast between tumour and surrounding hepatic parenchyma is minimal. The model assigns a Dice uncertainty of in this region. Consider requesting a delayed-phase contrast sequence for better boundary delineation.”
Clinical alert generation. When the uncertainty exceeds a predefined clinical threshold (e.g., the uncertain region would change the tumour staging or surgical planning), the system generates an explicit alert recommending human review.
Remark 32.
The clinical value of semantic uncertainty summaries lies in their actionability. A numerical uncertainty map requires the clinician to interpret spatial patterns and decide what to do; a semantic summary directly recommends an action (“consider requesting a delayed-phase sequence”). This bridges the gap between model output and clinical decision-making, reducing the cognitive load on the clinician and increasing the likelihood that uncertainty is appropriately addressed.
Formal characterisation of semantic uncertainty.
We can formalise the semantic uncertainty summary as a function that maps a spatial uncertainty map and the original image to a natural language description. The quality of this summary can be measured by its informativeness (does it convey the location, magnitude, and clinical relevance of the uncertainty?) and its actionability (does it suggest a concrete next step?).
Formally, let denote the set of actionable recommendations that could be derived from the uncertainty map. A semantic summary is complete if every recommendation is either explicitly stated in or logically entailed by the statements in . It is sound if every recommendation stated in belongs to . In practice, current systems achieve high soundness but incomplete coverage, tending to describe the most uncertain regions while missing subtle uncertainty patterns.
Multimodal Benchmarks for Medical VLMs
The rapid proliferation of medical VLMs has created an urgent need for rigorous evaluation. How do we know whether a model truly understands medical images and text, rather than exploiting superficial correlations? Three recent benchmarks have pushed the evaluation frontier, each probing different aspects of VLM capability.
DrVD-Bench: Comprehensive VLM evaluation.
DrVD-Bench (Doctor Video Dialogue Benchmark) provides the most comprehensive evaluation of medical VLMs to date. The benchmark tests 19 VLMs across 20 task types (diagnosis, treatment planning, anatomical identification, pathology grading, etc.) and 5 imaging modalities (radiology, pathology, dermatology, ophthalmology, endoscopy). The evaluation uses multi-turn question answering, where each question builds on the model's previous response, testing the model's ability to maintain coherent clinical reasoning across a dialogue.
Example 25.
DrVD-Bench evaluation revealing VLM reasoning failures. In the DrVD-Bench evaluation, a revealing pattern emerged across all tested VLMs: models performed well on perception tasks (“What structures are visible in this image?”) but failed dramatically on reasoning tasks (“Given the findings, what is the most likely diagnosis and why?”).
Consider a multi-turn evaluation on a cardiac MRI:
Turn 1: “What do you see in this cardiac MRI?”
Model: “This is a short-axis view of the heart showing the left ventricle with thinning of the inferolateral wall and delayed gadolinium enhancement in the same region.” [Correct]
Turn 2: “What is the most likely diagnosis?”
Model: “The findings are consistent with myocardial infarction in the territory of the left circumflex artery.” [Correct]
Turn 3: “The patient has no history of coronary artery disease and is 22 years old. Does this change your differential?”
Model: “No, myocardial infarction remains the most likely diagnosis given the imaging findings.” [Incorrect-in a 22-year-old without coronary disease, myocarditis or hypertrophic cardiomyopathy should be the leading differential]
This example illustrates a critical failure mode: the VLM can describe what it sees (perception) and apply pattern matching (delayed enhancement infarction) but cannot integrate clinical context (age, history) to revise its reasoning. Across DrVD-Bench, the average reasoning accuracy was compared to for perception, revealing a fundamental gap between seeing and understanding.
MedicalNarratives: Learning how radiologists look.
MedicalNarratives is a large-scale dataset of 4.7 million image–text pairs, of which approximately 1 million include localised mouse traces that record the radiologist's cursor movements during the report-writing process. These traces are a proxy for eye movements, capturing not just what the radiologist reported but how they visually inspected the image.
Insight.
Mouse traces from radiologists teach models not just what to see, but how to look. A conventional image–text pair tells the model the answer (“there is a nodule in the right upper lobe”) but nothing about the process of arriving at that answer. Mouse traces reveal the radiologist's visual search pattern: the systematic scan of lung fields, the pause at a suspicious region, the comparison with the contralateral side. Training VLMs on this process information, not just the outcome, produces models that exhibit more human-like visual attention patterns and more robust detection of subtle findings.
The mouse traces are represented as temporal sequences of coordinates, which are converted into spatial heatmaps indicating the radiologist's attention distribution. These heatmaps serve as an additional supervision signal during training: the model is penalised not only for producing incorrect text but also for attending to the wrong image regions. Formally, given the radiologist's attention heatmap and the model's attention map , the attention alignment loss is (Attention Alignment) where the KL divergence encourages the model's visual attention to match the radiologist's gaze pattern.
3DReasonKnee: Grounded 3D reasoning.
While most medical VLM benchmarks operate on 2D images, 3DReasonKnee extends evaluation to three-dimensional volumetric data. The benchmark consists of knee MRI volumes annotated with both segmentation masks and natural language reasoning traces that explain the diagnostic logic. For example, an annotation might state: “The anterior cruciate ligament shows abnormal signal on the sagittal PD-weighted sequence (slices 18–24) with complete disruption of fibre continuity at the femoral attachment, consistent with a complete ACL tear. Note the associated bone marrow oedema in the lateral femoral condyle and posterolateral tibial plateau (kissing contusions), supporting the mechanism of a pivot-shift injury.”
This benchmark tests whether VLMs can perform three tasks simultaneously: (1) identify the relevant structure in 3D, (2) describe its abnormality, and (3) reason about the clinical implications. Current models perform well on tasks (1) and (2) in isolation but struggle to maintain coherent reasoning across all three, particularly when the reasoning requires integrating information from multiple slices or sequences.
Multimodal Hallucination in Medical AI
We conclude this section with a discussion of what may be the most dangerous failure mode of medical VLMs: multimodal hallucination. Unlike text-only hallucination (where an LLM generates plausible but false text), multimodal hallucination involves a VLM generating clinical assertions that are contradicted by the input image but are linguistically coherent and medically plausible.
The danger is clear. A VLM that describes “a 2.3 cm mass in the right breast at the 10 o'clock position” when no mass is present could trigger an unnecessary biopsy, causing physical pain, psychological distress, and financial cost. Conversely, a VLM that fails to mention a real finding (a “hallucination of absence”) could delay a life-saving diagnosis. Both failure modes are qualitatively different from text-only hallucination: they involve concrete, verifiable claims about a specific image that can be checked against ground truth.
Sources of multimodal hallucination.
Medical VLMs hallucinate for several reasons:
Training data bias. If the training data disproportionately contains certain findings (e.g., pleural effusions are common in chest X-ray datasets), the model develops a prior toward generating these findings regardless of the input image. This is analogous to the “frequency bias” in text-only LLMs.
Modality imbalance. In encoder-decoder VLMs (Type 3), the language model is much larger and more powerful than the vision encoder. The model may “ignore” the visual input and generate text based primarily on its language prior, particularly for prompts that trigger well-rehearsed textual patterns.
Resolution mismatch. Medical images often contain subtle findings (a 3 mm nodule in a 512512 chest X-ray) that may be lost during the image encoding process, especially when the vision encoder reduces the image to a small number of tokens. The VLM may hallucinate findings based on global image statistics rather than the fine-grained details that matter clinically.
Prompt sensitivity. VLMs are surprisingly sensitive to the phrasing of the prompt. Asking “Is there a mass in this image?” (a leading question) produces different hallucination rates than asking “Describe the findings in this image” (an open question), because leading questions activate the model's tendency toward confirmatory responses.
Caution.
Multimodal hallucination in medical AI can be lethal-always ground outputs. A VLM that confidently describes a finding that does not exist can trigger invasive procedures, unnecessary treatments, or false reassurance. No medical VLM output should be treated as ground truth without independent verification, either by a human clinician, by cross-referencing with a knowledge base (RAG), or by requiring the model to cite specific image regions that support each assertion. The principle of “trust but verify” is insufficient in medicine; the correct principle is “verify, then consider trusting.”
Mitigation strategies.
Several strategies have been proposed to reduce multimodal hallucination in medical VLMs:
Grounding via attention supervision. Training the model with attention alignment losses (as in MedicalNarratives, (Attention Alignment)) forces the model to look at the relevant image regions when generating text, reducing the tendency to generate text from the language prior alone.
Retrieval augmentation. As formalised in Proposition 8, RAG reduces hallucination by providing external knowledge that constrains the model's outputs. The model is less likely to hallucinate a rare finding if the retrieved documents describe common findings for the given imaging presentation.
Self-verification. The model is asked to verify its own assertions by identifying the specific image region that supports each claim. If the model cannot point to a region (i.e., its attention is diffuse rather than localised), the assertion is flagged as potentially hallucinated.
Calibrated confidence. Training the model to produce calibrated confidence scores alongside its assertions allows downstream systems to filter low-confidence claims. In medical applications, it is better to say nothing than to say something false with high confidence.
Multi-model consensus. Running the same image through multiple VLMs and accepting only assertions that appear across all models reduces the hallucination rate at the cost of increased computation. This is the VLM analogue of ensemble methods in traditional machine learning.
Remark 33.
Despite these mitigation strategies, completely eliminating multimodal hallucination remains an open problem. Current approaches reduce the frequency of hallucinations but cannot guarantee their absence. This is a fundamental limitation: any model that generates text from visual input must balance between sensitivity (mentioning real findings) and specificity (not mentioning false ones). Achieving near-perfect specificity typically requires sacrificing sensitivity, which is unacceptable in screening applications where missing a finding is worse than flagging a false one. The optimal operating point depends on the clinical context and must be set by domain experts, not by model developers.
Evaluation of hallucination.
Measuring hallucination in medical VLMs requires specialised metrics that go beyond standard NLP evaluation. The CHAIR (Caption Hallucination Assessment with Image Relevance) metric, originally developed for natural image captioning, has been adapted for medical applications. The medical CHAIR score is defined as (Chair) where is the set of clinical assertions in the generated text and is the set of ground-truth findings in image . A CHAIR score of means that of the model's assertions are hallucinated.
However, CHAIR treats all hallucinations equally, which is inappropriate in a clinical context. Hallucinating a “bilateral pleural effusion” when none exists is far more serious than describing a finding as “moderate” when it is actually “mild.” Severity-weighted metrics that account for the clinical impact of each hallucination are an active area of research.
The Road Ahead: From Understanding to Action
The integration of language into medical image segmentation is still in its early stages. Current systems can interpret text prompts, retrieve relevant knowledge, and generate explanations, but they remain far from the clinical reasoning capabilities of expert radiologists. Several directions are particularly promising:
Interactive segmentation dialogue.
Future systems will engage in multi-turn dialogue with clinicians, iteratively refining segmentation masks based on verbal feedback. “The boundary is too generous in the anterior region-can you tighten it?” will produce a refined mask without requiring the clinician to draw corrections manually.
Cross-modal self-supervision.
The vast majority of medical images are accompanied by clinical reports, but current VLMs exploit only a fraction of this data. Self-supervised methods that automatically extract image–text correspondences from clinical workflows (radiology reports, surgical notes, pathology descriptions) will unlock much larger training corpora.
Embodied medical AI.
As robotic surgery advances, segmentation models will need to operate in real time on video feeds, responding to verbal commands from surgeons. “Highlight the ureter-I need to avoid it during dissection” requires real-time text-guided segmentation at video frame rates, a challenge that pushes the limits of current VLM architectures.
Historical Note.
The application of vision-language models to medicine has compressed decades of progress into a few years. CLIP appeared in January 2021. BiomedCLIP followed in 2023, demonstrating the importance of domain-specific pretraining. LLaVA-Med, introduced in mid-2023, brought generative visual reasoning to biomedical images. By 2024, text-guided segmentation systems like TGSAM-2 were demonstrating clinical-grade performance on video segmentation tasks. The MedicalNarratives dataset, with its radiologist mouse traces, and DrVD-Bench, with its multi-turn clinical reasoning evaluation, appeared in late 2024 and early 2025, respectively. This trajectory suggests that within a few years, VLMs may become standard components in clinical imaging workflows-not replacing radiologists, but augmenting their capabilities with language-aware, knowledge-grounded, uncertainty-communicating AI assistants.
Exercise 26.
Temperature sensitivity of InfoNCE. Consider the InfoNCE loss in (Infonce) with a batch of image–text pairs.
Show that as , the InfoNCE loss converges to zero if and only if each image embedding is most similar to its matched text embedding. That is, prove that if and only if for all and all .
Show that as , the gradients of the InfoNCE loss vanish, so the model learns nothing. Specifically, compute and show that as .
In practice, CLIP uses a learned temperature initialised at . Argue qualitatively why an intermediate value of is optimal: too small causes training instability (gradients concentrate on hard negatives), while too large provides insufficient learning signal.
(Bonus.) Suppose the embeddings are uniformly distributed on the unit sphere in . Derive the expected InfoNCE loss as a function of , , and , under the assumption that positive pairs have cosine similarity and negative pairs have expected cosine similarity .
Exercise 27.
Designing a RAG system for liver lesion characterisation. You are tasked with building a RAG-augmented VLM system for liver lesion characterisation on contrast-enhanced CT scans.
Define the knowledge base . List at least five types of documents that should be included (e.g., LI-RADS criteria, clinical guidelines, annotated case libraries). For each type, explain what information it provides and how it would be indexed for retrieval.
Design the query encoder . The input is a contrast-enhanced CT image and a clinical question (e.g., “What is the LI-RADS category of this lesion?”). Describe how you would combine image and text features into a query embedding. Should the query emphasise visual features, textual features, or both? Justify your design.
Derive an expression for the expected number of retrieved documents needed to achieve a target hallucination rate , as a function of the base model's hallucination rate , the retriever's relevance probability (which increases with ), and the residual hallucination rate .
Discuss the failure modes of your RAG system. What happens when the knowledge base contains outdated or incorrect information? How would you handle contradictions between retrieved documents? What if the query is out-of-distribution (a finding never described in the knowledge base)?
Exercise 28.
Detecting and measuring multimodal hallucination.
Propose a self-verification protocol for medical VLMs. Given a generated report and the input image , design a procedure that identifies which assertions in are supported by the image and which may be hallucinated. Your protocol should use the VLM's own attention maps and should not require access to ground-truth labels.
The CHAIR metric defined in (Chair) treats all hallucinations equally. Design a severity-weighted variant that assigns higher weight to clinically dangerous hallucinations. Define a severity function for assertions and write the formula for . Discuss how the severity weights should be determined (by clinical experts, by consequence analysis, or by other means).
A medical VLM generates the following report for a chest X-ray: “There is a left-sided pleural effusion with adjacent atelectasis. The heart is mildly enlarged. A cm nodule is seen in the right upper lobe.” The ground-truth findings are: left-sided pleural effusion and adjacent atelectasis. Compute and, using a severity scheme of your design, compute . Discuss which hallucinated assertion is more clinically concerning and why.
(Bonus.) Prove that the multi-model consensus approach (running independent VLMs and accepting only assertions that appear in all outputs) reduces the hallucination rate exponentially in , under the assumption that each model hallucinates independently with probability . Discuss why the independence assumption is unrealistic in practice and what this implies for the actual hallucination reduction.
Generative + Foundation Model Integration
The preceding sections developed three pillars of modern medical image segmentation: generative models that synthesise training data and model uncertainty, foundation models such as SAM that provide powerful zero-shot segmentation primitives, and vision–language models (VLMs) that bridge visual content with semantic understanding. Each pillar, in isolation, has clear limitations. Generative models produce diverse samples but lack the structured segmentation capabilities of foundation models. Foundation models like SAM demand carefully crafted prompts-points, bounding boxes, or text-yet in clinical practice no radiologist stands by to click on every scan. VLMs understand what is in an image but cannot, on their own, produce pixel-precise delineations.
The decisive insight of the most recent generation of methods is that these three pillars are complementary: the weaknesses of each are precisely the strengths of another. A VLM can generate the semantic understanding that SAM needs as a prompt. A diffusion model can synthesise the training data that a segmentation network lacks. SAM's prompt sensitivity, long regarded as a defect, becomes a feature when a conditional VAE models the full distribution over prompts and masks. This section formalises these synergies and surveys the architectures that exploit them.
Key Idea.
The future is not one model but an orchestra of specialised generative, foundation, and language models. No single architecture excels simultaneously at open-vocabulary understanding, pixel-precise segmentation, uncertainty quantification, and data-efficient learning. The frontier systems of 2024–2025 instead compose a pipeline of specialist models: a VLM for semantic grounding, a foundation segmenter for spatial precision, and a generative model for distributional reasoning. The engineering challenge shifts from designing one monolithic model to designing the interfaces between models-the prompts, latent codes, and feedback loops that allow information to flow from one module to the next. Mathematically, this is a problem of compositional inference: given a factorisation where represents intermediate representations produced by different models, how do we ensure that the composite system inherits the strengths of each component without compounding their errors?
ESC-Net: Open-Vocabulary Segmentation with SAM
Classical semantic segmentation operates over a closed vocabulary: the set of classes is fixed at training time, and the model cannot recognise objects outside this predefined taxonomy. In medical imaging, this is particularly restrictive. A model trained to segment liver tumours cannot, without retraining, segment adrenal gland lesions, even if both appear as hypo-attenuating masses on CT. Open-vocabulary segmentation removes this constraint by leveraging vision–language embeddings to segment objects described by arbitrary text queries at inference time.
Definition 35 (Open-Vocabulary Segmentation).
Let denote the set of class labels seen during training and the set of class labels encountered at test time, with in general. An open-vocabulary segmentation model is a mapping (OPEN Vocab) where is the image space, is the space of all natural-language class descriptions, and produces a binary mask for the concept described by in image . The model must generalise to without parameter updates.
ESC-Net (CVPR 2025) achieves open-vocabulary medical image segmentation by bridging CLIP's semantic space with SAM's segmentation decoder, entirely eliminating the need for human-provided prompts. The architecture comprises three stages.
Stage 1: Image–text correlation maps.
Given an input image and a text query (e.g., “polyp”), the CLIP image encoder and text encoder produce feature maps and embeddings, respectively. Let be the spatial feature map from an intermediate layer of the CLIP vision transformer, and be the text embedding. The correlation map is (CORR MAP) This produces a heatmap indicating regions of the image that are semantically aligned with the text query.
Stage 2: Pseudo-prompt generation.
Rather than requiring a human to click on the region of interest, ESC-Net converts the correlation map into a set of pseudo-prompts that SAM's decoder can consume. The top- locations in are extracted as point prompts: (Pseudo Prompts) with a threshold chosen to retain only high-confidence locations. Additionally, a bounding box prompt is derived as the tightest rectangle enclosing all points in , with a dilation margin : (Pseudo BOX)
Stage 3: SAM decoder with fused features.
The pseudo-prompts and bounding box are fed into SAM's prompt encoder alongside the image embedding from SAM's vision encoder. Crucially, ESC-Net fuses CLIP's semantic features with SAM's spatial features via a cross-attention module: (ESC Fusion) where is SAM's image embedding and is projected to compatible dimensions. The fused features are decoded by SAM's lightweight mask decoder to produce the final segmentation .
Example 26 (ESC-Net for Polyp Detection without Manual Prompts).
Consider a colonoscopy video frame and the text query “colorectal polyp.” The CLIP correlation map (Equation (CORR MAP)) produces high activation over a sessile polyp in the lower-right quadrant of the frame. Pseudo-prompt generation extracts point prompts clustered on the polyp surface and a tight bounding box with pixels of dilation. These are passed to SAM's decoder, which produces a mask achieving a Dice score of on this frame-comparable to the achieved by an expert gastroenterologist's manual annotation and significantly surpassing the obtained by SAM with a single centre-of-mass click prompt. Critically, the entire pipeline requires zero human interaction: the VLM provides the semantic grounding that SAM needs but cannot generate on its own, while SAM provides the pixel-precise segmentation that the VLM understands but cannot produce. On the Kvasir-SEG benchmark, ESC-Net achieves a mean Dice of across all polyp types, including flat and depressed polyps that are notoriously difficult for both automated and manual detection.
Automated Prompt Generation via Generative Models
ESC-Net leverages CLIP embeddings for prompt generation, but this is not the only route. A parallel line of work uses generative models themselves to produce the prompts that foundation segmenters require. The key insight is that a generative model trained on medical image–mask pairs implicitly learns where anatomical structures are located; this spatial knowledge can be distilled into prompts.
Definition 36 (Self-Prompting Pipeline).
A self-prompting pipeline is a two-stage system where:
The prompt generator maps an input image to a set of prompts (points, bounding boxes, or dense embeddings) without human intervention.
The foundation segmenter produces a segmentation mask given the image and prompts.
The pipeline is self-contained in the sense that no external input beyond the image is required at inference time: (SELF Prompting)
Diffusion-based prompt generation.
Consider a denoising diffusion model trained on medical images with associated segmentation masks. At inference, rather than generating a full image, we run the reverse process for only steps from a partially noised version of the input image. The intermediate activations of the U-Net at time step contain rich spatial information about anatomical structure. Following the observation that diffusion features encode semantic layout, we extract attention maps from the cross-attention layers: (DIFF ATTN) where and are the query and key matrices at layer and time step . These attention maps are aggregated across layers and time steps, thresholded, and converted into point and bounding box prompts via connected component analysis.
VAE-based prompt generation.
An alternative approach trains a variational autoencoder on pairs, where is a segmentation mask. The encoder maps images to a latent space that captures the location and extent of structures of interest. A lightweight decoder then produces prompt coordinates: (VAE Prompt) outputting point prompts and a bounding box. The entire system is trained end-to-end with a composite loss: (SELF Prompt LOSS) where denotes ground-truth prompts derived from mask (e.g., centroid points and tight bounding boxes), and is a smooth- localisation loss.
Iterative self-refinement.
Self-prompting pipelines can be made iterative. Let be the initial segmentation. The prompt generator can then be re-run on the composite input to produce refined prompts: (Iterative Refine) Empirically, convergence to a stable mask is typically achieved within rounds for organ segmentation tasks. This iterative scheme mirrors the clinical workflow where a radiologist refines an initial impression by re-examining the scan with updated hypotheses.
Taming SAM with Conditional VAEs
The Segment Anything Model (SAM) exhibits a well-documented sensitivity to prompt placement: shifting a point prompt by even a single pixel can produce dramatically different segmentation masks. In deterministic segmentation tasks-where a unique ground-truth mask exists-this sensitivity is a bug, introducing uncontrolled variance into predictions. However, for ambiguous segmentation tasks, where multiple valid interpretations exist (e.g., tumour boundary delineation, where different radiologists draw different contours), this sensitivity becomes a feature: it provides a natural mechanism for sampling diverse, plausible segmentations.
Insight.
SAM's biggest flaw-sensitivity to prompt placement-becomes its greatest strength when modelled probabilistically. A single SAM query with a fixed prompt returns one deterministic mask. But the space of masks reachable by varying the prompt over a small neighbourhood forms a rich distribution that captures genuine segmentation ambiguity. The problem is that this distribution is implicit: there is no closed-form expression for , where is an -ball around a nominal prompt location. A conditional VAE provides exactly the machinery to make this distribution explicit, tractable, and controllable.
The prompt–mask joint distribution.
Let denote a point prompt and the corresponding mask. The joint distribution over prompt locations and resulting masks, conditioned on image , is (Joint Prompt MASK) The first factor is deterministic (SAM's decoder is deterministic given a prompt), so all stochasticity comes from , the distribution over “reasonable” prompt locations. The marginal mask distribution is obtained by integrating out prompts: (Marginal MASK) This integral is intractable because is a complex, non-differentiable function (SAM's decoder).
The cVAE formulation (NeurIPS 2024).
The Taming SAM approach introduces a conditional VAE that models the joint distribution in Equation . Let be a latent variable. The generative model and inference network are: (Taming Prior) The decoder first predicts a prompt location from the latent code and image , then passes this prompt through SAM's frozen decoder to produce the mask . The Dirac delta in Equation encodes the fact that SAM is deterministic.
The training objective is the conditional ELBO: (Taming ELBO) where controls the trade-off between reconstruction quality and latent space regularity.
Proposition 9 (Taming SAM's Prompt Sensitivity).
Let denote SAM's deterministic mask decoder for image , and let be the prompt distribution learned by the cVAE decoder. Then:
Diversity: Sampling and decoding produces a set of masks whose pairwise Dice dissimilarity approximates the inter-annotator variability observed in multi-reader studies.
Controllability: The granularity of the sampled masks is monotonically related to the norm : small produces conservative (smaller) masks while large produces liberal (larger) masks, reflecting different levels of boundary inclusion.
Calibration: The pixel-wise entropy of the averaged prediction is a calibrated measure of segmentation uncertainty: the expected calibration error satisfies , where is a single-prompt prediction.
Proof.
(Sketch.) For part (1), note that the cVAE is trained on multi-annotator data where different readers produce different masks. The encoder maps each annotator's mask to a different region of latent space; the prior covers these regions, so samples from the prior naturally reproduce inter-annotator variation.
For part (2), the latent space is regularised to be Gaussian. The decoder learns to map the radial component to mask granularity because the KL penalty encourages this degree of freedom to align with the principal axis of variation in the data, which for boundary-ambiguous segmentation is mask size.
For part (3), the averaged prediction is a Monte Carlo estimate of . By the law of large numbers, as . Standard calibration theory then gives , and is better calibrated than any single sample by Jensen's inequality applied to proper scoring rules.
Practical considerations.
During training, SAM's image encoder and mask decoder are frozen; only the cVAE components (prior network, encoder, decoder) are trained. This makes the approach lightweight: the cVAE adds approximately parameters compared to SAM's , and training converges in under epochs on a single GPU. At inference, one samples latent codes, decodes each to a prompt, runs SAM times (the image encoding is cached and reused), and aggregates the resulting masks. With , this adds less than of wall-clock time per image on an A100 GPU.
ContourMS: Contour-Aware Multi-Expert Segmentation
Segmentation ambiguity in medical imaging is not merely about whether a pixel belongs to a structure but how the boundary is drawn. Different clinical experts bring different biases: radiation oncologists tend to include larger margins for safety, while diagnostic radiologists favour tight contours for measurement accuracy. The ContourMS framework explicitly models this multi-expert structure through a coarse-to-fine pipeline that separates the problems of approximate localisation, expert-style encoding, and boundary refinement.
Architecture overview.
ContourMS comprises three networks operating in sequence:
SegmentNet : A standard encoder–decoder (e.g., U-Net or nnU-Net) that produces an initial coarse segmentation mask and extracts the initial contour as the zero-level set of the signed distance function of .
LatentNet : A conditional VAE whose encoder maps the image and a specific expert's ground-truth mask to a latent code , capturing that expert's annotation style: (Latentnet) At inference, sampling yields different expert styles without access to any expert's ground truth.
ContourNet : A deformation network that takes the initial contour , the image features, and the expert-style latent , and produces a per-vertex displacement field: (Contournet)
Training objective.
The full ContourMS loss combines segmentation quality, contour accuracy, expert-style fidelity, and latent regularisation: (Contourms LOSS) where is the Chamfer distance between the predicted and ground-truth expert contours, measuring boundary fidelity.
Inference with diverse expert samples.
At test time, multiple contours are generated by sampling different latent codes: for . The resulting contours approximate the distribution of expert opinions. The mean contour provides a consensus segmentation, while the spread of contours quantifies annotation uncertainty-a critical metric for treatment planning in radiation oncology.
Noise-Consistent Siamese-Diffusion
A fundamental challenge in using diffusion models for data augmentation is maintaining consistency between generated images and their corresponding segmentation masks. Na\"vely generating an image with one diffusion model and a mask with another-or generating them independently-results in spatial misalignment: the synthesised tumour in the image may not correspond to the tumour region in the synthesised mask.
The Siamese-diffusion architecture (CVPR 2025).
Noise-Consistent Siamese-Diffusion addresses this by training two diffusion models that share noise schedules and are coupled through a consistency mechanism. Let and denote the image and mask diffusion models, respectively. The forward process corrupts both with the same noise realisation: (Siamese IMG FWD) where is shared between the two processes. This shared noise ensures that spatial structure is corrupted and recovered in a correlated fashion.
Cross-attention coupling.
During denoising, intermediate features from the image branch are injected into the mask branch via cross-attention, and vice versa: (Siamese IMG Denoise) where and are intermediate feature maps from the respective U-Nets, and prevents gradient flow between the two branches (each is trained with its own denoising objective).
Anatomical consistency loss.
Beyond shared noise, an explicit consistency loss penalises spatial misalignment between generated images and masks. Let and be the predicted clean image and mask at time step . The consistency loss is: (Consistency LOSS) where denotes the spatial gradient operator and is element-wise multiplication. The first term encourages the image to have low gradients outside the mask (background smoothness), and the second aligns mask edges with image edges within the foreground region.
Data augmentation via paired generation.
At inference, new training pairs are generated by sampling shared noise and running both diffusion models in parallel through the full reverse process. The shared noise and cross-attention coupling ensure that the generated image and mask are anatomically consistent. These pairs are then used to augment the training set of a downstream segmentation model, with the augmentation ratio typically set to : (synthetic to real).
The Complete Pipeline
The individual components surveyed throughout this chapter-diffusion models for data synthesis, foundation models for zero-shot segmentation, VLMs for semantic understanding, conditional VAEs for uncertainty modelling-have so far been presented as standalone contributions. This section unifies them into complete pipelines that address the full clinical workflow from raw scan to diagnostic output.
From Scan to Diagnosis: An End-to-End Generative Pipeline
The vision that motivates this section is ambitious but increasingly realisable: a patient's medical scan is acquired, a VLM understands its clinical context, generates appropriate text prompts, a foundation model segments the relevant anatomy, a diffusion model refines the segmentation and samples alternative interpretations, and a VLM generates a structured clinical report with calibrated uncertainty estimates-all without human intervention at the segmentation stage.
Pipeline stages.
The complete pipeline comprises five stages, each handled by a specialised model:
Contextual understanding (VLM): A medical VLM (e.g., Med-PaLM M or LLaVA-Med) receives the scan and patient metadata (age, clinical indication, imaging modality) and generates a structured context description: (VLM Context)
Prompt synthesis (VLM Prompt Generator): The context description is converted into segmentation prompts via the self-prompting pipeline of Section Automated Prompt Generation via Generative Models: (Prompt Synth)
Foundation segmentation (SAM): The prompts are fed to SAM (or a medical variant such as MedSAM, SAM-Med2D) to produce an initial segmentation: (SAM SEG)
Generative refinement (Diffusion + cVAE): The initial segmentation is refined by a conditional diffusion model that corrects boundary errors and, optionally, samples alternative masks via the cVAE mechanism of Section Taming SAM with Conditional VAEs: (Diffusion Refine)
Report generation (VLM): A medical report VLM receives the image, the segmentation samples, and derived measurements (volume, longest diameter, Hounsfield unit statistics within the segmented region) and generates a structured report with uncertainty quantification: (Report GEN)
Example 27 (Complete Pipeline for Breast Tumour Segmentation).
Consider a contrast-enhanced breast MRI scan of a 48-year-old woman with a suspicious finding on screening mammography. The pipeline operates as follows:
Stage 1 (Context): The medical VLM receives the MRI volume (T1-weighted post-contrast sequence, voxels) and metadata (age 48, BIRADS-4 on mammography). It generates the context: “Post-contrast breast MRI, suspected BIRADS-4 lesion, likely solid mass in upper outer quadrant of left breast. Key features to assess: enhancement pattern, margins, size.”
Stage 2 (Prompts): The self-prompting module processes the context and identifies the enhancing region. Using the diffusion-based prompt generator, it produces point prompts on the enhancing mass and a bounding box of voxels.
Stage 3 (Segmentation): MedSAM processes each axial slice with the projected 2D prompts, producing an initial 3D segmentation with Dice compared to expert annotation.
Stage 4 (Refinement): The conditional diffusion model refines boundary details, particularly along the posterior margin where the mass abuts the pectoral muscle. With samples, the mean Dice improves to , and the boundary uncertainty map correctly highlights the posterior margin as the region of highest ambiguity (pixel-wise entropy ).
Stage 5 (Report): The VLM generates: “Segmentation identifies a ,cm enhancing mass in the left breast, upper outer quadrant. Irregular margins with spiculations anteriorly. Volume: ,mL (95% CI from 16 segmentation samples). Posterior margin poorly defined with high segmentation uncertainty (entropy ), suggesting possible chest wall involvement-recommend dedicated chest wall protocol. BIRADS-5: Highly suggestive of malignancy.”
The entire pipeline executes in seconds on a single A100 GPU, with the diffusion refinement stage consuming seconds (66% of total inference time).
Generative Medical Segmentation (GMS) Framework
While the complete pipeline of Section From Scan to Diagnosis: An End-to-End Generative Pipeline composes multiple specialist models, the Generative Medical Segmentation (GMS) framework takes a different approach: it uses a single generative model, specifically a pre-trained vision foundation model, as the backbone for segmentation, with a lightweight learnable mapping in latent space.
Key insight.
Pre-trained vision foundation models (e.g., DINOv2, SAM's image encoder, or diffusion U-Net features) learn representations that capture rich spatial and semantic structure. GMS exploits this by not training a full segmentation network from scratch. Instead, it freezes the foundation model's encoder and trains only a compact latent-space network that maps foundation features to segmentation masks.
Architecture.
Let be the frozen feature extractor from a vision foundation model. The GMS framework consists of:
A feature projector that adapts the foundation features to the medical domain (a single convolution layer with ).
A latent segmentation head comprising a lightweight decoder (two transposed convolution layers and a sigmoid output) that predicts per-class segmentation probabilities.
The full model is: (GMS) with only and being trainable. The number of trainable parameters is typically , compared to for a standard U-Net and for nnU-Net with large encoders.
Why “generative”?
The framework earns the “generative” label because the pre-trained features were learned through a generative objective (e.g., masked image modelling in MAE, self-distillation in DINO, or denoising in diffusion models). These generative pre-training objectives force the encoder to learn representations that capture the full data distribution, not just discriminative features for a fixed set of classes. This distributional richness is what enables the lightweight decoder to generalise across diverse medical imaging tasks.
Performance characteristics.
On a benchmark of 12 medical image segmentation tasks spanning CT, MRI, and endoscopy, GMS with a frozen DINOv2 backbone and trainable parameters achieves:
Mean Dice , compared to for a fully trained U-Net with parameters.
Mean Dice , compared to for nnU-Net with parameters (a difference within the standard error).
Training time: minutes per task on a single GPU, compared to hours for nnU-Net.
Data efficiency: with only of training data, GMS achieves mean Dice compared to for U-Net and for nnU-Net, demonstrating superior few-shot performance due to the pre-trained representations.
Remark 34.
The parameter efficiency of GMS is striking: it achieves competitive performance with fewer trainable parameters than a standard U-Net. This efficiency has profound implications for medical imaging, where annotated data is scarce and computational resources at deployment sites (hospitals, clinics) are often limited. A model with fewer than trainable parameters can be fine-tuned on a clinician's laptop and deployed on edge devices, democratising access to AI-assisted segmentation.
GenSeg: Generate-What-Improves-the-Segmentor
All data augmentation methods face a fundamental question: which synthetic data is actually useful? Generating more data is easy; generating data that improves the downstream task is hard. Most augmentation strategies are task-agnostic: they generate data without considering how the downstream model will use it. GenSeg (Nature Communications, 2025) introduces task-coupled generation, where the generator is explicitly optimised to produce data that maximises the segmentor's performance.
Definition 37 (Task-Coupled Generation (GenSeg Paradigm)).
A task-coupled generation framework consists of:
A generator that maps latent codes to image–mask pairs .
A task model (the segmentor) trained on both real and generated data.
A multi-level optimisation coupling the two: (Genseg Outer)
The generator's parameters are optimised in an outer loop to minimise the segmentor's validation loss, while the segmentor's parameters are optimised in an inner loop on the union of real data and generated data . The generator thus learns to produce exactly the data the segmentor needs most.
This is a bi-level optimisation problem: the inner optimisation (training the segmentor) is nested inside the outer optimisation (training the generator). The gradient of the outer objective with respect to flows through the inner optimisation: (Genseg GRAD) where is the implicit gradient of the inner optimisation solution with respect to the generator parameters.
Practical implementation.
Computing the exact implicit gradient in Equation requires differentiating through the entire inner optimisation trajectory, which is computationally prohibitive. GenSeg uses a first-order approximation: rather than running the inner loop to convergence, it performs gradient steps on the segmentor and uses the resulting as a proxy for . The outer gradient is then: (Genseg Approx) where is the inner learning rate. In practice, inner steps suffice, and the Hessian–vector products are computed efficiently via automatic differentiation without materialising the full Hessian.
Theorem 4 (GenSeg Convergence under Multi-Level Optimisation).
Let be the outer objective in the GenSeg bi-level optimisation (Equations (Genseg Outer)–(Genseg Outer)), where denotes the minimiser of the inner problem. Assume:
- (A1)
The inner loss is -strongly convex in for each .
- (A2)
The outer loss is -smooth.
- (A3)
The cross-derivative is bounded in spectral norm by .
- (A4)
The inner loop runs for gradient descent steps with learning rate , where is the smoothness constant of the inner loss.
- (A5)
The outer loop uses learning rate with stochastic gradient estimates of variance .
Then after outer iterations, the expected gradient norm satisfies: (Genseg Convergence) where is the infimum of the outer objective. The three terms represent, respectively, the optimisation error (decreasing with ), the stochastic gradient noise floor, and the inner-loop approximation error (decreasing exponentially with ).
Proof.
The proof proceeds in three steps.
Step 1: Inner-loop approximation error. Since is -strongly convex (A1) and -smooth, gradient descent with converges linearly: (Inner Converge)
Step 2: Gradient estimation error. The approximate outer gradient using instead of introduces a bias. By the chain rule and smoothness of (A2): (GRAD BIAS) By the implicit function theorem, , which has norm bounded by using (A1) and (A3). The difference between -step and exact implicit derivatives is bounded by .
Step 3: Outer-loop convergence. Applying standard analysis for SGD on -smooth functions with biased, noisy gradients yields: (Final Bound) where , completing the proof.
Remark 35.
The bound in Equation has an elegant interpretation. The first term is the standard optimisation convergence rate . The second term is the irreducible noise floor from stochastic gradient estimation. The third term-the novel contribution-is the price of approximate inner-loop solving: using inner steps instead of solving to convergence introduces an exponentially decaying error. For and typical values , the inner-loop error is , which is already small. Increasing to reduces it to . In practice, provides an excellent trade-off between computational cost and approximation quality.
Example 28 (GenSeg with 10 Annotated Training Images).
On the ACDC cardiac segmentation benchmark (4 classes: left ventricle, right ventricle, myocardium, background), GenSeg is evaluated in an ultra-low-data regime with only annotated images. The experimental setup is as follows:
Generator: A conditional diffusion model pre-trained on unlabelled cardiac MRI (readily available) and fine-tuned to generate paired image–mask samples conditioned on class layout maps.
Segmentor: A standard 2D U-Net trained from scratch.
Baselines:
U-Net trained on 10 images only: Dice .
U-Net with standard augmentation (rotation, flipping, elastic deformation): Dice .
U-Net with task-agnostic diffusion augmentation (generate 200 synthetic pairs, no feedback): Dice .
U-Net with GenSeg (task-coupled, inner steps, outer iterations): Dice .
Analysis: GenSeg improves over task-agnostic augmentation by Dice, a substantial margin that demonstrates the value of task-coupled generation. Inspection of the generated samples reveals that GenSeg learns to synthesise images with challenging characteristics that the segmentor currently handles poorly: small right ventricle cases, unusual myocardial thickness, and artefact-corrupted slices. In contrast, task-agnostic generation produces “average” samples that are easy for the segmentor and provide little training signal. After 100 outer iterations, the generator has learned a curriculum that mirrors expert-designed hard example mining, but without any manual specification of what “hard” means.
Towards Universal Medical Segmentation
The preceding sections have presented individual components and specific pipelines. We now step back to articulate the emerging vision of universal medical segmentation: a single, unified framework that combines foundation models, generative augmentation, VLM reasoning, and probabilistic outputs to segment any anatomical structure in any imaging modality, with calibrated uncertainty and natural language explanations.
The four pillars.
A universal medical segmentation system rests on four pillars:
Foundation segmentation backbone. A large-scale model (SAM, MedSAM, or a successor) pre-trained on billions of image–mask pairs provides the spatial reasoning backbone. This model is never fine-tuned on individual tasks; instead, it is prompted by other components.
Generative data engine. A task-coupled generator (Section GenSeg: Generate-What-Improves-the-Segmentor) continuously synthesises training data for the lightweight adapter layers that bridge the foundation backbone to specific tasks. This engine operates in a closed loop: it monitors the system's failure modes and generates targeted augmentation data.
VLM semantic interface. A medical VLM provides the bridge between clinical concepts and the segmentation system. It translates natural language queries (“segment the hepatocellular carcinoma”) into prompts, interprets segmentation results in clinical context, and generates reports.
Probabilistic output layer. Rather than producing a single deterministic mask, the system outputs a distribution over segmentations, implemented via the cVAE mechanism of Section Taming SAM with Conditional VAEs or ensemble methods. This distribution captures both aleatoric uncertainty (genuine ambiguity in the anatomy) and epistemic uncertainty (the model's lack of knowledge about rare conditions).
Formal specification.
Let denote the set of all imaging modalities (CT, MRI with all sequences, ultrasound, X-ray, endoscopy, etc.), the set of all anatomical structures, and the space of natural language descriptions. A universal medical segmentation system is a mapping: (Universal) where is the union of image spaces across modalities, denotes a probability distribution over binary masks, and the second factor is the space of natural language outputs (reports, explanations). Given a scan and a query , the system produces: (Universal Output) where is a distribution over segmentation masks and is a natural language report.
Challenges towards universality.
Several open challenges remain on the path to true universality:
Cross-modality representation alignment. Foundation models pre-trained on natural images learn representations that may not transfer optimally to all medical modalities. Ultrasound, with its speckle noise and operator-dependent image quality, remains particularly challenging. Pre-training on large-scale multi-modal medical datasets is essential but hampered by data sharing restrictions.
Compositional understanding. Clinical queries can be compositional: “segment the largest metastasis in the right lobe of the liver that shows arterial enhancement.” This requires the VLM to decompose the query into sub-tasks (identify liver identify right lobe identify metastases filter by size filter by enhancement pattern) and orchestrate the segmentation backbone accordingly.
Calibrated uncertainty under distribution shift. The probabilistic output layer must remain calibrated not just on in-distribution data but also when encountering novel pathologies, rare anatomical variants, or imaging artefacts. This is an active area of research at the intersection of generative modelling and robust statistics.
Regulatory and ethical considerations. A universal system must be transparent about its limitations. When the system encounters a scan outside its competence (e.g., an ultra-rare disease), it should abstain rather than produce a confident but incorrect segmentation. Implementing reliable abstention mechanisms within a generative framework-where the model can always produce something-is a non-trivial design challenge.
Caution.
The gap between research benchmarks and clinical deployment. While the components described in this section achieve impressive results on research benchmarks, deploying a universal medical segmentation system in clinical practice requires addressing additional challenges: integration with hospital PACS/RIS systems, compliance with medical device regulations (FDA 510(k), CE marking), handling of edge cases where the system should defer to human experts, and ongoing monitoring for performance degradation as imaging protocols evolve. No current system fully addresses all these requirements. The vision articulated here is a research direction, not a finished product.
Exercises
Exercise 29 (Self-Prompting with Diffusion Features).
Consider a self-prompting pipeline where a diffusion model's intermediate features are used to generate point prompts for SAM.
- (a)
Let be the aggregated attention map at layer and time step (Equation (DIFF ATTN)). Define the multi-scale aggregated attention as where is a set of selected layers and bilinearly interpolates to a common resolution. Derive the time-averaged map and show that if attention maps across time steps are i.i.d. with mean and variance , the variance of at each pixel is .
- (b)
Design a criterion for selecting the threshold that maximises the expected IoU between the thresholded attention region and the ground-truth mask. Show that the optimal threshold under a Gaussian pixel-value model is related to the ratio of foreground to background prior probabilities.
- (c)
Discuss the failure modes of diffusion-based prompt generation when applied to structures with low contrast (e.g., pancreatic tumours on non-contrast CT). How might you augment the attention maps with edge-detection features to improve robustness?
Exercise 30 (Bi-Level Optimisation in GenSeg).
Consider the GenSeg bi-level optimisation in Equations (Genseg Outer)–(Genseg Outer).
- (a)
Suppose the inner loss is , where produces image–mask pairs. Derive the implicit gradient using the implicit function theorem, and show that it requires computing .
- (b)
Prove that the first-order approximation used in GenSeg (taking inner gradient steps and differentiating through them) recovers the exact implicit gradient in the limit when the inner problem is strongly convex.
- (c)
In the GenSeg convergence theorem (Theorem Theorem 4), determine the optimal choice of (number of inner steps) and (outer learning rate) as functions of (total outer iterations) to minimise the right-hand side of Equation . What is the resulting convergence rate?
Exercise 31 (Contour Deformation as Diffeomorphism).
In the ContourMS framework (Section ContourMS: Contour-Aware Multi-Expert Segmentation), the ContourNet produces a displacement field that deforms the initial contour.
- (a)
To ensure that the deformed contour remains a valid (non-self-intersecting) closed curve, we require the displacement field to be a diffeomorphism. A sufficient condition is that is the time-1 flow of a smooth velocity field : Show that if is Lipschitz continuous with constant , then is a diffeomorphism and the Jacobian determinant satisfies .
- (b)
Propose a regularisation loss for ContourNet that penalises non-diffeomorphic deformations. How does this relate to the smoothness of the generated expert contours?
- (c)
Given expert annotators with latent codes , define a consensus contour as . Under what conditions on the displacement fields is the consensus contour guaranteed to be non-self-intersecting? Provide a counter-example showing that averaging arbitrary non-self-intersecting contours can produce a self-intersecting result.
Clinical Translation Challenges
The preceding sections developed a rich mathematical toolkit: diffusion-based segmentation, prompt-driven foundation models, uncertainty quantification, and multi-modal fusion. Every one of these methods achieves impressive Dice scores on curated benchmarks. Yet remarkably few have been deployed in clinical practice. The gap between a paper reporting 92% Dice on BraTS and a system that a neurosurgeon trusts intraoperatively is not a gap of accuracy. It is a gap of trust, fairness, accessibility, and regulatory clarity.
Key Idea.
Clinical translation requires not just accuracy, but trust, fairness, and accessibility. A segmentation model that achieves state-of-the-art performance on a benchmark dataset may still be undeployable in practice if it (a) requires hardware that most hospitals cannot afford, (b) cannot explain its decisions to clinicians, (c) performs systematically worse on underrepresented patient populations, or (d) lacks regulatory approval. The path from laboratory to bedside is paved not with higher Dice scores but with solutions to these sociotechnical challenges. Formally, let be a clinical utility function that maps a model to a deployment decision. Then (Clinical Utility) where , , , and denote accuracy, fairness, computational cost, and regulatory approval respectively, and are institution-specific thresholds. Most research optimises only the first term.
This section confronts each of these barriers in turn: computational cost (Computational Overhead and Hardware Stratification), privacy-preserving training (Federated Learning for Privacy-Preserving Segmentation), interpretability (Interpretability of Diffused Attention), regulatory approval (Regulatory Challenges), algorithmic fairness (Algorithmic Fairness in Medical Segmentation), and dataset bias (Dataset Bias and Generalisation).
Computational Overhead and Hardware Stratification
Foundation models for medical segmentation demand extraordinary compute. Medical SAM 2, a recent adaptation of the Segment Anything Model to volumetric medical data, was reported to require approximately 5120,GB of VRAM for full fine-tuning on 3D volumes (Zhu et al., 2024). Even inference-time requirements are formidable: diffusion-based segmentation models that perform 100 or more denoising steps on a volume can consume 40–80,GB of GPU memory per patient.
The computational budget of a segmentation pipeline can be decomposed as follows. Let denote the number of diffusion steps, the number of channels at the bottleneck resolution, the spatial resolution of the volume (voxels per dimension), and the batch size. The peak memory footprint scales as (Memory Scaling) where accounts for activation checkpointing, optimizer states, and gradient accumulation buffers. For a typical 3D medical diffusion model with , , , and (mixed-precision training with AdamW), this yields memory requirements measured in hundreds of gigabytes.
Parameter-efficient alternatives.
The prohibitive cost of full fine-tuning has motivated parameter-efficient fine-tuning (PEFT) strategies. Low-Rank Adaptation (LoRA) (Hu et al., 2022) freezes the pre-trained weights and learns a low-rank update with , , and rank . The number of trainable parameters drops from to , a reduction of . For a model with and , this represents a reduction. Adapter layers insert small bottleneck modules into each transformer block: (Adapter) where , , and is a nonlinearity. Medical adaptations of these techniques have shown that LoRA fine-tuning of SAM can recover 95–98% of full fine-tuning performance while reducing GPU memory by –.
The GPU access gap.
The most concerning implication is not technical but societal. Training and deploying state-of-the-art medical segmentation models requires hardware that is economically inaccessible to most healthcare institutions worldwide. A single NVIDIA A100 80,GB GPU costs approximately $15,000; a cluster of 64 such GPUs, needed for training large foundation models, represents a capital expenditure exceeding $1,000,000 before accounting for networking, storage, cooling, and operational costs.
Caution.
The GPU access gap threatens to make medical AI a privilege of wealthy institutions. If state-of-the-art medical segmentation requires 8A100 GPUs for inference or 64A100 GPUs for adaptation, then the institutions that benefit are precisely those that least need help: well-funded academic medical centres and hospitals in high-income countries. Rural hospitals in sub-Saharan Africa, community clinics in Southeast Asia, and under-resourced facilities in low-income nations, the institutions where AI-assisted diagnostics could save the most lives, are locked out by hardware costs alone. This creates a feedback loop: wealthy institutions deploy better models, attract more patients and funding, and pull further ahead, while under-resourced institutions fall further behind. Any responsible research agenda for medical AI must include model compression, knowledge distillation, and edge deployment as first-class research objectives, not afterthoughts.
Knowledge distillation for edge deployment.
One promising approach is to distill the large foundation model into a smaller student network suitable for edge hardware. Let be the teacher (foundation model) and the student. The distillation loss combines task supervision with feature alignment: (Distillation) where extracts the feature map at layer and controls the alignment strength. Recent work has demonstrated that student networks with fewer parameters can retain 90–95% of the teacher's segmentation accuracy, bringing deployment within reach of consumer-grade GPUs.
Federated Learning for Privacy-Preserving Segmentation
Medical images are among the most sensitive forms of personal data. A brain MRI can reveal neurological conditions, psychiatric disorders, and even aspects of personal identity. A chest CT scan encodes information about smoking history, occupational exposures, and incidental findings. Sharing such data across institutions, even for the noble purpose of training better AI models, raises profound privacy concerns and is tightly regulated by frameworks such as HIPAA (United States), GDPR (European Union), and PIPEDA (Canada).
Definition 38 (Federated Learning for Medical Imaging).
Let denote hospitals, each holding a private dataset of medical images and corresponding segmentation masks . Federated learning (FL) trains a shared global model by iterating the following protocol:
Broadcast: The server sends the current global parameters to all participating hospitals.
Local training: Each hospital performs epochs of local optimisation: (Local Update) where is the local segmentation loss.
Aggregation: The server computes a weighted average of the local updates: (Fedavg)
No raw patient data ever leaves hospital . Only model parameters or gradients are transmitted.
The Federated Averaging (FedAvg) algorithm (McMahan et al., 2017) instantiates this protocol and remains the most widely used baseline. However, applying federated learning to diffusion-based segmentation models introduces unique challenges.
Communication costs of diffusion gradients.
A diffusion-based segmentation model such as a conditional U-Net with parameters requires transmitting floating-point numbers per communication round. For a model with million parameters in 32-bit precision, each round requires transmitting approximately 2,GB per hospital. With hospitals and communication rounds, the total communication volume is (COMM COST) where the factor of 2 accounts for both upload (local to server) and download (server to local). This is prohibitive for hospitals with limited network bandwidth, which is common in low-resource settings.
Gradient compression.
Communication-efficient FL methods reduce this burden through gradient compression. Sparse communication transmits only the top- gradient components: (TOPK) where is the sparsity ratio (e.g., transmits only 1% of gradients). Quantisation reduces each gradient component from 32 bits to 1–8 bits. LoRA-based federated learning transmits only the low-rank updates , reducing communication by as in the centralised setting.
Cross-centre domain shift.
Perhaps the most insidious challenge is heterogeneous data distributions across hospitals. Hospital may use a Siemens 3T MRI scanner, while uses a GE 1.5T scanner. The resulting distribution shift, , means that the global model may be far from optimal for any individual hospital. In the federated optimisation landscape, this manifests as conflicting gradient directions: (Gradient Conflict) causing the global update to oscillate rather than converge. FedProx (Li et al., 2020) mitigates this by adding a proximal term to each local objective, preventing local models from drifting too far from the global consensus.
Insight.
Federated learning + generative augmentation may solve both privacy and data scarcity simultaneously. Consider a federated protocol in which each hospital not only trains on its local data but also uses a local generative model to synthesise additional training examples . The augmented local dataset improves local model quality, and the federated aggregation then combines these improvements across all hospitals. Crucially, the synthetic data is generated locally and never shared, preserving privacy. This combines the privacy guarantees of federated learning with the data efficiency of generative augmentation, addressing two fundamental challenges simultaneously. Formally, the augmented local objective becomes (FED AUG) where is the number of synthetic samples and .
Example 29 (Federated Brain Tumour Segmentation Across Five Hospitals).
Consider a consortium of five hospitals collaborating on glioblastoma segmentation:
Hospital A (academic medical centre, USA): 800 patients, Siemens 3T Prisma, T1, T1-Gd, T2, FLAIR sequences. High-quality expert annotations by neuroradiologists.
Hospital B (regional hospital, Germany): 350 patients, Philips 3T Ingenia, same four sequences but with different pulse parameters. Annotations by radiology residents, reviewed by a single attending.
Hospital C (teaching hospital, India): 200 patients, GE 1.5T Signa, only T1-Gd and FLAIR available. Limited annotation resources: only whole-tumour labels, no sub-region delineation.
Hospital D (children's hospital, Japan): 150 patients, predominantly paediatric cases (ages 3–17). Siemens 3T Vida. Full multi-sequence and multi-label annotations.
Hospital E (rural clinic, Kenya): 75 patients, refurbished GE 1.5T scanner. T1 and FLAIR only. Annotations by a general radiologist with limited neuro-oncology training.
A naive approach of pooling all 1,575 patients would yield a strong centralised model but is prohibited by HIPAA, GDPR, Kenya's Data Protection Act, and Japan's APPI. Federated learning enables collaboration without data sharing.
Results. After 200 communication rounds of FedAvg with local LoRA adaptation (rank ), the global model achieves:
| Setting | Mean Dice | Worst-Site Dice |
| Hospital A only (centralised) | 0.89 | - |
| Each hospital alone (isolated) | 0.58 | |
| FedAvg (no augmentation) | 0.84 | 0.74 |
| FedAvg + local generative aug. | 0.87 | 0.81 |
Interpretability of Diffused Attention
A clinician presented with a segmentation mask produced by a deterministic U-Net can, in principle, trace the model's decision back through its layers: which features activated, which skip connections contributed, which input regions had the highest gradient attribution. The explanation may be imperfect, but the computational graph is deterministic and fixed.
Diffusion-based segmentation models shatter this paradigm. The segmentation mask is the output of a stochastic Markov chain: (Stochastic Chain) where is pure noise, each is sampled from , is the conditioning image, and the final is interpreted as the segmentation mask. Every run of this chain produces a different mask, even for the same input.
This stochasticity has two consequences for interpretability:
Non-reproducibility of explanations.
If we apply a gradient-based attribution method (e.g., Grad-CAM, integrated gradients) to one run of the chain, the attribution map reflects the specific noise trajectory that was sampled. A second run with different noise produces a different attribution map , even though both runs may produce nearly identical segmentation masks. The explanation is not a property of the model alone but of the model-noise pair.
Boundary hallucination.
In a diffusion segmentation model, the precise location of a segmentation boundary is iteratively constructed over denoising steps. At step , the boundary does not exist; at step , a coarse boundary has formed; at step 0, the boundary is sharp. There is no single step at which the model “decides” where the boundary lies. In a very real sense, the boundary was iteratively hallucinated from noise.
Ensemble-based explanations.
One mitigation is to aggregate explanations across stochastic runs. The expected attribution map is (Ensemble Attribution) where is the attribution map from the -th run and indexes spatial locations. Regions with high are regions where the model's “reasoning” is unstable across noise realisations, precisely the regions a clinician should examine most carefully. This transforms a weakness (stochastic explanations) into a strength (uncertainty over explanations identifies ambiguous regions).
Regulatory Challenges
Caution.
Regulatory approval for generative medical AI is uncharted territory. As of 2025, no purely generative AI segmentation system has received FDA clearance through the 510(k) pathway or De Novo classification. The FDA has cleared over 800 AI/ML-enabled medical devices, nearly all of which are deterministic: given the same input, they produce the same output. A diffusion model that produces a different segmentation mask each time it is run fundamentally challenges the regulatory framework, which assumes that a device's performance can be characterised by fixed test-set metrics. How does one validate a device whose output is a probability distribution over masks rather than a single mask? This question remains open, and its resolution will shape the future of generative medical AI.
The FDA 510(k) and De Novo pathways.
The 510(k) pathway requires demonstrating “substantial equivalence” to a legally marketed predicate device. For deterministic segmentation software, the predicate is typically a previously cleared AI/ML device with similar intended use. For a generative (stochastic) segmentation model, no predicate exists, making the 510(k) pathway difficult. The De Novo pathway, designed for novel devices of low-to-moderate risk that lack predicates, may be more appropriate. Under De Novo, the manufacturer must propose performance criteria and demonstrate that the device meets them.
For a stochastic segmentation model, appropriate performance criteria might include:
Mean performance: The expected Dice score exceeds a clinically meaningful threshold .
Worst-case performance: The -quantile of the Dice score distribution exceeds for specified tolerance : (Regulatory Quantile)
Calibration: The predicted uncertainty (variance across samples) is well-calibrated with respect to actual errors.
Subgroup equity: Performance criteria are met for all pre-specified demographic subgroups.
CE marking in the European Union.
Under the EU Medical Device Regulation (MDR 2017/745), AI-based segmentation software is classified as a medical device, typically Class IIa or IIb depending on the clinical context. The MDR requires a clinical evaluation demonstrating the device's safety and performance in the intended clinical setting. For generative models, the MDR's requirement for “transparency” of algorithmic decision-making (Article 61) is particularly challenging: how does one provide transparency for a 100-step stochastic Markov chain?
Algorithmic transparency requirements.
Both the FDA's Proposed Regulatory Framework for Modifications to AI/ML-Based Software as a Medical Device (2019) and the EU AI Act (2024) emphasise the need for algorithmic transparency. For diffusion models, this might require:
Documentation of the noise schedule and its effect on output variability.
Characterisation of the output distribution through statistical summaries (mean, variance, quantiles) computed over a representative test set.
Disclosure of training data provenance, including the number of institutions, patient demographics, and scanner types represented.
Specification of the sampling algorithm (DDPM, DDIM, DPM-Solver) and the number of steps used at inference time.
Pre-market validation.
Regulatory bodies require pre-market validation on data that is independent of the training and development data. For federated models trained across multiple institutions, this raises the question of whether a held-out site (rather than merely held-out patients within participating sites) should serve as the validation set. Site-level hold-out is more conservative but provides stronger evidence of generalisability.
Algorithmic Fairness in Medical Segmentation
Definition 39 (Algorithmic Fairness in Segmentation).
Let be a segmentation model, let be a function mapping each input to a sensitive attribute (e.g., on the Fitzpatrick scale), and let denote a performance metric evaluated on the subgroup . The model satisfies -group fairness if (Group Fairness) The model satisfies -minimax fairness if (Minimax Fairness) In words, group fairness bounds the disparity between the best- and worst-served groups, while minimax fairness places a floor on the worst-group performance.
Sources of unfairness.
Performance disparities in medical segmentation arise from multiple sources:
Representation bias: Training datasets over-represent certain demographics. If 80% of training images come from patients with Fitzpatrick skin types I–III, the model optimises for lighter skin and underperforms on types IV–VI.
Label bias: Expert annotators may draw boundaries less accurately on unfamiliar anatomies (e.g., cardiac structures in obese patients, where image quality is degraded by body habitus).
Scanner bias: If hospitals serving different demographic populations use different scanner brands, the model may learn scanner-specific shortcuts that correlate with demographics.
Biological variation: Anatomical variation across demographics (e.g., breast tissue density varies systematically with age and ethnicity) may cause the model to perform differently on different populations, even in the absence of any data bias.
Distribution-aware fairness learning.
Recent work on distribution-aware fairness (ICML 2025) proposes learning a reweighting function that adjusts the training loss to equalise performance across groups: (Fairness Reweight) where the weights are inversely proportional to current group performance: groups on which the model performs poorly receive higher weight. The weights are updated dynamically during training, creating an adversarial game between the model (which tries to improve performance) and the reweighting mechanism (which constantly shifts emphasis to the worst-performing group). This can be viewed as an instance of distributionally robust optimisation (DRO), where the uncertainty set is defined over demographic groups rather than input distributions.
Example 30 (Fairness Audit Revealing Skin-Tone Bias in Dermatology Segmentation).
A state-of-the-art diffusion-based segmentation model for melanoma boundary delineation was trained on the ISIC 2020 dataset, which contains 33,126 dermoscopic images. A post-hoc fairness audit stratified performance by Fitzpatrick skin type:
| Skin Type | Dice Score | (test set) |
| Type I (very fair) | 842 | |
| Type II (fair) | 1,203 | |
| Type III (medium) | 674 | |
| Type IV (olive) | 189 | |
| Type V (brown) | 73 | |
| Type VI (dark) | 31 |
The root cause is stark: the test set contains images of Type I but only images of Type VI, a representation gap that directly reflects the composition of the training set. After applying distribution-aware fairness learning with dynamically reweighted losses, the re-trained model achieves:
| Skin Type | Before | After DRO |
| Type I | 0.91 | 0.89 |
| Type VI | 0.71 | 0.82 |
| Gap | 0.20 | 0.07 |
Dataset Bias and Generalisation
The generalisation problem in medical imaging is more severe than in natural image segmentation. A model trained on ImageNet transfers reasonably well to other natural image datasets because the domain shift is relatively small: lighting, viewpoint, and camera vary, but the underlying statistics of natural images are broadly similar. Medical imaging exhibits far larger domain shifts because every parameter of the acquisition process, scanner manufacturer, field strength, pulse sequence, reconstruction algorithm, patient positioning, and contrast agent protocol, affects the image statistics.
The generalisation gap.
Let denote the source domain (training hospital) and the target domain (deployment hospital). The generalisation gap is (GEN GAP) Empirically, for medical segmentation models ranges from 5 to 25 Dice points, depending on the severity of the domain shift. A model trained at a single institution on 3T MRI may lose 15 Dice points when deployed at a different institution using 1.5T MRI, rendering it clinically unusable.
Scanner-specific artefacts.
Different scanner manufacturers produce subtly different image statistics. Siemens, GE, and Philips MRI scanners use different gradient coil designs, RF pulse sequences, and image reconstruction algorithms. These produce characteristic artefacts: Gibbs ringing, chemical shift artefacts, susceptibility distortions, and noise patterns that are scanner-specific. A model trained exclusively on Siemens data may learn to exploit Siemens-specific artefact patterns as discriminative features, performing well on Siemens test data but failing catastrophically when confronted with GE or Philips images in which these artefact patterns are different or absent.
Mitigation strategies.
Several strategies address the generalisation gap:
Multi-site training: Pooling data from multiple hospitals with diverse scanner types. This is the most direct approach but is limited by privacy constraints (see Federated Learning for Privacy-Preserving Segmentation).
Domain randomisation: Augmenting training data with synthetic domain shifts (intensity transformations, synthetic artefacts, resolution changes) to make the model invariant to scanner-specific characteristics.
Test-time adaptation: Adapting the model to the target domain at inference time using only the unlabelled test data. Techniques include batch normalisation adaptation and entropy minimisation.
Style transfer: Using generative models (GANs, diffusion models) to transform source-domain images into target-domain style while preserving anatomical content: (Style Transfer) where is a style representation extracted from target-domain images.
Research 1.
Open Problem 1: Provable Domain Generalisation Bounds for Medical Segmentation. Current domain generalisation methods for medical imaging are empirically motivated but lack theoretical guarantees. Can we establish PAC-style bounds of the form (Domain Bound) where is a discrepancy measure between source and target distributions and is an irreducible error term? The challenge is that existing domain adaptation theory (Ben-David et al., 2010) assumes shared label spaces and does not account for the structured, pixel-level nature of segmentation or the specific forms of domain shift in medical imaging.
Open Problems and Future Directions
The preceding sections have developed a comprehensive mathematical framework for generative models in medical image segmentation. We have covered diffusion-based architectures, prompt-driven foundation models, uncertainty quantification, multi-modal fusion, federated training, and fairness-aware learning. Yet many fundamental questions remain open. This section surveys the most important open problems, framed as formal research questions that we hope will inspire the next generation of research.
Calibrated Ambiguity Modelling in 3D+Time
The uncertainty quantification methods developed in this chapter operate primarily on 2D slices or, at best, on 3D static volumes. Clinical reality, however, is spatiotemporal: the heart beats, the lungs breathe, tumours grow, and contrast agents wash in and out. A cardiac MRI cine sequence comprises 20–30 temporal frames of 3D volumes, yielding a 4D tensor . Segmenting such data requires modelling not only spatial ambiguity (where is the boundary?) but also temporal ambiguity (when does the boundary move, and by how much?).
Research 2.
Open Problem 2: Calibrated Uncertainty in 4D Medical Volumes. Develop a diffusion-based segmentation framework for 4D medical volumes that produces spatiotemporal uncertainty maps satisfying the following calibration property: for any spatiotemporal region and any confidence level , (4D Calibration) Current methods for 2D calibration do not extend trivially to 4D because temporal correlations in cardiac or respiratory motion introduce long-range dependencies that violate the conditional independence assumptions underlying most calibration frameworks. The computational cost of running multiple diffusion samples on 4D volumes is also prohibitive with current hardware: a single denoising pass on a volume may take minutes, making ensemble-based uncertainty estimation impractical.
The core difficulty is that spatial and temporal uncertainties are coupled. Consider a cardiac segmentation: the left ventricular boundary is ambiguous in frames where the heart is mid-contraction (high temporal gradient), but the spatial uncertainty at frame depends on the segmentation at frames and . Capturing this coupling requires either:
A joint diffusion process over the entire 4D volume, which is computationally intractable with current architectures.
An autoregressive approach that conditions each temporal frame on the preceding frames, which introduces error accumulation and breaks temporal symmetry.
A factored approach that models spatial and temporal uncertainty independently and couples them through a learned correction, which may miss important correlations.
Real-Time Interactive Diffusion Segmentation
Diffusion models produce high-quality segmentations but at significant computational cost. A typical DDPM sampler requires denoising steps; even accelerated samplers (DDIM, DPM-Solver) require – steps. For a 3D medical volume, each step involves a full forward pass through a U-Net, taking 50–200,ms on a high-end GPU. The total inference time is thus 1–20 seconds per volume, far too slow for applications that require real-time feedback.
Intraoperative guidance.
In neurosurgery, the surgeon operates with real-time ultrasound or intraoperative MRI guidance. The segmentation system must process each new image frame within 30–100,ms to provide useful feedback. In interventional cardiology, catheter-based procedures require segmentation of fluoroscopic images at frame rates of 15–30,fps (33–66,ms per frame). These latency requirements are one to two orders of magnitude tighter than what current diffusion models can achieve.
Conjecture 1 (Diffusion Speed–Quality Tradeoff).
For any diffusion-based segmentation model with denoising schedule and learned score function , there exists a fundamental lower bound on the number of function evaluations (NFE) required to achieve a given segmentation quality : (Speed Quality) where is a constant depending on the data dimension, the score estimation error , and the curvature of the probability flow ODE. In particular, achieving (e.g., ) requires , while requires . The logarithmic scaling is optimistic in theory but the constant is large in practice (typically ), meaning that high-quality diffusion segmentation inherently requires dozens of function evaluations.
Distillation-based acceleration.
Consistency models (Song et al., 2023) and progressive distillation offer a path toward single-step or few-step generation. The idea is to train a student model that maps directly from noise to clean segmentation: (Consistency) enforcing a self-consistency property: running the model from any point along the trajectory should produce the same output. Applied to medical segmentation, consistency distillation has achieved inference times of 50–100,ms on 2D slices (1–2 steps), at the cost of a 2–5% Dice reduction compared to the full diffusion model. Whether this gap can be closed to zero remains an open question.
Universal Medical Foundation Models
The current landscape of medical segmentation models is fragmented. SAM-Med2D is specialised for 2D slices, SegVol for 3D volumes, STU-Net for abdominal organs, and specialised models exist for nearly every organ system and imaging modality. The dream of a universal medical foundation model, one model for all organs, all modalities, all tasks, is compelling but faces fundamental challenges.
Conjecture 2 (No Universal Dominance).
Let be a set of specialised segmentation models, where is optimised for task (e.g., “cardiac MRI segmentation”, “retinal OCT layer segmentation”). Let be any single universal model trained on the union of all training datasets. Then for any with parameter count , there exists a task and a specialised model with parameter count such that (NO Universal) In words, no universal model can simultaneously dominate all specialised models on their respective tasks. The universal model pays a “generality tax”: its parameters must encode knowledge about all tasks, leaving fewer effective parameters per task than a specialised model that devotes all its capacity to a single task.
Evidence for and against.
Scaling laws for language models suggest that sufficiently large models can master many tasks simultaneously without significant per-task degradation. GPT-4, for instance, performs competitively with specialised models on many NLP benchmarks despite being a generalist. However, medical segmentation differs from language in a crucial way: the visual features required for different tasks are far more heterogeneous. The texture patterns relevant for retinal layer segmentation (micron-scale optical coherence patterns) share almost no visual statistics with those relevant for liver tumour segmentation (centimetre-scale contrast enhancement patterns on CT).
Mixture-of-experts architectures.
A promising middle ground is the mixture-of-experts (MoE) architecture, in which a shared backbone routes different inputs to specialised expert modules: (MOE) where is a shared feature representation, is the gating weight for expert , and each expert specialises in a subset of tasks. This allows the model to maintain specialised capacity while sharing general features across tasks.
Research 3.
Open Problem 3: Optimal Task Routing in Medical MoE Models. Given a medical MoE model with experts and a stream of segmentation tasks from diverse modalities and organ systems, design a routing algorithm (mapping inputs to the probability simplex over experts) that minimises the average regret relative to an oracle that knows each task's optimal expert assignment: (Routing Regret) where is the oracle expert assignment. The routing algorithm must operate without knowing the task identity a priori (the input image arrives without a label indicating “cardiac MRI” or “retinal OCT”), and must generalise to tasks not seen during training (zero-shot routing).
Biofluids and the Navier–Stokes Connection
An unexpected connection links medical image segmentation to one of the deepest open problems in mathematics. Vascular segmentation, the task of delineating blood vessels from medical images, produces geometric models of the vascular tree. These geometric models are precisely the computational domains needed to simulate blood flow using the Navier–Stokes equations: where is the velocity field, is pressure, is fluid density, is dynamic viscosity, and represents external body forces.
Remark 36 (Connection to the Navier–Stokes Millennium Problem).
The Navier–Stokes existence and smoothness problem is one of the seven Millennium Prize Problems posed by the Clay Mathematics Institute. The problem asks whether smooth, physically reasonable solutions to the 3D Navier–Stokes equations always exist, or whether singularities (infinite velocities or pressures) can develop in finite time from smooth initial conditions.
The connection to medical segmentation is more than metaphorical. In computational haemodynamics, the accuracy of a blood flow simulation depends critically on the accuracy of the vascular geometry extracted by segmentation. A segmentation error that introduces a spurious stenosis (narrowing) into a coronary artery can change the computed fractional flow reserve (FFR), a clinical decision metric, by enough to flip a treatment decision from “medically manage” to “surgically intervene.” If the Navier–Stokes equations in that geometry admit singular solutions (as is unknown), then the sensitivity of clinical decisions to segmentation errors may be even more severe than current analyses assume, because the flow solution may be discontinuously sensitive to boundary perturbations near singular configurations.
For a thorough mathematical treatment of the Navier–Stokes equations, their regularity properties, and numerical methods for their solution, we refer the reader to the part on Generative Models for PDE-Based Simulation (Part XIX).
Physics-informed segmentation.
The Navier–Stokes connection suggests a new paradigm: physics-informed segmentation, where the segmentation model is jointly trained to produce masks that are not only anatomically plausible but also physically consistent with the governing equations of blood flow. The combined loss is (Physics Informed) where is the fluid domain defined by the predicted segmentation mask. This couples the segmentation model to a physics simulator, using the physics residual as a regulariser that penalises segmentations that would produce unphysical flow patterns.
Research 4.
Open Problem 4: Differentiable Navier–Stokes Solvers for Segmentation Regularisation. Design a differentiable Navier–Stokes solver that can be integrated into the training loop of a medical image segmentation model, such that gradients of the physics residual flow back through the solver and into the segmentation parameters. The solver must be:
Differentiable: Gradients must be computable via automatic differentiation.
Efficient: The cost of evaluating the physics loss must be at most per training step, where is the number of voxels, to remain tractable for 3D volumes.
Stable: The solver must handle the complex geometries produced by vascular segmentation without numerical blow-up, even for geometries with sharp corners, thin vessels, and bifurcations.
Current differentiable fluid solvers (e.g., JAX-Fluids, PhiFlow) handle simple geometries but struggle with the topological complexity of real vascular trees.
The Interpretability–Performance Tradeoff
Empirical evidence suggests a troubling pattern: the most accurate segmentation models are also the least interpretable. Simple thresholding methods are perfectly interpretable but inaccurate. Classical atlas-based methods are interpretable (registration to a template) but limited. Deterministic U-Nets achieve high accuracy and admit gradient-based explanations. Foundation models with prompt engineering achieve still higher accuracy but are harder to interpret. Diffusion-based models achieve state-of-the-art accuracy but, as argued in Interpretability of Diffused Attention, resist deterministic explanation entirely.
Can we have both?
Several recent approaches attempt to break the interpretability–performance tradeoff:
Concept bottleneck models: Force the model to route its decisions through a set of human-interpretable concepts (e.g., “tumour margin is irregular”, “enhancement is heterogeneous”) before making a segmentation prediction. This provides built-in explanations but may limit capacity.
Post-hoc diffusion explanations: The ensemble attribution method of (Ensemble Attribution) provides statistical explanations for diffusion models, sacrificing per-run determinism for aggregate interpretability.
Neuro-symbolic segmentation: Combine neural feature extraction with symbolic reasoning over anatomical rules (e.g., “the left ventricle is enclosed by the myocardium”). The neural component provides accuracy, the symbolic component provides interpretable constraints.
Sparse attention mechanisms: Design attention layers that attend to only a small number of image regions, making the attention pattern itself an explanation.
Self-Improving Medical AI
The most labour-intensive component of medical image segmentation is not model design or training but annotation. A single 3D medical volume may require 2–8 hours of expert radiologist time to annotate, at a cost of $200–$800 per volume. For a training set of 500 volumes, the annotation cost alone exceeds $100,000. This creates a perverse incentive: the institutions that most need AI assistance (those with limited radiologist availability) are precisely those that cannot afford to create the training data needed to build AI models.
The solution is self-improving AI: models that identify their own failure cases and strategically request human annotation only where it is most needed. This is the intersection of active learning and generative modelling.
Acquisition functions for segmentation.
The active learning framework requires an acquisition function that assigns a score to each unlabelled volume, indicating how informative its annotation would be. For segmentation, natural choices include:
Predictive entropy: The average per-voxel entropy of the model's predictive distribution: (Entropy ACQ) where is the number of voxels and is the Shannon entropy.
Boundary uncertainty: The average uncertainty along the predicted segmentation boundary: (Boundary ACQ) where denotes the set of voxels on the predicted boundary and the variance is computed across stochastic forward passes.
Expected model change: The expected change in model parameters if the volume were annotated and the model retrained: (EMC ACQ) which is expensive to compute exactly but can be approximated via influence functions.
Generative amplification of active learning.
Each human annotation is expensive. Generative augmentation amplifies the value of each annotation by using it to seed the generation of synthetic training examples. If the active learning oracle provides a single annotated volume , the generative model can produce variations: (GEN Amplification) each preserving the anatomical structure of while varying scanner characteristics, noise levels, and contrast. The effective training set grows by for each human annotation, dramatically improving the label efficiency of the active learning loop.
Research 5.
Open Problem 5: Optimal Stopping for Self-Improving Medical AI. In the active learning + generative augmentation loop of fig:medseg:active-learning-loop, each iteration produces a model and incurs an annotation cost . The cumulative cost is , and the model quality is . The optimal stopping problem is: (Optimal Stopping) where is a clinically required performance level. When does one stop requesting annotations? The answer depends on the marginal return of each annotation, which depends on the current model, the distribution of unlabelled data, and the effectiveness of generative amplification, all of which change over time. Designing principled stopping criteria that account for these non-stationary dynamics is an open problem.
Benchmark Design for Multimodal Prompting
Current benchmarks for medical image segmentation evaluate models on isolated tasks: given an image and a fixed prompt type (e.g., a bounding box, a set of points, or a text description), produce a segmentation mask . Performance is measured by a single metric (typically Dice or IoU) averaged over the test set. This evaluation paradigm has three critical limitations.
Single-prompt evaluation.
Real clinical workflows involve multiple prompt types used in combination. A radiologist might first specify a bounding box around the region of interest, then provide a text description (“segment the enhancing tumour, not the surrounding oedema”), then click on a few points to correct errors. No existing benchmark evaluates this multi-step, multi-modal interaction pattern.
Static evaluation.
Benchmarks present each test case independently. In clinical practice, the model is used iteratively: the clinician sees the first segmentation, corrects it, re-runs the model, corrects again, and so on until the result is satisfactory. The clinically relevant metric is not the Dice score after one pass but the Dice score after interaction rounds, weighted by the time cost of each interaction.
Metric monoculture.
The Dice coefficient measures volumetric overlap but is insensitive to boundary quality, topological correctness, and clinical relevance. A model that correctly segments 95% of a tumour's volume but misses a thin infiltrating margin may receive a high Dice score while providing a segmentation that is clinically dangerous for surgical planning. Metrics such as Hausdorff distance, boundary F1 score, and topology-aware metrics (Betti number preservation) are used in some papers but are not standardised across benchmarks.
Towards comprehensive benchmarks.
A well-designed multimodal prompting benchmark should evaluate:
Prompt compositionality: Performance when combining text, visual, and interactive prompts.
Prompt robustness: Sensitivity to prompt variations (e.g., rephrasing text, shifting click points by a few pixels).
Iterative refinement: Performance improvement over multiple interaction rounds.
Multi-metric evaluation: Dice, Hausdorff distance, boundary F1, topological accuracy, and clinical-task-specific metrics.
Fairness stratification: All metrics reported per demographic subgroup.
Computational cost: Inference time and memory usage as first-class metrics alongside accuracy.
Exercise 32 (Federated Learning Convergence Analysis).
Consider a federated learning setup with hospitals, each with local loss function . Assume each local loss is -smooth and -strongly convex, and that the local gradients have bounded variance: for all , where is the global objective.
Show that after communication rounds of FedAvg with learning rate and local epochs per round, the convergence rate of the global objective satisfies Identify the terms corresponding to optimisation error and statistical error respectively.
The second term increases with the number of local epochs . Explain intuitively why more local computation can hurt convergence in the presence of heterogeneous data ().
Propose a modification to FedAvg that reduces the statistical error term without increasing communication frequency. Hint: Consider FedProx with proximal parameter .
If Hospital E has only patients while Hospital A has , should the aggregation weights be modified? Propose an alternative weighting scheme that balances the contributions of data-rich and data-scarce hospitals, and analyse its effect on the convergence bound.
Exercise 33 (Fairness–Accuracy Pareto Analysis).
Consider a segmentation model evaluated on demographic groups (Fitzpatrick Types I–VI). Let denote the Dice score on group .
Define the fairness–accuracy Pareto frontier as the set of all models for which no other model achieves both higher average Dice and lower fairness gap simultaneously. Sketch what this frontier might look like and argue whether it is convex or non-convex.
Prove that the distribution-aware reweighting scheme of (Fairness Reweight), in the limit of perfect optimisation, converges to a minimax-fair solution satisfying . Under what conditions on the data does this minimax-fair solution also maximise average Dice?
A hospital administrator argues: “We should not sacrifice any accuracy on the majority group to improve performance on minority groups.” Formalise this as a constrained optimisation problem and show that it is incompatible with -group fairness for any .
Propose a Pareto-aware training algorithm that explores the fairness–accuracy frontier by solving a sequence of scalarised objectives for . What are the endpoints of this family ( and ), and how would you select in practice?
Key Idea.
Chapter summary: From algorithms to impact. The clinical translation of generative models for medical image segmentation is obstructed not by a single barrier but by a constellation of interdependent challenges: computational cost (which excludes under-resourced institutions), privacy requirements (which fragment data across institutions), stochastic non-reproducibility (which undermines interpretability), regulatory uncertainty (which slows deployment), algorithmic unfairness (which risks exacerbating health disparities), and dataset bias (which limits generalisation). No single technical advance will resolve all of these; progress requires a systems-level approach that addresses accuracy, fairness, accessibility, interpretability, and regulatory compliance simultaneously.
The open problems outlined in this section, calibrated 4D uncertainty, real-time diffusion, universal foundation models, physics-informed segmentation, breaking the interpretability–performance tradeoff, self-improving AI, and comprehensive benchmarks, represent the frontier of the field. Their resolution will determine whether generative medical segmentation remains a laboratory curiosity or becomes a transformative clinical tool.
Exercises
The exercises in this section consolidate the theoretical and practical foundations developed throughout the chapter. They progress from foundational calculations to advanced research-flavoured problems that require synthesising ideas across multiple sections. Each exercise has several parts of increasing difficulty; we encourage the reader to attempt every part before consulting references.
Key Idea.
Difficulty Progression Exercises 1–5 focus on core mathematical and architectural foundations (loss functions, U-Net, active contours, GANs, diffusion). Exercises 6–10 address probabilistic modelling, evaluation metrics, prompt-based segmentation, domain adaptation, and cell tracking. Exercises 11–15 tackle advanced topics including diffusion conditioning, vision–language models, federated learning, domain adaptation, and multi-annotator modelling.
Exercise 34 (Dice Coefficient Properties).
Let be two binary segmentation masks defined on a discrete image domain with pixels. The Dice coefficient and Intersection-over-Union (IoU, also called the Jaccard index) are defined as (DICE DEF)
Dice–IoU relationship. Prove that the Dice coefficient and IoU are related by (DICE IOU) Hint: Start from and substitute into the definitions. Show also the inverse: .
Dice is not a metric. Recall that a function is a metric if it satisfies (i) , (ii) , and (iii) (triangle inequality). Define the Dice distance as .
Show that satisfies (i) and (ii) but fails the triangle inequality (iii). Construct an explicit counterexample with three sets where the triangle inequality is violated.
Hint: Choose and with no overlap and overlapping partially with both.
Gradient of the soft Dice loss. In practice we work with soft predictions. Let denote the predicted probability at pixel and the ground truth. The soft Dice loss is (SOFT DICE) where is a smoothing constant. Compute the gradient for an arbitrary pixel . Express the result in terms of the numerator and denominator .
Verify that the gradient magnitude is larger for false positives (pixels where is high but ) than for true positives (pixels where both and are high), and explain why this property is beneficial for imbalanced segmentation tasks.
When does Dice loss outperform cross-entropy? Consider a binary segmentation problem where the foreground occupies only 1% of the image. Let denote the standard binary cross-entropy loss.
enumerate[label=()]
Show that a trivial classifier predicting for all pixels achieves (small) but (maximal).
Argue that cross-entropy is dominated by the easy-to-classify background pixels, while Dice loss focuses on the overlap with the foreground.
Discuss practical scenarios (e.g., small polyp segmentation, retinal vessel segmentation) where this difference is clinically significant.
Under what conditions might a combined loss outperform either loss alone? enumerate
Exercise 35 (U-Net Architecture Analysis).
Consider a standard U-Net with encoder levels. At each level, the encoder applies two convolutions (each followed by batch normalisation and ReLU) and then a max pooling. The decoder applies a transposed convolution for upsampling, concatenates the corresponding encoder feature map via a skip connection, and then applies two convolutions. Let the initial number of channels be , doubling at each level: for . The bottleneck has channels.
Receptive field computation. Compute the theoretical receptive field of the U-Net at the output layer. Recall that for a single convolution, the receptive field increases by 2 pixels per layer. Account for: enumerate[label=()]
The two convolutions at each encoder level.
The max pooling, which doubles the effective receptive field of subsequent layers.
The bottleneck convolutions.
The decoder convolutions (which do not increase the receptive field in the encoder's coordinate system but refine local features). enumerate Show that the receptive field is (UNET RF) Evaluate for and discuss whether this is sufficient to capture global context in a CT slice.
Parameter count. Compute the total number of trainable parameters in the network. For each convolutional layer with input channels and output channels, the parameter count is (weights plus biases). Carefully account for: enumerate[label=()]
Encoder: the first convolution at level maps (with for grayscale input), and the second maps .
Bottleneck: two convolutions at the deepest level.
Decoder: the transposed convolution maps ; after skip concatenation, the input has channels; two convolutions then map and .
Final convolution for classification. enumerate Express the total as a function of and , and evaluate numerically.
Skip connections and gradient flow. Consider training the U-Net with the Dice loss from Exercise 34. Let denote the encoder feature map at level , and let denote the corresponding decoder feature map.
enumerate[label=()]
Without skip connections, write the backpropagation path from the loss to and count the number of nonlinear layers the gradient must traverse.
With skip connections, identify the shortest gradient path from the loss to and compare.
Relate this to the vanishing gradient problem: if each nonlinear layer attenuates gradients by a factor , by what factor is the gradient attenuated in each case? enumerate
Minimal U-Net design. Design a minimal U-Net variant for grayscale images with only levels and . Specify the complete architecture (all convolutions, pooling, upsampling, skip connections, and output layer). Compute the parameter count and receptive field. Discuss in what medical imaging scenarios (e.g., cell segmentation on small patches, retinal vessel segmentation on cropped regions) such a lightweight architecture might be preferred over the full U-Net.
Exercise 36 (Active Contour Energy Functional).
The classical active contour model (snake) represents a curve for and minimises the energy functional (Snake Energy) where controls elasticity (resistance to stretching), controls rigidity (resistance to bending), and is an external energy derived from the image (typically for an image ).
Euler–Lagrange equations. Derive the Euler–Lagrange equations for the energy functional (Snake Energy). Show that the necessary condition for a minimum is (Euler Lagrange) for all , subject to appropriate boundary conditions. State what boundary conditions are needed for a closed contour (periodic boundary conditions) versus an open contour (natural boundary conditions).
Hint: Apply the calculus of variations. Let for a smooth test function and compute .
Discrete approximation. Discretise the contour as points with uniform spacing . Approximate the derivatives: Write the resulting discrete Euler–Lagrange system in matrix form: (Discrete Snake) where and collects the external forces. Identify the structure of the matrices and (they should be banded and circulant for a closed contour).
Failure modes. Describe and explain at least three situations where the classical snake model fails: enumerate[label=()]
The contour is initialised too far from the target boundary.
The target object has a concave boundary.
The image has multiple objects with similar edge strengths. enumerate For each case, explain the root cause in terms of the energy landscape (e.g., local minima, capture range of ).
Connection to level sets. The level set method represents the contour implicitly as the zero level set of a function : . The evolving curve is governed by the PDE (Level SET) where is a speed function. Show that if , where is the curvature and is the outward normal, then the level set evolution is equivalent to gradient descent on the snake energy (in the limit ).
Discuss why level sets can handle topological changes (splitting and merging of contours) naturally, while explicit snakes cannot.
Exercise 37 (GAN Training Dynamics for Segmentation).
Consider a segmentation GAN (SegAN) in which a generator produces segmentation masks from input images , and a multi-scale discriminator distinguishes between (image, ground truth mask) pairs and (image, generated mask) pairs . The training objective is (Segan LOSS) where is the mean absolute error and is a balancing hyperparameter.
Optimal discriminator. Fix the generator and derive the optimal discriminator . Show that for each pair (where is a candidate mask), the optimal discriminator is (Optimal DISC) where is the probability of being the true mask given , and is the probability under the generator's distribution.
Hint: This follows the standard derivation of the optimal discriminator for the vanilla GAN, applied to conditional distributions.
Mode collapse: a one-dimensional example. Consider a simplified one-dimensional setting where the image is fixed and the ground truth mask distribution is a mixture of two delta functions: This models a genuinely ambiguous segmentation with two valid masks.
enumerate[label=()]
Show that a deterministic generator can only capture one mode at a time, i.e., for some .
Compute the Jensen–Shannon divergence as a function of and show it is minimised when or (but not at the midpoint ).
Explain why this demonstrates mode collapse and how it manifests in medical image segmentation with ambiguous boundaries. enumerate
Wasserstein vs. Jensen–Shannon for medical images. In medical image segmentation, the target distribution often has support on a low-dimensional manifold (since valid segmentation masks form a structured subset of ).
enumerate[label=()]
Show that the Jensen–Shannon divergence between two distributions with disjoint supports is always , regardless of how “close” the distributions are geometrically.
In contrast, show that the Wasserstein-1 distance is continuous in the geometric sense: if and are supported on nearby (but disjoint) sets, can be arbitrarily small.
Argue why this property makes Wasserstein GANs more suitable for medical image segmentation, where slight boundary shifts should incur small losses. enumerate
GAN-generated polyps for data augmentation. Suppose a GAN is trained to generate synthetic colonoscopy images containing polyps, conditioned on polyp size, shape, and location parameters.
enumerate[label=()]
Design a protocol for validating the quality and diversity of generated polyps. What quantitative metrics (FID, precision/recall, clinical Turing test) would you use?
If a segmentation model trained with 50% real and 50% synthetic data achieves 3% higher Dice than a model trained on real data alone, how would you verify this improvement is statistically significant? Specify the null hypothesis and test.
What are the risks of generated polyps that are too realistic? Could they compromise clinical datasets if not properly labelled as synthetic? enumerate
Exercise 38 (DDPM Forward Process for Medical Images).
In a denoising diffusion probabilistic model (DDPM), the forward process adds Gaussian noise to a clean image according to (Forward STEP) where is the noise schedule with .
Closed-form marginal. Define and . Prove by induction that (Closed FORM Marginal)
Hint: For the base case , verify directly. For the inductive step, use the fact that if and with independent standard Gaussians and , then substitute and collect terms.
Signal-to-noise ratio. Define the signal-to-noise ratio at time as (SNR DEF) Show that is strictly decreasing in for any valid noise schedule. That is, show: enumerate[label=()]
is strictly decreasing (since each ).
The function is strictly increasing on .
Therefore for all . enumerate Compute , in terms of , and verify that as .
Number of diffusion steps for medical images. In natural image diffusion, is standard. For medical images, several factors differ: enumerate[label=()]
Medical images (CT, MRI) often have lower dynamic range and smoother textures than natural images. Argue that fewer diffusion steps might suffice for adequate noise scheduling.
Conversely, medical images require higher fidelity in subtle features (e.g., small lesions, thin vessel walls). Argue that more steps might be needed to preserve fine details during denoising.
Suppose the noise schedule is linear: with and . Compute for and determine the minimum such that (i.e., the signal is essentially destroyed).
Discuss the trade-off between sampling quality and inference time in a clinical setting where real-time segmentation is desirable. enumerate
Noise schedule and image frequency content. Consider two images: a chest X-ray (dominated by low-frequency content) and a retinal fundus image (containing fine, high-frequency vessel structures).
enumerate[label=()]
Argue intuitively that Gaussian noise destroys high-frequency components first. Formalise this by computing the expected power spectrum of : where is the Fourier coefficient at frequency and is the noise power (flat for white noise). Show that high-frequency signal components are masked by noise at smaller than low-frequency components.
Based on this analysis, propose a frequency-aware noise schedule that adds noise preferentially to high-frequency components first, and argue why this might improve diffusion-based segmentation of fine structures like retinal vessels. enumerate
Exercise 39 (Probabilistic U-Net).
The Probabilistic U-Net models the distribution of segmentation masks given an image using a latent variable model. A prior network produces and a posterior network produces , both Gaussian. A U-Net backbone extracts features, and the latent code is injected (e.g., via tiling and concatenation) to produce the final segmentation .
ELBO derivation. Write the evidence lower bound (ELBO) for this model. Starting from the marginal log-likelihood , apply Jensen's inequality (or equivalently, introduce the variational posterior ) to obtain: (ELBO) Identify each term: the reconstruction term (expected negative Dice loss or cross-entropy) and the KL regulariser.
KL + reconstruction decomposition. Show that maximising the ELBO is equivalent to simultaneously minimising the reconstruction error and the KL divergence. Formally, if we denote (where is the reconstruction term and is the KL divergence), then: enumerate[label=()]
Increasing improves mask quality.
Decreasing ensures the posterior matches the prior, enabling sampling at test time (when is not available).
Show that , where is the true posterior. This implies the gap between the ELBO and the true log-likelihood is exactly the KL divergence of the approximate posterior from the true posterior. enumerate
Latent dimension and diversity. Let where is the latent dimension. enumerate[label=()]
When , argue that the model can only capture a one-parameter family of segmentation variants (e.g., slight boundary shifts in one direction).
When is very large (e.g., ), the model has more representational capacity but the KL term becomes harder to optimise. Explain the “posterior collapse” problem: the model may learn to ignore entirely and produce deterministic outputs.
Propose a practical strategy for choosing . Consider using the number of distinct annotator masks in the training set as a guide. If there are annotators, what range of would you recommend and why? enumerate
Sampling and GED evaluation. At test time, sample latent codes and generate masks . Suppose the ground truth consists of annotator masks . Compute the Generalised Energy Distance (GED) as defined in ex:medseg:ged.
Using the following toy Dice values (where ):
and intra-set distances: mean , mean , compute a numerical estimate of the GED.0.10 0.25 0.30 0.22 0.28 0.08 0.15 0.20 0.15 0.18 0.12 0.25 0.30 0.22 0.28 0.09 0.20 0.14 0.18 0.16
Exercise 40 (Generalized Energy Distance).
The Generalized Energy Distance (GED) between two distributions and over segmentation masks, using a base distance , is defined as (GED DEF)
Formal definition and interpretation. Explain each of the three terms in (GED DEF): enumerate[label=()]
The cross-term measures the average distance between samples from and .
The term measures the spread (diversity) of .
The term measures the spread of . enumerate Argue that is small when the cross-distances are similar to the within-distribution distances, i.e., when and have similar means and similar variances.
GED equals zero iff distributions match. This is a deep result that depends on being a negative definite kernel (which the and distances satisfy). Prove the result for the special case where and are finite discrete distributions:
Let and with . Show that implies by arguing that: enumerate[label=()]
Define the energy distance in terms of characteristic functions. For with , the GED can be written as a weighted integral of the squared difference of characteristic functions: for a positive weight .
Since everywhere, the integral is zero iff almost everywhere.
Characteristic functions uniquely determine distributions. enumerate
Discrete computation. Let be the uniform distribution over masks and be the uniform distribution over , with the following distance matrix (using ):
and intra-distances , , , .0.10 0.40 0.35 0.15 0.20 0.25 Compute explicitly.
Why GED is superior for ambiguous segmentation. Consider a retinal fundus image where the optic disc boundary is inherently ambiguous: four expert annotators produce four different but all clinically acceptable masks.
enumerate[label=()]
If we use the standard Dice coefficient with a single majority vote ground truth, what information is lost?
Show with an example that a deterministic model achieving Dice against the majority vote could have , while a probabilistic model with Dice against the majority vote might achieve .
Explain why the probabilistic model is clinically preferable despite having a lower Dice score. enumerate
Exercise 41 (SAM Prompt Sensitivity Analysis).
The Segment Anything Model (SAM) accepts various prompt types: point prompts (positive/negative), bounding box prompts, and mask prompts. The model's output mask depends on the specific prompt provided.
Point prompt perturbation. Let denote the binary mask produced by SAM for image with a single positive point prompt at pixel location . Define the local sensitivity as (Prompt Sensitivity) where is the set of pixel locations within distance of .
For pixels on a image: enumerate[label=()]
How many perturbations are in ?
If the average Dice between the original and perturbed masks is 0.92, what is ?
Argue that should be higher near object boundaries than in object interiors. Why?
How does prompt sensitivity relate to the clinical risk of using SAM for interactive segmentation? enumerate
Experimental design. Design a rigorous experiment to measure SAM's prompt sensitivity across different medical imaging modalities. Specify: enumerate[label=()]
The dataset: at least 3 modalities (e.g., CT, MRI, endoscopy) with at least 100 images each.
The prompt sampling strategy: how to select initial prompt locations (random within ground truth, centroid, boundary).
The perturbation protocol: range of values to test.
The evaluation metrics: sensitivity , mask stability (IoU between consecutive perturbations), and clinical acceptability.
Statistical analysis: how to determine whether sensitivity differences across modalities are significant. enumerate
Negative prompts for small organs. Consider segmenting a small structure (e.g., the pancreas, which occupies of a CT volume).
enumerate[label=()]
Explain why a negative prompt placed inside a nearby large organ (e.g., the liver) might inadvertently suppress parts of the small target organ.
Formalise this: if SAM's decoder computes attention over prompt embeddings, a negative prompt with a large receptive field can create a “suppression zone” that extends beyond the intended region. Sketch how the attention weights might look.
Under what conditions (relative organ size, distance between organs) is this effect most severe? enumerate
Robust prompting strategy. Propose a multi-prompt strategy that reduces sensitivity to individual prompt placement. Your strategy should: enumerate[label=()]
Use positive prompts sampled from a prior distribution over likely foreground locations.
Aggregate multiple SAM outputs (e.g., via majority voting, STAPLE, or averaging logits).
Provide a theoretical justification for why aggregation reduces variance. If individual masks have sensitivity , show that majority voting over independent masks reduces the effective sensitivity by a factor of approximately .
Discuss the computational overhead: if SAM runs in ms per prompt, what is the total time for prompts, and what is feasible for interactive (sub-second) segmentation? enumerate
Exercise 42 (CycleGAN for Medical Domain Adaptation).
CycleGAN learns mappings and between two unpaired image domains using cycle consistency. Consider domain as CT images from hospital A and domain as CT images from hospital B, acquired with different scanners (different reconstruction kernels, noise characteristics, and contrast protocols).
Full CycleGAN loss. Write out the complete CycleGAN training objective: (Cyclegan LOSS) where: enumerate[label=()]
is the adversarial loss for .
is the cycle consistency loss.
is the identity loss. enumerate Explain the role of each term and typical values for and .
Cycle consistency for medical images. enumerate[label=()]
Explain why cycle consistency is particularly important for medical images: the mapping should change the style (scanner characteristics) without altering the content (anatomy, pathology).
Consider a patient with a small lung nodule in domain . If maps this image to domain without cycle consistency, the nodule could be removed (hallucinated away). Show that cycle consistency provides a necessary (but not sufficient) condition for content preservation: if , then must contain enough information to reconstruct , including the nodule.
Give an example where cycle consistency is satisfied but content is still altered. Hint: Consider steganographic encoding. enumerate
CycleGAN artifacts. Enumerate and explain at least four types of artifacts that CycleGAN can introduce in medical images: enumerate[label=()]
Checkerboard artifacts from transposed convolutions in the generator.
Hallucinated structures (e.g., adding or removing lesions) that satisfy cycle consistency via steganography.
Geometric distortions that warp anatomical structures.
Intensity shifts that alter Hounsfield unit (HU) distributions in CT, potentially affecting downstream quantitative analysis. enumerate For each artifact, propose a detection method or architectural modification to mitigate it.
Validation protocol. Design a comprehensive validation protocol for using CycleGAN-adapted images to train a segmentation model. Your protocol should include: enumerate[label=()]
A quantitative check for anatomical preservation (e.g., segmenting structures before and after translation and comparing masks).
A distribution-level check (e.g., comparing HU histograms of translated images against real images from the target domain).
A downstream task evaluation: train a segmentation model on adapted data and evaluate on real target domain data.
A clinical evaluation: have a radiologist review a blinded set of real and translated images and report any detected artifacts. enumerate
Exercise 43 (Cell Tracking as Bipartite Assignment).
In time-lapse microscopy, cell tracking requires associating detected cells in frame with detected cells in frame . Let be detections in frame and be detections in frame .
Bipartite matching formulation. Formalise cell tracking between consecutive frames as a bipartite matching problem. Define a cost matrix where (COST Matrix) where is the centroid position, is the area, and is the mask overlap of detection in frame . The weights control the relative importance.
Write the integer linear program (ILP) for the assignment: (ILP) Explain why the constraint allows (a cell in frame disappears) and (a new cell appears in frame ).
Hungarian algorithm complexity. The Hungarian algorithm solves the assignment problem in time.
enumerate[label=()]
For a typical cell tracking scenario with cells per frame, estimate the computation time assuming operations per second. Is this feasible for real-time tracking?
Describe how to augment the cost matrix to handle the rectangular case by adding dummy rows or columns with cost (a threshold for accepting new tracks/terminations).
Discuss alternative algorithms (auction algorithm, Jonker–Volgenant) and their practical advantages. enumerate
Handling cell division. Standard bipartite matching assumes one-to-one assignment, but cells can divide (mitosis), creating a one-to-two correspondence.
enumerate[label=()]
Propose a modification to the ILP that allows one detection in frame to be matched to at most two detections in frame . Write the modified constraint.
Discuss how to set the cost for a division event. Should it be cheaper or more expensive than a standard match? Consider biological priors (e.g., dividing cells tend to be larger and rounder).
How would you detect a division event retroactively: if cell at time has two potential matches at time , what features of , , and would you check? enumerate
When tracking-by-detection fails. The tracking-by-detection paradigm assumes reliable frame-wise detections. Describe and explain at least three failure modes: enumerate[label=()]
Dense cell populations: when cells are tightly packed, detection errors (merges, splits) propagate to tracking errors.
Low frame rate: when the time between frames is large relative to cell displacement, the cost matrix becomes ambiguous (many plausible matches).
Cell shape changes: during mitosis or apoptosis, cell appearance changes dramatically, making feature-based matching unreliable. enumerate For each failure mode, suggest a mitigation strategy and discuss how generative models (e.g., diffusion-based cell image synthesis for data augmentation, or a learned motion model) might help.
Exercise 44 (MedSegDiff Conditioning Mechanisms).
MedSegDiff is a diffusion-based medical image segmentation model that conditions the denoising process on the input image through a dynamic conditional encoding mechanism.
Dynamic conditional encoding. In MedSegDiff, the conditioning image is not simply concatenated with the noisy mask . Instead, a dynamic conditional encoder processes at multiple scales and modulates the denoising U-Net's feature maps via feature-wise linear modulation (FiLM): (FILM) where is the feature map at level in the denoising U-Net, and are learned affine parameters derived from the image encoder.
enumerate[label=()]
Explain why this is called “dynamic”: the modulation parameters and change for each input image .
Compare this to concatenation-based conditioning, where is fed as input. What additional expressiveness does FiLM provide?
Count the additional parameters introduced by FiLM at each level compared to concatenation. enumerate
Concatenation vs. cross-attention conditioning. Compare three conditioning strategies for diffusion-based segmentation:
enumerate[label=()]
Concatenation: , where denotes channel-wise concatenation.
Cross-attention: with cross-attention layers where comes from and come from an encoding of .
FiLM: as in part (a). enumerate
For each, analyse: (1) the computational cost in terms of the spatial resolution and channel count ; (2) the ability to capture long-range dependencies between the image and the mask; and (3) the inductive bias (does the method assume spatial alignment between and ?).
Feature Frequency Parser (FF-Parser). MedSegDiff-V2 introduces an FF-Parser that operates on the frequency spectrum of intermediate features.
enumerate[label=()]
The FF-Parser applies a 2D discrete Fourier transform to the feature map , applies a learnable mask in frequency space, and transforms back: Explain the purpose of this operation: it allows the model to selectively amplify or suppress different frequency components.
Why is frequency filtering beneficial for medical image segmentation? Relate to the typical frequency content of anatomical boundaries (edges are high-frequency) versus tissue texture (low to mid-frequency).
What is the computational cost of the FF-Parser relative to spatial convolution? Compare the cost of a 2D FFT () to a convolution (). enumerate
Extension to 3D volumes. Design a conditioning mechanism for diffusion-based segmentation of 3D medical volumes (e.g., CT scans). enumerate[label=()]
Discuss whether the 2D FiLM approach extends naturally to 3D or whether modifications are needed for the depth dimension.
Propose a “2.5D” approach that processes individual 2D slices but aggregates 3D context via a separate module. Describe the architecture.
Discuss memory constraints: a volume with 64 channels requires approximately bytes 2 GB per feature map. How would you handle this in practice? enumerate
Exercise 45 (VLM Grounding for Segmentation).
Vision–language models (VLMs) can ground textual descriptions to spatial regions in medical images. However, they are prone to hallucination-generating plausible but factually incorrect outputs.
Hallucination in medical VLMs. Define hallucination formally in the context of medical image segmentation. A VLM hallucinates when it produces a segmentation mask such that: enumerate[label=()]
includes a region that does not correspond to any anatomical structure matching the text prompt (fabrication).
omits a region that clearly matches the text prompt (omission).
segments the wrong structure (e.g., segmenting the right kidney when asked for the left kidney) (confusion). enumerate Give a concrete example of each type in a clinical scenario. Discuss why hallucination is more dangerous in medical imaging than in natural image understanding.
RAG for reducing hallucination. Retrieval-augmented generation (RAG) can ground VLM outputs in verified knowledge.
enumerate[label=()]
Design a RAG pipeline for medical image segmentation. The pipeline retrieves: (1) similar annotated images from a reference database, (2) relevant anatomy descriptions from a medical ontology, and (3) previous segmentation results for the same patient.
Formally, let be the retrieval function that returns reference pairs for query image and text . The augmented VLM produces: Argue that grounding in retrieved examples reduces fabrication by providing visual evidence of what the target structure looks like.
What are the failure modes of RAG? Consider: retrieval of incorrect references (the nearest neighbour has different anatomy), catastrophic reliance on retrieved examples, and privacy concerns when retrieving from patient databases. enumerate
Text prompt design. Design a text prompt for segmenting the liver in an abdominal CT scan. Consider multiple levels of specificity: enumerate[label=()]
Simple: “Segment the liver.”
Anatomical: “Segment the liver, the largest solid organ in the upper right abdomen, bounded superiorly by the diaphragm and inferiorly by the hepatic flexure of the colon.”
Quantitative: “Segment the liver parenchyma, excluding the portal vein, hepatic veins, and any focal lesions. The liver typically occupies 2–3% of body weight and has HU values of 50–70 on non-contrast CT.” enumerate Discuss how prompt specificity affects segmentation quality and potential failure modes (over-specification may cause the model to exclude valid liver tissue).
Text-guided vs. point-guided segmentation. Design a controlled experiment comparing text-guided and point-guided segmentation on a standard benchmark (e.g., BTCV multi-organ segmentation).
enumerate[label=()]
Define the experimental protocol: same base model (e.g., SAM-Med2D), same test set, same evaluation metrics (Dice, HD95).
For text-guided: use standardised anatomical prompts for each of the 13 organs.
For point-guided: use the centroid of each ground truth mask as the point prompt (best case) and also a random interior point (average case).
Predict which approach will perform better for large organs (liver, spleen) vs. small organs (adrenal glands, gallbladder), and explain your reasoning. enumerate
Exercise 46 (Federated Learning for Segmentation).
Federated learning enables multiple hospitals to collaboratively train a segmentation model without sharing patient data. Consider hospitals, each with a local dataset .
FedAvg for segmentation. Write the Federated Averaging (FedAvg) algorithm for training a U-Net segmentation model.
enumerate[label=()]
Server initialisation: initialise global model parameters .
Local training: at round , each hospital receives , performs local epochs of SGD on to obtain : (Local SGD) where is a mini-batch from .
Aggregation: the server computes (Fedavg) enumerate Write pseudocode for the complete algorithm including the communication protocol.
Domain shift between hospitals. Different hospitals use different scanners, protocols, and patient populations, creating domain shift.
enumerate[label=()]
Formalise domain shift: hospital has data distribution , where both the marginal (covariate shift) and the conditional (concept shift, e.g., different annotation guidelines) may differ.
Show that FedAvg implicitly optimises , which may not converge to a good solution when the are very different. Construct an example with hospitals where the FedAvg solution is worse than either local model.
Propose a modification (e.g., FedProx, personalised layers, domain-specific batch normalisation) and explain how it addresses the domain shift problem. enumerate
Differential privacy budget. To provide formal privacy guarantees, we add Gaussian noise to the model updates. In the Gaussian mechanism for -differential privacy, each local update is clipped to norm and noise is added, with for a constant .
enumerate[label=()]
For , compute the noise standard deviation .
Estimate the impact on segmentation quality. If the model has million parameters and the signal-to-noise ratio of the aggregated update is , compute the SNR for and the from (i).
Based on empirical studies, a rule of thumb is that Dice drops by approximately for . Discuss whether this trade-off is acceptable for different clinical applications (screening vs. surgical planning).
How does the privacy budget compose over rounds of federated training? Use the moments accountant to give a tighter bound than naive composition (). enumerate
Communication-efficient protocol. Each round of FedAvg requires transmitting the full model ( MB for a large U-Net) from each hospital to the server and back.
enumerate[label=()]
Propose three methods to reduce communication cost: gradient compression (top- sparsification), quantisation (from 32-bit to 8-bit or 1-bit), and local SGD with fewer communication rounds.
For top- sparsification with of parameters, compute the compression ratio and estimate the Dice degradation (empirically, for ).
Design a complete protocol specifying the communication schedule, compression method, and convergence criterion. How many rounds are typically needed for convergence with hospitals? enumerate
Exercise 47 (Domain Adaptation for Medical Segmentation).
A segmentation model trained on source domain often degrades when applied to a target domain due to domain shift. Generative models offer a principled approach to bridging this gap.
Formalising domain shift. Let be labelled source data from distribution and be unlabelled target data from . The domain shift can be decomposed as: (Domain Shift)
enumerate[label=()]
Covariate shift: but . Give a medical imaging example (e.g., different MRI field strengths produce different image appearances but the segmentation labels are the same).
Label shift: but . Give a medical imaging example (e.g., different disease prevalence between sites).
Concept shift: . Give a medical imaging example (e.g., different annotation guidelines between institutions).
Write the Ben-David domain adaptation bound: (BEN David) where is the target error, is the source error, is the -divergence, and is the optimal joint error. Explain each term. enumerate
CycleGAN-based adaptation. CycleGAN (Exercise 42) can reduce domain shift by translating source images to look like target images.
enumerate[label=()]
Let be the CycleGAN generator. The adapted training set is . Under what assumptions on are the source labels still valid for the translated images?
Show that if is an isometry in label space (i.e., the segmentation boundaries are preserved), then training on adapted data is equivalent to training on correctly labelled target data.
Discuss failure modes: when might the translated images be out-of-distribution for the target domain? enumerate
Diffusion-based adaptation. Diffusion models offer an alternative to GANs for domain adaptation. The approach adds noise to a source image and then denoises it conditioned on the target domain: (DIFF Adapt)
enumerate[label=()]
The noise level controls the strength of adaptation. For small , the adapted image stays close to the source (minor style transfer). For large , the adapted image is essentially sampled from the target distribution (losing content). Argue that there is an optimal that maximises adaptation quality while preserving anatomical content.
How would you determine in practice? Propose a method based on measuring Dice consistency between the source segmentation and the segmentation of the adapted image.
Compare to CycleGAN: diffusion-based adaptation requires no adversarial training but needs a pre-trained target-domain diffusion model. Discuss the practical trade-offs. enumerate
GAN-based vs. diffusion-based adaptation. Design a head-to-head comparison experiment.
enumerate[label=()]
Source domain: cardiac MRI from one scanner (e.g., 1.5T Siemens). Target domain: cardiac MRI from another scanner (e.g., 3T Philips).
Baselines: (a) no adaptation (train on source, test on target), (b) CycleGAN adaptation, (c) diffusion-based adaptation, (d) direct fine-tuning with a few labelled target examples (upper bound).
Evaluation: Dice, Hausdorff distance, and a novel metric you propose that captures both segmentation accuracy and anatomical plausibility.
What sample sizes are needed for the comparison to be statistically powered? Use a power analysis assuming effect size in Dice, standard deviation , significance level , and power . enumerate
Exercise 48 (Multi-Annotator Modelling).
In medical image segmentation, multiple expert annotators often provide different masks for the same image due to genuine ambiguity in boundary delineation. Let be four annotator masks for a single image.
Majority vote and information loss. The majority vote mask is defined pixel-wise: (Majority VOTE) for pixel .
enumerate[label=()]
Consider a pixel where annotators split 2-2 (two say foreground, two say background). Show that the majority vote assigns this pixel to the foreground, but this assignment is no better than a coin flip.
Compute the fraction of pixels where majority voting can be misleading: if on average 15% of boundary pixels have a 2-2 or 3-1 split, quantify the information lost by collapsing to a single mask.
Show that the Dice score between any individual annotator mask and the majority vote is bounded: with equality only when all annotators agree everywhere.
Define the inter-annotator agreement using pairwise Dice: . Show that if , the inherent segmentation uncertainty is approximately , which sets a ceiling on achievable performance. enumerate
Probabilistic multi-annotator model. Design a model that preserves individual annotator characteristics instead of collapsing to a single ground truth.
enumerate[label=()]
Model architecture: Extend the Probabilistic U-Net (Exercise 39) with an annotator embedding. For each annotator , learn an embedding vector . The generative model produces , allowing it to generate masks in the “style” of annotator .
Training objective: Write the modified ELBO that sums over annotators: (Multi Annot ELBO)
At test time: how do you generate a “consensus” mask and an “uncertainty” map? Propose sampling from and marginalising over annotator embeddings. enumerate
Annotator weighting. Not all annotators are equally reliable. Some annotators may be more experienced (e.g., a senior radiologist vs. a trainee).
enumerate[label=()]
The STAPLE algorithm estimates annotator reliability parameters (sensitivity and specificity for each annotator ) via EM. Write the E-step (compute the expected true segmentation given current reliability estimates) and the M-step (update reliability estimates given the expected true segmentation).
When should annotators be weighted equally vs. differentially? Argue that equal weighting is appropriate when annotators have similar training and the disagreement is due to genuine ambiguity, while differential weighting is appropriate when some annotators are systematically less accurate.
Design a calibration experiment to distinguish genuine ambiguity from annotator error. Hint: Have annotators re-annotate the same images after a washout period and compare intra-annotator consistency with inter-annotator consistency. enumerate
Connection to the ambiguity problem. The multi-annotator setting is a special case of the broader ambiguity problem in segmentation.
enumerate[label=()]
Ambiguity arises even with a single “true” annotator when the image is genuinely ambiguous (e.g., blurry boundaries). In this case, the single annotator's mask is a sample from the true conditional distribution . Explain why training with a single sample and cross-entropy loss biases the model towards the mode of .
Show that training with multiple annotator masks using the model in part (b) approximates the full distribution , not just its mode.
Discuss: if medical AI systems report only a single segmentation mask (the mode), what clinical information is lost? Propose a clinical interface that communicates uncertainty to the physician, drawing on the multi-annotator model's ability to generate diverse plausible masks. enumerate
0.60.4pt
Research Challenges
The following open-ended challenges represent frontier research directions in generative models for medical image segmentation. Each challenge is intended to inspire a research project, a thesis chapter, or a multi-year research programme. We provide context, desiderata, and evaluation criteria, but deliberately leave the solution approach open.
Challenge 4 (Real-Time Diffusion for Intraoperative Segmentation).
Context. Diffusion-based segmentation models such as MedSegDiff achieve state-of-the-art accuracy on multiple medical image benchmarks by iteratively denoising a mask over steps. However, each step requires a full forward pass through a U-Net, resulting in inference times of several seconds to minutes on modern GPUs. In intraoperative settings-image-guided surgery, real-time ultrasound-guided biopsy, endoscopic navigation-the segmentation system must produce a result within the surgeon's perceptual loop, typically ms per frame ( fps).
The Challenge. Design a diffusion-based segmentation system that achieves:
Latency: ms end-to-end on a single GPU (including image loading, preprocessing, inference, and postprocessing).
Accuracy: within 2% Dice of the full -step MedSegDiff baseline on at least two anatomical targets (e.g., surgical instrument segmentation, tumour margin delineation).
Uncertainty: preserve the ability to generate multiple plausible masks (at least 4 samples) to communicate uncertainty.
Technical Directions. Consider the following approaches, either individually or in combination:
Progressive distillation. Train a student model that reproduces the output of two teacher denoising steps in a single step. Iterating times yields a model that performs the full diffusion in a single step. The distillation loss for step halving is (Distillation) where is the two-step teacher prediction. Analyse: how many rounds of distillation are needed to go from to ? What accuracy is lost at each stage?
Consistency models. Consistency models learn to map any point on the diffusion trajectory directly to the clean data: for all . The consistency condition is (Consistency) where and lie on the same probability flow ODE trajectory. Discuss: can consistency models be trained directly on medical segmentation datasets, or must they be fine-tuned from a pre-trained diffusion model?
Architectural optimisation. Replace the standard U-Net backbone with an efficient architecture: itemize
MobileNet-style depthwise separable convolutions.
Linear attention mechanisms ( instead of ).
TensorRT or ONNX compilation with FP16/INT8 quantisation. itemize Estimate the speedup for each optimisation and determine whether architectural changes alone can achieve the 50 ms target.
Hardware-aware design. Modern surgical suites are equipped with edge computing devices (e.g., NVIDIA Jetson, Apple Neural Engine). Design the system to run on a specific hardware target and report latency measurements.
Evaluation Protocol. Report: (1) Dice score on 5 test sets across 2 modalities; (2) inference latency (mean std) measured over 1000 forward passes on the target hardware after warmup; (3) GED computed from samples to assess preserved uncertainty; (4) a qualitative comparison of segmentation masks under single-step vs. multi-step inference.
Open Questions.
Is there a fundamental accuracy–latency Pareto frontier for diffusion-based segmentation, and where does it lie?
Can one-step diffusion models match the uncertainty calibration of multi-step models?
How does the optimal number of denoising steps vary across anatomical targets (simple vs. complex shapes)?
Challenge 5 (Universal Cell Tracking Foundation Model).
Context. Cell tracking is fundamental to biomedical research: quantifying cell migration, proliferation, and morphological dynamics in time-lapse microscopy. Current state-of-the-art methods are modality-specific: a tracker trained on fluorescence microscopy images degrades dramatically when applied to phase contrast or electron microscopy (EM) images. Each new microscopy modality or cell type requires collecting and annotating new tracking data-a bottleneck that limits the pace of biological discovery.
The Challenge. Design a foundation model for cell tracking that:
Zero-shot generalisation: tracks cells in any microscopy modality (fluorescence, phase contrast, brightfield, differential interference contrast, electron microscopy) without fine-tuning.
Biological events: handles cell division (mitosis), cell death (apoptosis), cell-cell fusion, and cell extrusion.
Dimensionality: works in 2D, 2D+time, 3D, and 3D+time settings.
Frame rate robustness: handles temporal sampling rates from 1 frame per minute to 1 frame per day.
Scale: tracks from tens of cells to millions of cells in a single experiment.
Technical Directions.
Self-supervised pre-training. Design a pre-training objective that learns cell representations from unlabelled microscopy videos. Consider: itemize
Masked autoencoding (MAE) on spatiotemporal patches.
Contrastive learning: pull together representations of the same cell across time, push apart representations of different cells.
Predictive coding: given frames , predict the cell configuration at frame . itemize Which objective best captures the dynamics needed for tracking?
Modality-agnostic representation. Different modalities produce fundamentally different image statistics. Propose a representation that is invariant to imaging modality: (Modality Invariant) when and depict the same cells. How do you obtain paired cross-modality data for training? Consider: simultaneous multimodal imaging, CycleGAN-based modality translation, or physics-based image simulation.
Division-aware architecture. Standard tracking models use bipartite matching (one-to-one assignment). For cell division, extend the architecture to predict: itemize
A division probability for each cell at time .
The expected positions of daughter cells.
The optimal cost assignment under the modified ILP from Exercise 43. itemize
Scaling to millions of cells. Large-scale experiments (e.g., whole-embryo light-sheet microscopy) involve millions of cells across thousands of frames. Discuss: graph-based tracking vs. attention-based tracking, memory-efficient representations, and hierarchical approaches (track cell clusters, then individual cells).
Evaluation Protocol. Use the Cell Tracking Challenge (CTC) benchmark, which provides datasets across 10+ modalities. Report: (1) AOGM (Acyclic Oriented Graph Matching) score for tracking accuracy; (2) SEG score for segmentation quality; (3) TRA score for tracking quality; (4) zero-shot vs. fine-tuned performance on held-out modalities.
Open Questions.
What is the minimum amount of per-modality labelled data needed to match the performance of a modality-specific tracker?
Can generative models (diffusion, flow matching) be used to synthesise training data for rare biological events (e.g., asymmetric division, apoptosis followed by phagocytosis)?
How should temporal information be incorporated: explicit motion models, implicit via video transformers, or hybrid approaches?
Challenge 6 (Privacy-Preserving Generative Augmentation).
Context. Medical image datasets are scarce due to privacy regulations (HIPAA, GDPR), institutional data governance, and the cost of expert annotation. Generative models-GANs, VAEs, diffusion models-can synthesise realistic medical images to augment training data. However, a generative model trained on real patient data may memorise individual training examples, enabling membership inference attacks that compromise patient privacy. The challenge is to generate images that are useful for training segmentation models while providing formal privacy guarantees.
The Challenge. Design a generative augmentation pipeline that satisfies:
Formal privacy: the synthetic data release satisfies -differential privacy with and .
Utility: a segmentation model trained on synthetic data alone achieves at least 90% of the Dice score of a model trained on real data.
Diversity: the synthetic dataset has comparable diversity to the real dataset, as measured by precision/recall metrics and FID.
Resistance to attacks: membership inference attacks against the generative model have accuracy (near random).
Technical Directions.
DP-SGD training. Train the generative model with differentially private stochastic gradient descent (DP-SGD). In DP-SGD, each per-example gradient is clipped to norm and Gaussian noise is added to the aggregated gradient: (Dpsgd) Analyse: (1) how does the noise level affect image quality? (2) how does the clipping norm affect training stability? (3) what is the privacy cost per epoch, and how many epochs can you afford?
PATE for generative models. An alternative to DP-SGD is Private Aggregation of Teacher Ensembles (PATE). Train an ensemble of “teacher” generators on disjoint data partitions. A “student” generator is then trained on synthetic data produced by the teachers, with noise added to the aggregation. Design this pipeline for medical image generation and analyse the privacy–utility trade-off.
Post-hoc sanitisation. Rather than training with DP-SGD, train a standard generative model and then sanitise the synthetic data by: itemize
Removing outliers that are too close to real training images (measured by perceptual distance).
Adding noise to the latent codes before generating images.
Using a membership inference attack as a filter: discard synthetic images that are flagged as “memorised.” itemize Discuss: does post-hoc sanitisation provide formal DP guarantees? Under what conditions might it provide practical privacy protection without formal guarantees?
Evaluation of privacy. Design a comprehensive privacy evaluation: itemize
Black-box membership inference: train an attack model to distinguish training set members from non-members.
Nearest-neighbour analysis: for each synthetic image, find the nearest real image (in pixel space, feature space, and perceptual space) and report the distribution of distances.
Re-identification: attempt to match synthetic images to specific patients using anatomical landmarks.
Attribute inference: attempt to infer sensitive attributes (age, sex, diagnosis) from synthetic images. itemize
Evaluation Protocol. Report: (1) guarantee; (2) Dice of segmentation model trained on synthetic data vs. real data baseline; (3) FID and precision/recall of synthetic images; (4) membership inference AUROC; (5) nearest-neighbour distance distribution; (6) re-identification accuracy.
Open Questions.
Is there a fundamental privacy–utility trade-off curve for medical image synthesis, and can it be characterised theoretically?
Can we achieve (strong privacy) while maintaining Dice on liver segmentation?
How does privacy budget scale with dataset size? Is it easier to be private with large datasets?
Can federated generation (each site generates locally, aggregate globally) improve the privacy–utility trade-off?
Challenge 7 (Text-to-Segmentation Zero-Shot).
Context. Current medical image segmentation systems require either (a) labelled training data for supervised learning or (b) visual prompts (points, boxes) for interactive segmentation. Neither is ideal: labelled data is expensive to obtain, and visual prompts require a human in the loop. An emerging paradigm is text-to-segmentation: given only a natural language description of the target structure, produce a segmentation mask without any example images or visual prompts.
The Challenge. Design a system that, given:
A medical image (CT, MRI, ultrasound, endoscopy, or histology),
A text description (e.g., “segment the 3 mm sessile polyp in the ascending colon, visible as a slightly raised mucosal lesion with smooth borders”),
produces a binary segmentation mask without having seen any labelled examples of that specific structure, achieving Dice on previously unseen target types.
Technical Directions.
VLM reasoning + SAM execution pipeline. Decompose the problem into two stages: enumerate[label=()]
Reasoning: A medical VLM (e.g., Med-PaLM, BiomedCLIP) interprets the text and the image to identify the spatial region of interest. The VLM outputs: (a) a bounding box proposal, (b) a set of positive and negative point prompts, and (c) a confidence score.
Execution: The prompts from (i) are fed to a medical SAM variant (e.g., MedSAM) to produce the final mask. enumerate Formalise this as a chain: (VLM SAM Chain) Analyse the error propagation: if the VLM places the bounding box with IoU 0.8 relative to the true bounding box, what is the expected Dice of the SAM output?
Grounded medical reasoning. The VLM must understand medical terminology and map it to spatial regions. Design a training procedure that teaches the VLM to ground anatomical terms: itemize
Pre-training on radiology reports paired with images (weak supervision: reports mention structures but do not provide masks).
Fine-tuning on a small set of text–mask pairs using visual grounding loss.
Retrieval augmentation: retrieve similar cases from a database to provide in-context examples. itemize
Handling ambiguous descriptions. Medical text descriptions can be ambiguous: “segment the mass” does not specify whether to include surrounding oedema, calcification, or necrotic core. Design a dialogue system: enumerate[label=()]
The system produces an initial segmentation and a confidence map.
If confidence is low in certain regions, the system asks a clarifying question (e.g., “Should I include the surrounding oedema?”).
The user responds, and the system refines the segmentation. enumerate Formalise this as an iterative process: , where is the user's response at iteration .
Cross-modal generalisation. A text prompt like “segment the liver” should work on CT, MRI, and ultrasound, despite the liver appearing very differently in each. Design a modality-aware text encoder that conditions on both the text and the imaging modality: (Modality Aware) where is the modality. How should the modality information be incorporated (separate encoders, modality tokens, or conditional normalisation)?
Evaluation Protocol.
In-distribution: Evaluate on structures seen during training but with novel text prompts (paraphrases, varying specificity).
Zero-shot: Evaluate on entirely new structures not seen during training (e.g., train on abdominal organs, test on brain structures).
Cross-modal: Train on CT, test on MRI (or vice versa).
Metrics: Dice, HD95, and a new metric for “prompt adherence” (does the mask match all constraints in the text?).
Open Questions.
What is the minimum text specificity needed for reliable segmentation? Is “segment the liver” sufficient, or do we always need detailed anatomical descriptions?
Can a single system handle all medical imaging modalities, or is per-modality specialisation necessary?
How do we handle text descriptions of pathologies that the model has never seen (e.g., a rare tumour type described only in text)?
Challenge 8 (Calibrated Uncertainty for Clinical Decision Support).
Context. Medical image segmentation models increasingly inform clinical decisions: tumour volumetry guides radiation therapy planning, organ segmentation guides surgical navigation, and lesion detection influences diagnostic pathways. For these decisions to be safe, the model must communicate not just what it predicts, but how confident it is. Crucially, these confidence estimates must be calibrated: when the model says “80% confident this pixel is tumour,” tumour should be present at that pixel in 80% of cases.
The Challenge. Design a segmentation system where:
Pixel-level calibration: the predicted probability at each pixel is calibrated, as measured by the pixel-level Expected Calibration Error (ECE): (ECE) where is the set of pixels in confidence bin , is the empirical accuracy, and is the mean confidence. Target: ECE .
Structure-level calibration: the model's confidence that an entire structure (e.g., a tumour) is correctly segmented (Dice ) should be calibrated. If the model says “90% confident this liver segmentation has Dice ,” this should hold for 90% of test cases.
Clinical utility: the uncertainty estimates directly improve clinical outcomes, as measured by decision-theoretic metrics (e.g., expected utility of treatment decisions based on model output + uncertainty).
Technical Directions.
Sources of uncertainty. Medical image segmentation uncertainty arises from multiple sources: itemize
Aleatoric uncertainty (data noise): irreducible uncertainty due to image acquisition noise, motion artefacts, and inherent ambiguity in boundary delineation.
Epistemic uncertainty (model uncertainty): reducible with more data, arising from limited training data and model capacity.
Out-of-distribution (OOD) uncertainty: the test image is unlike anything seen in training (different scanner, pathology, or anatomy). itemize Design a system that disentangles these three sources. A common approach: use the Probabilistic U-Net (Exercise 39) for aleatoric uncertainty, MC-Dropout or deep ensembles for epistemic uncertainty, and a learned OOD detector for distribution shift.
Post-hoc calibration for segmentation. Temperature scaling, a standard calibration technique for classification, does not directly apply to structured outputs like segmentation masks.
enumerate[label=()]
Propose an extension of temperature scaling to segmentation: apply a spatially varying temperature at each pixel : . How should be learned? Consider: global , class-specific , or a learned spatial map .
Analyse: does temperature scaling change the predicted mask (hard segmentation), or only the confidence (soft segmentation)? Show that temperature scaling preserves the argmax and therefore does not affect Dice or IoU.
Discuss why this is insufficient: even with perfect pixel-level calibration, the model may not be calibrated at the structure level (because pixel errors are correlated). enumerate
Decision-theoretic evaluation. Define a clinical decision problem: enumerate[label=()]
The clinician must decide between two treatment options (e.g., surgery vs. watchful waiting) based on tumour volume.
The tumour volume is estimated from the segmentation mask.
The decision is optimal when the model's uncertainty correctly triggers a “refer to human expert” action. enumerate Formalise this as a decision problem with cost matrix: (Decision COST) Show that the optimal referral threshold depends on the calibration quality: a well-calibrated model can use a higher threshold (fewer referrals) while maintaining the same expected cost.
Generative uncertainty quantification. Use the multi-sample capability of generative models (Probabilistic U-Net, diffusion models) to estimate uncertainty: itemize
Generate segmentation samples .
Compute the pixel-wise entropy: , where .
Compute the structure-level uncertainty: the variance of Dice across samples: . itemize Show that this approach captures aleatoric uncertainty (high entropy at ambiguous boundaries) and argue that it can be combined with ensembles of generative models to capture epistemic uncertainty.
Evaluation Protocol.
Calibration metrics: pixel-level ECE, structure-level ECE, reliability diagrams.
Segmentation metrics: Dice, HD95, surface distance.
Decision metrics: expected cost under the decision model, referral rate, missed pathology rate.
Clinical study: a reader study where radiologists use the uncertainty visualisation and report whether it improves their confidence and decision quality.
Open Questions.
What is the minimum calibration quality (ECE threshold) below which uncertainty estimates become clinically useful?
How should uncertainty be visualised? Colour overlays, contour variability plots, or numerical confidence scores?
Can we build a self-aware system that refuses to produce a segmentation when uncertainty is too high, and if so, what threshold should trigger refusal?
How does calibration change under domain shift? If a model is calibrated on data from hospital A, is it still calibrated on data from hospital B?