Skip to content
AIAI Wranglers

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 𝒙H×W×C be a medical image with spatial dimensions H×W and C channels (e.g., C=1 for grayscale CT, C=3 for RGB histopathology). A segmentation mask is a map (MASK DEF)𝒚:{1,,H}×{1,,W}{0,1,,K}, where K is the number of foreground classes and 0 denotes the background. The segmentation task is to produce a mask 𝒚 that assigns each pixel (i,j) to the correct anatomical or pathological class. In the 3D setting, the image 𝒙D×H×W×C has an additional depth dimension D (the number of slices), and the mask becomes 𝒚:{1,,D}×{1,,H}×{1,,W}{0,1,,K}.

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).

  1. 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 ={0,1,,K}.

  2. 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 ={0}{(k,n):k{1,,K},n{1,2,}}, where n indexes distinct instances of class k.

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 2040 structures per patient, a task that takes a trained dosimetrist 30 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.

The clinical segmentation pipeline. A medical image (CT, MRI, X-ray, or histopathology slide) is processed by a segmentation algorithm that assigns anatomical or pathological labels to each pixel or voxel. The resulting labelled regions inform clinical decisions - staging, dosimetry, surgical planning - that ultimately determine the treatment plan. Segmentation is the critical bridge between raw imaging data and actionable clinical information.

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 0 HU and air is 1000 HU. CT excels at depicting bony structures and lung parenchyma, and is the workhorse of oncologic imaging. A typical CT volume has dimensions 512×512×D, where D ranges from 50 (a focused abdominal scan) to over 1000 (a whole-body PET/CT), with in-plane resolution of 0.51.0 mm and slice spacing of 0.55.0 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 1×1×1 mm3 for structural brain MRI and 1.5×1.5×8 mm3 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 100,000×100,000 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.

Three canonical medical image segmentation tasks. Left: Brain tumour segmentation on MRI, requiring delineation of enhancing tumour (red), surrounding oedema (amber), and necrotic core - a multi-class semantic segmentation task. Centre: Lung nodule segmentation on CT, a binary segmentation task distinguishing nodule from background. Right: Cell nuclei segmentation on histopathology, an instance segmentation task where each nucleus receives a unique label. Colours indicate segmentation overlays.

Example 1 (Lung nodule segmentation for radiotherapy planning).

Consider a 62-year-old patient diagnosed with stage IIA non-small cell lung cancer. A contrast-enhanced CT scan of the chest is acquired, producing a 512×512×280 volume with 0.7×0.7 mm in-plane resolution and 1.5 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 0.61 to 0.89, with a median of 0.78. 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 45-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 2040 organs at risk) requires 30 minutes to 4 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 0.80. This means that two board-certified neuroradiologists, given the same MRI, produce tumour delineations that overlap by only 80%. For the peritumoral oedema, the overlap drops further. For prostate segmentation on MRI, inter-observer Dice scores as low as 0.65 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 3.6 billion medical imaging examinations are performed annually, producing petabytes of data. The number of trained radiologists, by contrast, is approximately 500,000 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 1 per 100,000 - compared to 12 per 100,000 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 (x,y,z) 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 p^i,k=p𝜽(yi=k|𝒙), the pixel-wise cross-entropy loss is (Cross Entropy)CE(𝜽)=1Ni=1Nk=0Kyi,klogp^i,k, where N=H×W is the number of pixels, yi,k{0,1} is the one-hot encoding of the ground truth label for pixel i, and p^i,k is the predicted probability that pixel i belongs to class k. 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)Dice(𝒚,𝒚^)=2|𝒚𝒚^||𝒚|+|𝒚^|=2i=1Nyiy^ii=1Nyi+i=1Ny^i, where yi,y^i{0,1} are the ground truth and predicted labels for pixel i, respectively. The Dice coefficient ranges from 0 (no overlap) to 1 (perfect overlap) and is related to the Jaccard index by Dice=2IoU/(1+IoU).

To use the Dice coefficient as a training loss, we define the soft Dice loss using predicted probabilities: (DICE LOSS)Dice(𝜽)=12i=1Nyip^i+ϵi=1Nyi+i=1Np^i+ϵ, where p^i=p𝜽(yi=1|𝒙) is the predicted foreground probability and ϵ>0 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)(𝜽)=αCE(𝜽)+(1α)Dice(𝜽), where α[0,1] 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 α=0.5 is a common default.

Hausdorff distance loss.

For applications where boundary accuracy is critical (e.g., radiotherapy planning), the Hausdorff distance (Hausdorff)dH(A,B)=max{sup𝒂Ainf𝒃B𝒂𝒃2,sup𝒃Binf𝒂A𝒂𝒃2} measures the worst-case boundary error between predicted and ground truth contours A and B. 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 2040 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 117 anatomical structures, found that the model matched expert performance (mean Dice >0.90) on 93% of structures, while reducing segmentation time from 3090 minutes per case to under 10 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 >90% 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 f𝜽:𝒙𝒚^ 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 60% 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 4×4 image patch near a tumour boundary. Expert A labels pixels (3,1) through (3,4) as tumour; Expert B labels pixels (4,1) through (4,4) as tumour. The pixel-wise average of their annotations assigns 50% 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 p(𝒙,𝒚) or the conditional p(𝒚|𝒙) 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.

LimitationDiscriminativeGenerative
UncertaintySingle mask output; pixel-wise probabilities lose correlationsSamples multiple plausible masks; captures spatial correlations
[4pt] Domain shiftPoint mapping; brittle extrapolationLearns data distribution for synthesis; principled OOD detection
[4pt] Data scarcityRequires large labelled datasetsTransfers 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).

  1. A discriminative segmentation model learns a function f𝜽:𝒳𝒴 (or, with probabilistic output, a point estimate 𝒚^=arg max𝒚p𝜽(𝒚|𝒙)) that maps an input image 𝒙𝒳 to a single predicted mask 𝒚^𝒴. Training minimises a loss (𝒚^,𝒚) between the prediction and a reference annotation 𝒚.

  2. A generative segmentation model learns the full conditional distribution p𝜽(𝒚|𝒙) over segmentation masks given the input image. At inference time, the model can sample multiple plausible masks 𝒚(1),𝒚(2),,𝒚(S)p𝜽(𝒚|𝒙), compute the posterior mean 𝔼p𝜽[𝒚|𝒙], or evaluate the probability of any specific mask p𝜽(𝒚|𝒙).

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 R expert annotators, each producing a mask 𝒚(r) for the same image 𝒙. The empirical distribution over expert annotations is (Empirical Expert DIST)p^(𝒚|𝒙)=1Rr=1Rδ(𝒚𝒚(r)), 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 p(yi=k|𝒙)=1Rr=1R𝟏[yi(r)=k], which is the marginalised distribution that loses all information about the correlation structure between pixels. A generative model that learns the full joint distribution p𝜽(𝒚|𝒙) preserves these correlations: it can sample mask 𝒚(1) (a coherent delineation consistent with annotator 1's style) or mask 𝒚(2) (consistent with annotator 2's style), rather than producing a blurred average.

The mathematical statement is that the pixel-wise entropy H(𝒚|𝒙) decomposes as (Entropy Decomposition)H(𝒚|𝒙)=i=1NH(yi|𝒙)sum of marginal entropiesI(y1;y2;;yN|𝒙)multi-information (redundancy), where the multi-information I(y1;y2;;yN|𝒙) 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.

Discriminative vs. generative segmentation. Left: A discriminative model maps an input image 𝒙 to a single predicted mask 𝒚^, discarding information about the distribution of plausible masks. Right: A generative model learns the full conditional distribution p𝜽(𝒚|𝒙) and can sample multiple plausible masks 𝒚(1),𝒚(2),𝒚(3), each representing a coherent, clinically valid interpretation of the ambiguous image. The diversity of samples reflects the genuine uncertainty in the segmentation task.

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 p(𝒚|𝒙) 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.

The three pillars of generative medical image segmentation. Pillar 1: Synthetic data generation amplifies scarce annotations by generating realistic image–mask pairs. Pillar 2: Ambiguity modelling captures the full distribution of plausible masks, enabling uncertainty quantification. Pillar 3: Zero-shot adaptation leverages pretrained generative priors to segment novel structures without task-specific training data. All three pillars are built on the same foundation of generative modelling techniques.

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 p(𝒚|𝒙) 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 q𝜽(𝒚|𝒙) and optimises (KL Objective)min𝜽𝔼𝒙p(𝒙)[KL(p(𝒚|𝒙)q𝜽(𝒚|𝒙))]. If q𝜽 factorises as a product of independent pixel-wise distributions, i.e., (MEAN Field)q𝜽(𝒚|𝒙)=i=1Nq𝜽(yi|𝒙), 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 arg max 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)p𝜽(𝒚|𝒙)=p(𝒚T)t=1Tp𝜽(𝒚t1|𝒚t,𝒙)d𝒚1:T, where the reverse process gradually refines a noisy mask 𝒚T into a coherent segmentation 𝒚0, 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)p𝜽(𝒚|𝒙)=p𝜽(𝒚|𝒛,𝒙)p(𝒛)d𝒛, where the latent variable 𝒛 captures the “style” or “interpretation” of the segmentation. Different samples of 𝒛 produce different coherent masks, and the marginal p𝜽(𝒚|𝒙) is a mixture over these interpretations.

Posterior collapse and mode coverage.

A critical challenge for generative segmentation models is ensuring that the learned distribution p𝜽(𝒚|𝒙) actually covers all modes of the true distribution p(𝒚|𝒙). 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:

  1. Sample quality: each individual sample 𝒚(s)p𝜽(𝒚|𝒙) should be a coherent, clinically plausible mask.

  2. Sample diversity: the set of samples {𝒚(1),,𝒚(S)} 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 𝒮={𝒚(1),,𝒚(S)} be a set of samples from the model and 𝒢={𝒚(1),,𝒚(R)} be the set of ground truth annotations from R experts. The generalised energy distance (Kohl et al., 2018) is defined as (GED)DGED2(𝒮,𝒢)=2𝔼[d(𝒚(s),𝒚(r))]𝔼[d(𝒚(s),𝒚(s))]𝔼[d(𝒚(r),𝒚(r))], where d is a distance metric (typically 1IoU) 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-S.

A simpler evaluation strategy draws S samples from the model and reports the best Dice coefficient achieved among them: (BEST OF S)Best-of-S=maxs{1,,S}Dice(𝒚(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 0.7 to a particular boundary configuration, then roughly 70% 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 Dss=Dice(𝒚(s),𝒚(s)) for s,s{1,,S} 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.

Chapter roadmap for Generative Models for Medical Image Segmentation. File A (this file, highlighted) provides the introduction and clinical motivation. Files B–E develop the core technical content: synthetic data generation, ambiguity modelling, diffusion-based segmentation, and foundation models. Files F–G address clinical deployment and research frontiers. Arrows indicate prerequisite relationships.
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 A,B{1,,N} be two sets of pixel indices (e.g., the foreground pixels in two segmentation masks), and define the Dice coefficient as Dice(A,B)=2|AB|/(|A|+|B|).

  1. Show that Dice(A,B)[0,1], with Dice(A,B)=1 if and only if A=B and Dice(A,B)=0 if and only if AB=.

  2. Prove that 1Dice(A,B) is not a metric (i.e., it violates the triangle inequality). Hint: Consider three sets in {1,2,3,4}.

  3. Show the relationship between the Dice coefficient and the Jaccard index (intersection over union): (DICE IOU Relation)Dice(A,B)=2IoU(A,B)1+IoU(A,B),whereIoU(A,B)=|AB||AB|.

  4. Prove that 1IoU(A,B) is a metric. Hint: Show that |AB|=|AB||AB| satisfies the triangle inequality, where AB denotes the symmetric difference.

  5. Consider the soft Dice loss in (DICE LOSS). Compute its gradient Dice/p^i 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 1×4 image (four pixels in a row). Two equally qualified experts annotate the image as follows: (Expert1)𝒚(1)=(0,1,1,0),𝒚(2)=(0,0,1,1). Expert 1 believes the object occupies pixels 2–3; Expert 2 believes it occupies pixels 3–4. Both agree that pixel 3 is foreground.

  1. Compute the pixel-wise average 𝒚=12(𝒚(1)+𝒚(2)) and threshold it at 0.5 to produce a “consensus” mask. What is the resulting mask?

  2. 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?

  3. Now consider a more extreme example with three experts: 𝒚(1)=(1,1,0,0),𝒚(2)=(0,0,1,1),𝒚(3)=(0,1,1,0). Compute the pixel-wise average and threshold at 0.5. Show that the resulting consensus mask is identical to 𝒚(3), effectively discarding the views of experts 1 and 2.

  4. Argue that a generative model that can sample all three expert-like masks provides strictly more clinical information than any single consensus mask.

  5. 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 1% of pixels and the background occupies 99%. A model predicts p^i=0.01 for all pixels (foreground probability equal to the class prior).

  1. Compute the cross-entropy loss CE for this prediction.

  2. Compute the soft Dice loss Dice for this prediction (set ϵ=0).

  3. Now suppose the model predicts p^i=0 for all pixels (predicting everything as background). Compute both losses. Which loss function more strongly penalises this degenerate prediction?

  4. Discuss the implications for training segmentation models on datasets with extreme class imbalance.

Exercise 4 (Entropy of ambiguous segmentations).

Consider a 2×2 binary segmentation task. The mask 𝒚=(y1,y2,y3,y4){0,1}4 has 24=16 possible configurations. Suppose the true conditional distribution p(𝒚|𝒙) places equal probability on two masks: (TWO MODE DIST)p(𝒚|𝒙)=12δ𝒚,(1,1,0,0)+12δ𝒚,(0,0,1,1).

  1. Compute the joint entropy H(𝒚|𝒙).

  2. Compute the marginal entropy H(yi|𝒙) for each pixel i. What is iH(yi|𝒙)?

  3. Compute the multi-information I(y1;y2;y3;y4|𝒙)=iH(yi|𝒙)H(𝒚|𝒙). Interpret this quantity in terms of the spatial structure of the uncertainty.

  4. A discriminative model with independent pixel-wise outputs matches the marginals: q(yi=1|𝒙)=0.5 for all i. Sample from q(𝒚|𝒙)=iq(yi|𝒙). 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?

  5. Compute KL(pq). Is it positive? Interpret.

Exercise 5 (Generative model sample size).

A generative segmentation model produces S samples 𝒚(1),,𝒚(S)p𝜽(𝒚|𝒙).

  1. The pixel-wise uncertainty at pixel i can be estimated as the sample variance σ^i2=1S1s=1S(yi(s)yi)2. For binary masks, show that this simplifies to σ^i2=SS1p^i(1p^i) where p^i=1Ssyi(s).

  2. How large must S be to estimate a probability of 0.05 with a 95% confidence interval of width at most 0.02? Hint: Use the normal approximation to the binomial.

  3. Discuss the trade-off between computational cost (larger S requires more forward passes through the generative model) and estimation accuracy. In what clinical scenarios might a small S (e.g., S=4) 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:

  1. Output structure: What kind of label map does the model produce? (Semantic, instance, or panoptic.)

  2. Spatial dimensionality: How many spatial and temporal dimensions does the input occupy? (2D, 3D, 2D+t, or 4D.)

  3. Clinical target: What anatomy or pathology is being segmented? (Cells, lungs, brain, abdomen, heart, vessels, endoscopy, histology.)

  4. 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.

A four-axis taxonomy of medical image segmentation tasks. Each axis captures an orthogonal dimension of variation: what labels are produced (output structure), how many spatial and temporal dimensions the data spans (spatial dimension), what anatomy or pathology is targeted (clinical target), and how the user interacts with the system (annotation interface). Any concrete segmentation task occupies a specific combination of choices across all four axes.

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 𝐗H×W×C be an input image with C channels, spatial height H, and spatial width W. Let 𝒦={0,1,,K1} be a set of K semantic classes, where class 0 typically denotes background. A semantic segmentation of 𝐗 is a map (Semantic)𝒮:{1,,H}×{1,,W}𝒦, assigning each spatial location (i,j) to exactly one class 𝒮(i,j)𝒦. Equivalently, 𝒮 can be represented as a one-hot tensor 𝐘{0,1}H×W×K satisfying k=0K1Yi,j,k=1 for all (i,j).

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 𝐗H×W×C be an input image. An instance segmentation of 𝐗 is a collection of N binary masks {(𝒎n,kn)}n=1N, where each mask 𝒎n{0,1}H×W delineates the spatial extent of instance n, and kn𝒦{0} is its class label. Masks may overlap in general, but in standard settings we require (Instance)n=1Nmn,i,j1for all (i,j), 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 N 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 𝒦=𝒦stuff𝒦thing be a partition of the class set into stuff and thing categories. A panoptic segmentation of image 𝐗 is a map (Panoptic)𝒫:{1,,H}×{1,,W}𝒦×, where 𝒫(i,j)=(k,z) assigns pixel (i,j) to class k with instance identifier z. For stuff classes k𝒦stuff, all pixels of class k share the same instance identifier z=0. For thing classes k𝒦thing, distinct objects of the same class receive distinct identifiers z{1,2,}.

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 𝐗D×H×W where D 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 𝐗D×H×W×C.

  • 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 512×512×300 contains approximately 78 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 0.71.0 mm but slice thickness of 2.55.0 mm, 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+t 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 𝐒t denotes the segmentation mask at frame t, then a temporally consistent segmentation satisfies (Consistency)𝐒t+1𝐖t(𝐒t)Fϵ, where 𝐖t is the optical flow warp from frame t to frame t+1 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+t 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 512×512×100×25 voxel-frames, over 600 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.

Spatial dimensionality in medical image segmentation. Left: a single 2D image (e.g., chest X-ray or dermoscopy photograph) with a segmented region shown in green. Centre: a 3D volume (e.g., CT or MRI) composed of stacked slices. Right: a 4D spatio-temporal sequence of 3D volumes evolving over time (e.g., dynamic cardiac MRI). Each increase in dimensionality multiplies computational cost and data requirements, posing progressively harder challenges for generative models.

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@ DomainModalityKey ChallengesGenerative Interventions
Cells & MicroscopyFluorescence, phase-contrast, EMDense clusters, division events, domain shift across stainsStyle transfer (GAN), synthetic cell generation (DM)
[4pt] Lung & ThoraxCT, chest X-rayNodule size variation, multi-radiologist variability, low contrastNodule synthesis (GAN/DM), multi-rater ambiguity modelling
[4pt] Brain & NeuroMRI (T1, T2, FLAIR, T1ce)Tumour subregion heterogeneity, white matter lesion variability, small vessel segmentationSynthetic tumour insertion (DM), multi-sequence generation
[4pt] AbdomenCT, MRIExtreme class imbalance (pancreas vs. liver), organ size disparity, contrast variationOrgan-conditioned synthesis (GAN/DM), data augmentation for rare organs (VAE)
[4pt] CardiacMRI (cine), echo\-cardiographyTemporal motion, thin myocardium, phase variabilityCardiac cycle generation (DM), temporal augmentation
[4pt] VesselsCTA, MRA, fundus, OCT-AExtreme topology sensitivity, thin tubular structures, bifurcation fidelityTopology-aware generation, synthetic vascular trees (GAN)
[4pt] EndoscopyVideo endoscopyMotion blur, deformation, specular reflections, occlusionFrame synthesis (GAN/DM), video augmentation
[4pt] PathologyH&E, IHC, whole-slide imagesGigapixel resolution, staining domain shift, dense nucleiStain normalisation (GAN), synthetic tile generation (DM)
Overview of major clinical segmentation domains. For each domain, we list the primary imaging modality, the key technical challenges, and the principal generative interventions that address those challenges. GAN = generative adversarial network, DM = diffusion model, VAE = variational autoencoder.

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:

  1. 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.

  2. 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.

  3. 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 1500 cm3 in a CT volume while the pancreas occupies barely 70 cm3, a ratio of over 20:1 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 CO2), 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 40× magnification can contain 100,000×100,000 pixels or more, a single image larger than the entire ImageNet dataset in pixel count.

Segmentation targets.

The two primary targets are:

  1. 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.

  2. 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.

Six major imaging modalities in medical image segmentation. Each modality produces data with distinct dimensionality, resolution, contrast characteristics, and noise profiles. Generative models must be adapted to the specific properties of each modality: volumetric coherence for CT and MRI, real-time efficiency for ultrasound and endoscopy, gigapixel scale for microscopy, and projection geometry for X-ray.

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 3 mm in diameter. Consider a 9 mm 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 120 mm2.

  • Radiologist B included the surrounding ground-glass halo, yielding a larger mask of approximately 280 mm2.

  • Radiologist C followed the solid core but added a narrow margin, producing 170 mm2.

  • Radiologist D agreed closely with Radiologist B but excluded a small region near an adjacent vessel, yielding 250 mm2.

The pairwise Dice coefficients among these four annotations range from 0.51 (A vs. B) to 0.89 (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 p(mask|image) 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:

  1. 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.

  2. 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.

  3. 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:

  1. 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.

  2. 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.

  3. 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 5080% 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 𝐗H×W×C be an input image and let 𝒰={(ui,vi,i)}i=1M be a set of M user-provided spatial prompts, where (ui,vi) is a pixel location and i{+1,1} indicates a positive (foreground) or negative (background) prompt. An interactive segmentation model is a function (Interactive)f𝜽:H×W×C×(2×{+1,1})M[0,1]H×W, mapping the image and the set of prompts to a soft segmentation mask. The model may optionally accept bounding box prompts ={(xmin,ymin,xmax,ymax)} 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 pθ(mask|image,prompt) 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 pθ(mask|image) 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.

  1. 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.

  2. 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.

  3. 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.

  4. 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).

  1. Explain why standard pixel-wise cross-entropy loss is poorly suited to this task. What loss functions would you use instead, and why?

  2. 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.

  3. 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)y(i,j)={1if I(i,j)τ,0if I(i,j)<τ, where I(i,j) denotes the intensity at pixel (i,j) and y(i,j){0,1} 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 {0,1,,L1} with normalised histogram pi=ni/N, where ni is the number of pixels with intensity i and N is the total pixel count. For a threshold τ, define the class probabilities (Probs)ω0(τ)=i=0τpi,ω1(τ)=i=τ+1L1pi=1ω0(τ), and the class means (Means)μ0(τ)=1ω0(τ)i=0τipi,μ1(τ)=1ω1(τ)i=τ+1L1ipi. The between-class variance is (Variance)σB2(τ)=ω0(τ)ω1(τ)[μ0(τ)μ1(τ)]2, and the optimal threshold is τ=argmaxτσB2(τ).

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 τ(i,j) for each pixel based on the statistics of a neighbourhood 𝒩(i,j): (Adaptive Threshold)τ(i,j)=1|𝒩(i,j)|(i,j)𝒩(i,j)I(i,j)C, where C 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 (i0,j0) 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)(t+1)=(t){(i,j)𝒩((t)):|I(i,j)I((t))|<δ}, where 𝒩((t)) is the set of pixels neighbouring the current region, and I((t)) is the mean intensity within the region at iteration t. 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 𝐯(s)=(x(s),y(s)) for s[0,1] that minimises the energy functional (Snake Energy)Esnake=01[α(s)|𝐯(s)|2+β(s)|𝐯(s)|2]dsEinternal+01Eext(𝐯(s))dsEexternal, where:

  • α(s)0 is the elasticity parameter, penalising stretching of the contour (first-order smoothness);

  • β(s)0 is the rigidity parameter, penalising bending of the contour (second-order smoothness);

  • Eext(𝐯) is the external energy derived from image features, typically defined as Eext(𝐯)=|I(𝐯)|2 so that the contour is attracted to strong edges.

The internal energy Einternal 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 Eexternal drives the contour toward image features. The balance between these two competing forces determines the final segmentation.

Euler–Lagrange equation.

The necessary condition for 𝐯(s) to minimise Esnake is given by the Euler–Lagrange equation: (Euler Lagrange)s[α(s)𝐯(s)]+2s2[β(s)𝐯(s)]+Eext(𝐯(s))=𝟎. For constant α and β, this simplifies to (Euler Lagrange Const)α𝐯(s)+β𝐯(s)+Eext(𝐯(s))=𝟎. This fourth-order differential equation is typically solved numerically by discretising the contour into N control points 𝐯i=𝐯(si) and iterating a gradient descent scheme: (Snake Iteration)𝐯i(t+1)=𝐯i(t)γ(𝐀𝐯(t)+Eext(𝐯i(t))), where 𝐀 is a pentadiagonal matrix encoding the discretised internal forces and γ>0 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 Eext 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)min𝐟[μ|𝐟|2+|I|2|𝐟I|2]d𝐱, where 𝐟(𝐱) is the GVF field and μ controls the trade-off between smoothness and fidelity to the edge map. The GVF field replaces Eext 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 ϕ(𝐱,t): (Level SET)𝒞(t)={𝐱Ω:ϕ(𝐱,t)=0}. The evolution of ϕ is governed by a partial differential equation that encodes both geometric regularity and image forces: (Level SET PDE)ϕt=g(I)|ϕ|(κ+V0)+gϕ, where κ=(ϕ/|ϕ|) is the mean curvature of the level set, V0 is a constant inflation term, and g(I) is an edge-stopping function, typically g(I)=1/(1+|GσI|2), 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).

Evolution of an active contour (snake). (a) The contour is initialised as a circle surrounding the target structure; external forces (arrows) pull it inward. (b) At an intermediate iteration, the contour has deformed toward the true boundary under the influence of image gradient forces balanced against internal smoothness constraints. (c) At convergence, the contour closely approximates the true organ boundary. The energy functional ((Snake Energy)) reaches a local minimum where internal and external forces balance.

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 𝐟(i,j)D and predict a label y(i,j){1,,K}. The feature vector typically includes:

  1. Intensity features: raw intensity, local mean, local variance, gradient magnitude, Laplacian, computed at multiple scales using Gaussian pyramids.

  2. 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).

  3. Context features: the intensity difference between the current pixel and randomly offset pixels, encoding long-range spatial relationships without explicit neighbourhood enumeration.

  4. Location features: normalised coordinates (i/H,j/W) 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 B 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)p^(y=k|𝐟)=1Bb=1Bpb(y=k|𝐟), where pb is the prediction of the b-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 M atlas pairs {(m,m)}m=1M, where m is the atlas image and m is the atlas label map, the segmentation of a target image proceeds in two stages:

  1. Registration: For each atlas m, compute a deformation field 𝝓m that maps m to , typically by minimising (Registration)𝝓m=argmin𝝓[𝒟(m𝝓,)+λ(𝝓)], where 𝒟 is a dissimilarity metric (e.g., mutual information, normalised cross-correlation) and is a regulariser enforcing smoothness of the deformation.

  2. Label fusion: Apply each deformation to the corresponding atlas labels, ^m=m𝝓m, and combine the warped labels using a fusion rule. The simplest is majority voting: (Majority VOTE)y^(𝐱)=argmaxkm=1M𝟏[^m(𝐱)=k]. 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.

  1. 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.

  2. 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.

  3. 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.

  4. Inability to learn from large datasets. Classical methods cannot effectively leverage the growing availability of large annotated datasets. A random forest trained on 10,000 annotated images is not qualitatively different from one trained on 1,000; 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 224×224 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 n outputs is mathematically equivalent to a 1×1 convolution with n filters. Replacing the FC layers with 1×1 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 P stages of 2× pooling, the output is downsampled by a factor of 2P. For VGG-16 with P=5, the output is 32× 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 32×. Produces coarse segmentations with poor boundary delineation.

  • FCN-16s: Combine the 2×-upsampled final prediction with predictions from the pool4 layer (stride 16), then upsample 16×.

  • 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 l{1,,L}, it applies two 3×3 convolutions (each followed by a ReLU activation), then a 2×2 max pooling with stride 2 for downsampling. At each downsampling stage, the number of feature channels is doubled. If the input has C0 channels and the first stage produces C1 channels, then stage l produces Cl=C12l1 channels. In the original U-Net, C1=64, so the channel progression is 641282565121024.

Formally, let 𝐡lencCl×Hl×Wl denote the feature map at the l-th encoder stage, where Hl=H0/2l and Wl=W0/2l. The encoder operations are: (Encoder)𝐳l=σ(𝐖l(2)σ(𝐖l(1)𝐡l1enc+𝐛l(1))+𝐛l(2)),𝐡lenc=MaxPool2×2(𝐳l), where denotes convolution, σ is the ReLU activation, and 𝐖l(1),𝐖l(2) are the convolution kernels at stage l. Note that 𝐳l (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 3×3 convolutions without any pooling. In the original U-Net, this produces a 1024-channel feature map at the coarsest spatial resolution (H0/24×W0/24 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 l{L,L1,,1}, it applies:

  1. A 2×2 transposed convolution (“up-convolution”) that halves the number of channels and doubles the spatial dimensions.

  2. Concatenation of the upsampled feature map with the corresponding encoder feature map 𝐳l 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.

  3. Two 3×3 convolutions, each followed by ReLU\@.

Formally, the decoder operations at stage l are: (Decoder)𝐮l=UpConv2×2(𝐡l+1dec),𝐜l=Concat(Crop(𝐳l),𝐮l),𝐡ldec=σ(𝐖l(4)σ(𝐖l(3)𝐜l+𝐛l(3))+𝐛l(4)). The final output is a 1×1 convolution that maps the C1-channel feature map to K channels (one per class), followed by a softmax or sigmoid activation: (Output)𝐲^(𝐱)=Softmax(𝐖out𝐡1dec+𝐛out)K×H0×W0.

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)=𝐱Ωw(𝐱)k=1Kyk(𝐱)logy^k(𝐱), where yk(𝐱) is the one-hot ground-truth label at pixel 𝐱 for class k, y^k(𝐱) is the predicted probability, and w(𝐱) is a weight map. The weight map is defined as (Weightmap)w(𝐱)=wc(𝐱)+w0exp((d1(𝐱)+d2(𝐱))22σ2), where wc(𝐱) compensates for class frequency, and d1(𝐱),d2(𝐱) are the distances to the borders of the two nearest cells, with w0=10 and σ5 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 (565×584 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 0.82 on this dataset, comparable to the inter-observer agreement between human annotators (0.79).

The key challenge is that retinal vessels span a wide range of calibres: the main arcades are 510 pixels wide, while capillaries may be only 12 pixels wide. The multi-scale nature of the U-Net encoder, which captures features at 4 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 565×584 images, patches of size 128×128 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.

The U-Net architecture. The contracting path (left, blue) doubles the number of feature channels at each stage while halving the spatial dimensions via max pooling (P). The expanding path (right, green) mirrors the encoder, using transposed convolutions (U) to upsample and skip connections (dashed grey arrows) to concatenate corresponding encoder features. The bottleneck (orange) at the base captures the most abstract representation. A final 1×1 convolution produces the K-class segmentation map. Channel dimensions are annotated at each stage.

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 (3×3×3), all 2D pooling becomes 3D pooling (2×2×2), and skip connections carry 3D feature volumes. However, the computational implications are dramatic: a 3×3×3 convolution has 27/9=3× more parameters than a 3×3 convolution, and feature maps grow by a factor proportional to the depth of the volume. Training V-Net on a 256×256×256 volume with the same channel dimensions as U-Net requires roughly 100× more memory than processing a single 256×256 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 y^n[0,1] and ground-truth labels yn{0,1} for voxels n=1,,N, the Dice loss is (DICE LOSS)Dice=12n=1Ny^nyn+ϵn=1Ny^n+n=1Nyn+ϵ, where ϵ>0 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 15% 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 k adjacent slices as multi-channel input. This captures local inter-slice context while maintaining the memory efficiency of 2D convolutions. Typical choices are k=3 or k=5. 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:

  1. 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.

  2. 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.

  3. 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).

  4. Postprocessing: Whether to apply connected-component analysis to remove small spurious predictions, determined by cross-validation performance.

  5. 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.

The nnU-Net self-configuration pipeline. The framework extracts a dataset fingerprint (voxel spacing, image dimensions, modality, class frequencies) and uses rule-based heuristics to configure three U-Net variants (2D, 3D full-resolution, and 3D cascade). All three are trained with 5-fold cross-validation. An ensemble selection step determines the best combination, followed by optional postprocessing (connected-component analysis to remove small spurious predictions).

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 𝐱lCl×Hl×Wl from the skip connection at level l, and the gating signal 𝐠lCg×Hl×Wl from the decoder at the level below (typically upsampled to match the spatial dimensions of 𝐱l). The attention gate computes a spatial attention map 𝜶l[0,1]Hl×Wl that modulates the encoder features: (Attention GATE)𝐪l=σ1(𝐖x𝐱l+𝐖g𝐠l+𝐛),𝜶l=σ2(𝝍𝐪l+bψ),𝐱^l=𝜶l𝐱l, where 𝐖x,𝐖g are 1×1 convolution weights that project both inputs to a common intermediate dimensionality, σ1 is the ReLU activation, 𝝍 is a 1×1 convolution that maps to a single channel, σ2 is the sigmoid function, and denotes element-wise multiplication (broadcasting over channels). The attention coefficient 𝜶l(i,j) is close to 1 for spatial locations that are relevant to the segmentation and close to 0 for irrelevant locations.

The intuition is that the gating signal 𝐠l, 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 𝐱l 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 0.79 (enhancing), 0.85 (core), and 0.90 (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.

The attention gate mechanism. Encoder features 𝐱l and the decoder gating signal 𝐠l are projected to a common space via 1×1 convolutions, added, passed through ReLU, reduced to a single channel by 𝝍, and squeezed through a sigmoid to produce the attention map 𝜶l[0,1]. The encoder features are then modulated element-wise by 𝜶l before being passed to the decoder via the skip connection. Spatial positions deemed irrelevant by the gate receive near-zero attention, effectively suppressing background noise.

Transformer-Based Segmentation

Convolutional neural networks, including U-Net and its variants, operate on local neighbourhoods: a 3×3 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 𝐡LencCL×HL×WL be the output of the CNN encoder at the final stage. TransUNet divides this into N=HLWL/P2 non-overlapping patches of size P×P, projects each to a D-dimensional embedding, adds positional encodings, and processes the sequence through M transformer layers: (Transunet)𝐳0=[𝐄𝐩1;𝐄𝐩2;;𝐄𝐩N]+𝐄pos,𝐳m=TransformerBlock(𝐳m1),m=1,,M,𝐡trans=Reshape(𝐳M)D×HL×WL, where 𝐄D×(CLP2) is the patch embedding matrix and 𝐄posD×N 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 𝒪(n) complexity in the number of patches (versus 𝒪(n2) 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 S^ and the ground-truth segmentation S. 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 A,BΩ, the Dice similarity coefficient (also called the Srensen–Dice coefficient) is (DICE)DSC(A,B)=2|AB||A|+|B|=2TP2TP+FP+FN, where TP=|AB| is the number of true positives, FP=|AB| is the number of false positives, and FN=|BA| is the number of false negatives. The Dice coefficient takes values in [0,1], where 1 indicates perfect agreement and 0 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 A,BΩ, the Intersection over Union (IoU), also called the Jaccard index, is (IOU)IoU(A,B)=|AB||AB|=TPTP+FP+FN. The IoU takes values in [0,1], where 1 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 A,BΩ, the Dice coefficient D=DSC(A,B) and the IoU J=IoU(A,B) satisfy (DICE IOU Relation)D=2J1+JandJ=D2D. Consequently, DJ for all J[0,1], with equality only when J=0 or J=1.

Proof.

Let a=|AB|, b=|AB|, and c=|BA|. Then |A|+|B|=2a+b+c and |AB|=a+b+c. We have D=2a2a+b+c,J=aa+b+c. Computing 2J/(1+J): 2J1+J=2aa+b+c1+aa+b+c=2aa+b+c2a+b+ca+b+c=2a2a+b+c=D. For the inequality, observe that DJ=2a2a+b+caa+b+c=a(b+c)(2a+b+c)(a+b+c)0, with equality if and only if a=0 (both are 0) or b+c=0 (both are 1).

Definition 11 (Hausdorff Distance).

For two non-empty subsets A,Bd, the Hausdorff distance is (Hausdorff)dH(A,B)=max{sup𝐚Ainf𝐛B𝐚𝐛,sup𝐛Binf𝐚A𝐛𝐚}. Equivalently, dH(A,B)=max{dH(A,B),dH(B,A)}, where dH(A,B)=sup𝐚Ainf𝐛B𝐚𝐛 is the directed Hausdorff distance from A to B.

The Hausdorff distance measures the worst-case boundary error: dH(A,B)=ϵ means that every point in A is within distance ϵ of some point in B, 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 dH95 is often preferred in practice, which replaces the sup 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 (Recall)=TPTP+FN,Specificity=TNTN+FP,Precision=TPTP+FP. 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)Dice(𝐲^,𝐲)=12ny^nyn+ϵny^n+nyn+ϵ, where y^n[0,1] are predicted probabilities and yn{0,1} are ground-truth labels. The gradient with respect to a single prediction y^n is (DICE Gradient)Dicey^n=2yn(my^m+mym+ϵ)(my^mym+ϵ2)(my^m+mym+ϵ)2. This gradient has two important properties:

  1. 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.

  2. 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 A=my^mym+ϵ/2 and B=my^m+mym+ϵ. Then =12A/B. By the quotient rule: y^n=2Ay^nBABy^nB2. We have A/y^n=yn and B/y^n=1, so y^n=2ynBAB2=2yn(my^m+mym+ϵ)(my^mym+ϵ2)(my^m+mym+ϵ)2. For property (1), observe that B=Θ(|S|) where |S|=mym is the foreground size, so the gradient scales as Θ(1/|S|), normalising for object size. For property (2), the Hessian 2/y^ny^n is not positive semidefinite in general: for nn, the cross terms have mixed signs depending on the labels.

Caution.

High Dice does not mean clinically useful segmentation. A Dice score of 0.90 on liver segmentation sounds impressive, but it may hide clinically significant errors: a segmentation that misses a 5,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 0.85 that perfectly captures all surface details may be more useful than one with Dice 0.92 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 L=4 stages. Each stage applies two 3×3 convolutions (with stride 1 and no padding) followed by 2×2 max pooling with stride 2. The bottleneck applies two additional 3×3 convolutions.

  1. Compute the receptive field of the encoder output (before the bottleneck) by tracking how each operation expands the effective input region. Recall that a k×k convolution with stride 1 increases the receptive field by k1 at the current scale, and a 2×2 pooling with stride 2 doubles the scale factor.

  2. How large is the receptive field of the bottleneck output? Compare this to the input image size of 572×572 used in the original U-Net and discuss whether the bottleneck “sees” the entire image.

  3. 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 ρ(0,1) of the image.

  1. Show that a trivial predictor that outputs y^n=0 for all pixels achieves cross-entropy loss CE=ρlog(ϵ)(1ρ)log(1) (where ϵ is the clamped minimum probability) but Dice loss Dice=1ϵ/(ρ+ϵ)1.

  2. For ρ=0.01 (a 1% foreground fraction, typical of small lesion segmentation), compute the cross-entropy loss of a predictor that outputs y^n=0.5 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?

  3. Explain why the combination =Dice+λCE 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 𝐱lC×H×W, gating signal 𝐠lC×H×W (already upsampled), intermediate dimension Cint, and the attention computation from (Attention GATE).

  1. Count the total number of learnable parameters in the attention gate. Express your answer in terms of C and Cint. Compare this to the number of parameters in a single 3×3×C×C convolutional layer and argue that the attention gate adds minimal computational overhead.

  2. Suppose the attention gate learns 𝜶l=𝟏 (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?

  3. Now suppose the ground truth segmentation mask is available at training time. Design an auxiliary loss that encourages the attention maps 𝜶l 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 N items to one of K categories, let po denote the observed fraction of items on which the two raters agree, and let pe 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)κ=pope1pe. When applied to segmentation, each pixel is treated as an “item” to be classified (foreground vs. background). A value of κ=1 indicates perfect agreement, κ=0 indicates agreement no better than chance, and κ<0 indicates systematic disagreement.

Definition 13 (Inter-Rater Agreement: Fleiss' Kappa).

For R2 raters (not necessarily the same pair for every item), Fleiss' kappa generalises Cohen's measure. Let nij be the number of raters who assign item i to category j. Define (PO)Po=1Ni=1N1R(R1)j=1Knij(nij1), which is the average pairwise agreement across items. Let p^j=1NRi=1Nnij be the overall proportion of assignments to category j, and define (PE)Pe=j=1Kp^j2. Then (Kappa)κF=PoPe1Pe. 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-pe 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:

  1. Blinded read. Each radiologist independently marks nodules and traces their boundaries without knowledge of the other radiologists' annotations.

  2. 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 0.600.75, depending on nodule morphology. For nodules with irregular or spiculated margins, the pairwise Dice can drop below 0.50.

Four radiologists' annotations of the same lung nodule, overlaid on a schematic density map. Rater 1 (blue, dashed) traces only the solid core; Rater 3 (orange, dash-dotted) includes the surrounding ground-glass halo; Raters 2 and 4 fall in between but with different shape emphases. All four annotations are clinically defensible.

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:

  1. Enhancing tumour (ET). The contrast-enhancing rim on T1-weighted gadolinium images. This subregion has the highest agreement (κF0.80 in well-controlled studies) because the contrast agent provides a relatively sharp boundary.

  2. Tumour core (TC). The union of enhancing tumour and necrotic core. Agreement is moderate (κF0.70) because the necrotic interior can be difficult to distinguish from cystic components or haemorrhage.

  3. Whole tumour (WT). The union of tumour core and peritumoral oedema visible on FLAIR. Agreement is lowest (κF0.600.65) 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 p𝜽(y|x) should match the empirical distribution of expert annotations p^(y|x)-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 {y(r)}r=1R be the binary segmentation masks drawn by R annotators, where y(r){0,1}H×W. The averaged mask is (MASK)y=1Rr=1Ry(r)[0,1]H×W. For a given pixel i, suppose the annotators split into two camps: a fraction α includes the pixel (yi(r)=1) and a fraction 1α excludes it (yi(r)=0). The averaged value at that pixel is yi=α. If we threshold at 0.5 to recover a binary mask, the pixel is included when α>0.5 and excluded otherwise.

Now consider the situation where α0.5 for a spatially coherent region-a connected patch of tissue about which experts genuinely disagree. The averaged mask assigns values near 0.5 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.

Why averaging fails for bimodal annotations. Left: at a disputed pixel, the distribution of labels is bimodal (either 0 or 1). Centre: the averaged mask assigns a value near 0.5 throughout the disputed region-a mask that no expert would draw. Right: the actual expert opinions are spatially coherent: “include the entire region” or “exclude it.” Averaging destroys this structure.

To make this precise, consider the space of all binary masks 𝒴={0,1}H×W for an image of resolution H×W. The expert annotations define an empirical distribution (DIST)p^(y)=1Rr=1Rδ(yy(r)), where δ is the Kronecker delta on 𝒴. The averaged mask y is the mean of this distribution: (MASK)y=𝔼p^[y]=y𝒴yp^(y). But the mean of a multimodal distribution can fall in a region of low probability. Consider the simplest case: two annotators, one draws mask y(1) with a region included, the other draws y(2) with the region excluded. The mean y=12(y(1)+y(2)) has value 0.5 in the disputed region-a mask that has zero probability under p^.

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:

  1. Expert annotations of ambiguous medical images are multimodal: the distribution over masks concentrates on a finite number of distinct segmentations, not a smooth continuum.

  2. The mean of a multimodal distribution may lie outside the support of the distribution, producing a mask that no expert would endorse.

  3. 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.

  4. 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 𝖧(p^)=y𝒴p^(y)logp^(y) denote the entropy of the empirical annotation distribution. The averaged mask y is a sufficient statistic for the product-of-marginals approximation q(y)=iq(yi) where q(yi=1)=yi. The information lost by averaging is exactly the multi-information (total correlation): (LOSS)TC(p^)=i=1N𝖧(p^yi)𝖧(p^)=DKL(p^i=1Np^yi)0, where p^yi is the marginal distribution of pixel i. This quantity is zero only when the pixels are independent under p^-that is, when there is no spatial structure in the disagreement. In practice, TC(p^) 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 xH×W×C denote an input medical image with spatial dimensions H×W and C channels (e.g., C=4 for multi-modal MRI). Let y{0,1}H×W×K denote a one-hot encoded segmentation mask with K classes. We wish to learn the conditional distribution (Target)p(y|x), 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 {p𝜽(y|x)}𝜽 over segmentation masks y𝒴 conditioned on images x𝒳, together with an inference procedure that, given a new image x, produces a set of samples {y(s)}s=1Sp𝜽(|x). 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 f𝜽:𝒳𝒴 maps each image to a single mask. When trained with a loss that averages over multiple annotators' masks, the model learns the conditional mean 𝔼[y|x]-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)p𝜽(yi=k|x)=exp(f𝜽(k)(x)i)k=1Kexp(f𝜽(k)(x)i), where f𝜽(k)(x)i is the logit for class k at pixel i. 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 p(y|x) be the true conditional distribution over binary masks, and let q(y|x)=i=1Nq(yi|x) be the best product-of-marginals approximation, where N=HW is the number of pixels. If the true distribution has non-trivial spatial correlation-i.e., there exist pixels i,j with Covp(yi,yj|x)0-then (Indep)DKL(p(y|x)q(y|x))>0, and the variance of any linear functional (y)=iaiyi (such as region volume) satisfies (Underestimate)𝖵arq[(y)|x]=i=1Nai2𝖵arq[yi|x]<i=1Nai2𝖵arp[yi|x]+2i<jaiaj𝖢ovp(yi,yj|x)=𝖵arp[(y)|x], whenever the net covariance i<jaiaj𝖢ovp(yi,yj|x)>0. In particular, the variance of the predicted lesion volume is underestimated.

Proof.

The KL divergence between p and any product distribution q is non-negative and equals zero only when p itself is a product distribution, which contradicts the assumption of non-trivial spatial correlation. For the variance inequality, note that q is a product distribution, so all cross-covariance terms vanish: 𝖢ovq(yi,yj|x)=0 for ij. Expanding 𝖵ar[(y)] under p and q 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.

Comparison of pixel-wise uncertainty (a) with two coherent samples from a probabilistic segmentation model (b, c). The pixel-wise map shows a smooth gradient of uncertainty at the boundary, concealing the fact that the underlying distribution is bimodal: either the entire boundary region is included (sample 1) or excluded (sample 2). Only the coherent samples reveal this structure.

Insight.

Sampling coherent masks reveals structure that uncertainty maps hide. A pixel-wise uncertainty map summarises the marginal p(yi|x) at each pixel but discards the joint structure of p(y|x). 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 𝒛d 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):

  1. U-Net backbone. A standard U-Net f𝜽(x) that takes the input image x and produces a feature map 𝒉H×W×D at the final layer (before the classification head). This feature map encodes the spatial structure of the image at full resolution.

  2. Prior network. A convolutional encoder g𝝓(x) that maps the input image to the parameters of a Gaussian distribution in latent space: (Prior)p𝝓(𝒛|x)=Normal(𝒛|𝝁prior(x),diag(𝝈prior2(x))). This network sees only the image and must predict the range of plausible segmentations from the image alone.

  3. Posterior network. A convolutional encoder h𝝍(x,y) that maps both the image x and a ground-truth mask y to the parameters of a Gaussian distribution: (Posterior)q𝝍(𝒛|x,y)=Normal(𝒛|𝝁post(x,y),diag(𝝈post2(x,y))). This network is used only during training; it provides the variational posterior that guides the prior to encode segmentation-relevant information.

  4. Combining module. The latent sample 𝒛 is broadcast spatially and concatenated with the U-Net feature map 𝒉, then passed through a 1×1 convolution to produce the final logits: (Decode)p𝜽(y|x,𝒛)=i=1HWsoftmax(Wout[𝒉i𝒛]+𝒃out). Given a specific 𝒛, the output is a deterministic (pixel-wise independent) segmentation; the stochasticity enters only through 𝒛.

Architecture of the Probabilistic U-Net. The U-Net backbone (blue) produces a spatial feature map; the prior network (green) encodes image-only uncertainty; the posterior network (orange, dashed, training only) encodes image-and-label information. At test time, 𝒛 is sampled from the prior and combined with the feature map to produce a coherent segmentation. The KL divergence (red, dotted) between posterior and prior is minimised during training.
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 x and an observed segmentation y drawn from the multi-annotator distribution, the ELBO for the Probabilistic U-Net is (ELBO)ELBO(𝜽,𝝓,𝝍;x,y)=𝔼q𝝍(𝒛|x,y)[logp𝜽(y|x,𝒛)]reconstruction termβDKL(q𝝍(𝒛|x,y)p𝝓(𝒛|x))KL regularisation, where β>0 is a weighting factor (set to 1 for the standard ELBO, and β<1 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 p𝝓(𝒛|x) to match the posterior q𝝍(𝒛|x,y), so that at test time-when y is unavailable and we must sample from the prior-the resulting 𝒛 values are informative.

Remark 7.

In practice, β is a critical hyperparameter. Setting β=1 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 [0.01,1.0].

Inference.

At test time, to generate S plausible segmentations for a new image x:

  1. Compute the U-Net feature map 𝒉=f𝜽(x).

  2. Compute the prior parameters 𝝁prior,𝝈prior=g𝝓(x).

  3. For s=1,,S: enumerate

  4. Sample 𝒛(s)Normal(𝝁prior,diag(𝝈prior2)).

  5. Compute y(s)=arg maxkp𝜽(y|x,𝒛(s)) (or sample pixel-wise for soft masks). enumerate

Each sample 𝒛(s) 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 d=6.

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 GED20.28, substantially better than a deterministic U-Net (GED20.45) and a pixel-wise dropout-based uncertainty estimate (GED20.38).

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 L latent variables 𝒛1,𝒛2,,𝒛L, where 𝒛l has spatial resolution matching the l-th level of the U-Net decoder. The generative model factors as (Generative)p(𝒛1:L,y|x)=p(𝒛L|x)l=L11p(𝒛l|𝒛l+1,x)p(y|𝒛1,x), where each p(𝒛l|𝒛l+1,x) is a conditional Gaussian whose parameters depend on the coarser latent 𝒛l+1 and the image x. The coarsest latent 𝒛L captures global shape variation; finer latents 𝒛1,,𝒛L1 progressively refine the boundary.

The inference model (posterior) mirrors this hierarchy: (Posterior)q(𝒛1:L|x,y)=q(𝒛L|x,y)l=L11q(𝒛l|𝒛l+1,x,y).

PHiSeg architecture with a three-level latent hierarchy. The coarsest latent 𝒛3 captures global shape variation (large vs. small segmentation), while finer latents 𝒛2,𝒛1 progressively refine boundary details. Skip connections (dotted) from the encoder provide spatial context at each resolution.
Training objective.

The ELBO for PHiSeg decomposes the KL divergence across levels: (ELBO)PHiSeg=𝔼q(𝒛1:L|x,y)[logp(y|𝒛1,x)]l=1L𝔼q(𝒛>l|x,y)[DKL(q(𝒛l|𝒛l+1,x,y)p(𝒛l|𝒛l+1,x))], where 𝒛>l=(𝒛l+1,,𝒛L). Each KL term encourages the prior at level l to match the corresponding posterior, conditioned on all coarser latents.

Inference.

Sampling proceeds top-down: first sample 𝒛L from the coarsest prior, then progressively sample 𝒛L1,,𝒛1 conditioned on the coarser latents. This produces a coarse-to-fine generation process:

  1. Sample 𝒛Lp(𝒛L|x): determines overall tumour extent.

  2. Sample 𝒛L1p(𝒛L1|𝒛L,x): refines intermediate structure.

  3. Continue until 𝒛1p(𝒛1|𝒛2,x): determines fine boundary details.

  4. Decode: yp(y|𝒛1,x).

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 L=5 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 GED20.22 on the brain lesion task, compared to GED20.28 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 d 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 𝒛L selects the overall extent, and the fine latents 𝒛1,,𝒛L1 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 P and Q be two distributions over segmentation masks, and let d:𝒴×𝒴0 be a distance function on masks (e.g., d(y,y)=1Dice(y,y) or d(y,y)=1IoU(y,y)). The Generalized Energy Distance between P and Q is (GED)DGED2(P,Q)=2𝔼yP,yQ[d(y,y)]𝔼y,yP[d(y,y)]𝔼y,yQ[d(y,y)]. In practice, P is the empirical distribution of R expert annotations {y(r)}r=1R and Q is the empirical distribution of S model samples {y^(s)}s=1S. The expectations are estimated by averaging over all pairs: (Empirical)D^GED2=2RSr=1Rs=1Sd(y(r),y^(s))1R2r,rd(y(r),y(r))1S2s,sd(y^(s),y^(s)).

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 DGED2(P,Q) is a proper scoring rule for distributional predictions in the following sense:

  1. DGED2(P,Q)0 for all distributions P,Q over 𝒴.

  2. DGED2(P,Q)=0 if and only if P=Q (assuming d is a metric on 𝒴).

  3. For any reference distribution P, the minimiser of QDGED2(P,Q) over all distributions Q is Q=P.

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 P with respect to distance d as E(P)=𝔼y,yP[d(y,y)]. The GED can be rewritten as (Energy)DGED2(P,Q)=2𝔼yP,yQ[d(y,y)]E(P)E(Q). When d is a metric of negative type (which includes all metrics of the form d(y,y)=yyα for α(0,2] 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 P=Q, then the cross-term equals E(P) and both self-terms equal E(P), giving DGED2=2E(P)E(P)E(P)=0. Conversely, DGED2=0 implies P=Q when d is a metric of negative type, again by the Székely–Rizzo characterisation.

Properness. For any Q, write (Proof)DGED2(P,Q)=2𝔼P×Q[d]E(P)E(Q)=(2𝔼P×Q[d]2E(P))+(E(P)E(Q)). Setting Q=P makes the first parenthetical zero (since 𝔼P×P[d]=E(P)) and the second parenthetical zero. For QP, non-negativity ensures DGED2>0, so P is the unique minimiser.

Remark 9.

The empirical GED estimator in is unbiased but has variance that scales as O(1/RS). When the number of reference annotations R is small (e.g., R=4 in LIDC-IDRI), the within-reference term 1R2r,rd(y(r),y(r)) has high variance. It is therefore important to use a large number of model samples S (typically S=16 or S=100) to reduce the contribution of the within-prediction term to the overall variance.

Choosing the base distance d.

The GED is parameterised by the choice of base distance d on mask space, and this choice matters in practice. Common options include:

  • d(y,y)=1Dice(y,y): 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).

  • d(y,y)=1IoU(y,y): similar to the Dice-based distance but with a different normalisation. Penalises false positives and false negatives more symmetrically for large objects.

  • d(y,y)=1Ni=1N|yiyi|: the normalised Hamming distance. Treats all pixels equally regardless of lesion size. Simple but does not respect the clinical importance of boundary pixels.

  • d(y,y)=HD95(y,y): 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 d=1Dice 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 p(y|x) without explicitly modelling who drew each annotation. An alternative approach is to model annotator-specific behaviour directly: learn a distribution p(y|x,a) conditioned on annotator identity a{1,,A}. 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 {(xn,yn(an))}n=1N where each image xn is annotated by annotator an producing mask yn(an). We model (Model)p𝜽(y|x,a)=p𝜽(y|x,𝒛)p𝝓(𝒛|x,a)d𝒛, where the latent variable 𝒛 now depends on both the image and the annotator identity. One concrete instantiation is to decompose 𝒛=[𝒛img,𝒛ann] into an image-dependent component and an annotator-dependent component: (Decompose)p(𝒛img|x)=Normal(𝝁img(x),diag(𝝈img2(x))),p(𝒛ann|a)=Normal(𝝁a,diag(𝝈a2)), where 𝝁a,𝝈a are learnable parameters specific to annotator a.

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)p(y|x,a)=softmax(f𝜽(x)+g𝝓a(f𝜽(x))), where f𝜽(x) is a shared feature extractor and g𝝓a is a lightweight annotator-specific module (e.g., a 1×1 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 a as applying a learnable pixel-wise confusion matrix 𝑪aK×K to the “true” segmentation produced by the shared backbone. Formally, if p^(yi=k|x)=[softmax(f𝜽(x))]i,k is the backbone's class probability at pixel i, then annotator a's predicted label distribution is (Confmat)p(yi=k|x,a)=k=1K[𝑪a]k,kp^(yi=k|x). Here [𝑪a]k,k represents the probability that annotator a labels a pixel as class k when the “true” class is k. The matrix 𝑪a is constrained to be row-stochastic (each column sums to one). A perfect annotator has 𝑪a=𝐈; 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 𝑪a to understand each annotator's systematic tendencies. For instance, if [𝑪a]bg,tumour is large, annotator a 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 {𝝓a}a=1A-can mitigate this by sharing statistical strength across annotators. Specifically, one can place a matrix-valued prior on the confusion matrices: 𝑪aDirichlet(𝜶) 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 p(y|x,a) 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 p(y|x)=ap(a)p(y|x,a), integrating over annotator identity but not modelling it explicitly.

The richest models combine both: a latent variable 𝒛ann captures annotator-specific style, a latent variable 𝒛img captures image-specific ambiguity, and the decoder produces a mask conditioned on both. Marginalising over 𝒛ann yields the distribution over masks for an “average” annotator; conditioning on a specific annotator yields that annotator's predicted mask; and the variance of 𝒛img given 𝒛ann 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 d-dimensional latent space and diagonal Gaussian prior p(𝒛|x)=Normal(𝝁p,diag(𝝈p2)) and posterior q(𝒛|x,y)=Normal(𝝁q,diag(𝝈q2)).

  1. (a)

    Derive the closed-form expression for DKL(qp) in terms of 𝝁p,𝝁q,𝝈p,𝝈q.

  2. (b)

    Show that if 𝝈p=𝝈q everywhere, then the KL divergence reduces to a scaled squared Euclidean distance between the means.

  3. (c)

    Suppose we set β=0 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 2×2. Three annotators provide the following masks for an image x: y(1)=(1110),y(2)=(1100),y(3)=(1111). A probabilistic model generates two samples: y^(1)=(1110),y^(2)=(1000). Using d(y,y)=1IoU(y,y) as the distance, compute D^GED2 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 L=2 latent levels. The coarse latent 𝒛2 determines whether a lesion is “large” (𝒛2>0) or “small” (𝒛20). The fine latent 𝒛1 (conditioned on 𝒛2) determines whether the boundary is “smooth” (𝒛1>0) or “irregular” (𝒛10).

  1. (a)

    How many distinct segmentation modes can this model represent? Describe each mode.

  2. (b)

    Suppose the prior is p(𝒛2|x)=Normal(0.5,1) and p(𝒛1|𝒛2,x)=Normal(𝒛2,0.5). Compute p(𝒛1>0,𝒛2>0|x)-the probability of the “large and smooth” mode.

  3. (c)

    Compare this hierarchical sampling with a single 2D latent 𝒛=(𝒛1,𝒛2) 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:

  1. Generate a synthetic dataset of 64×64 images, each containing an elliptical “lesion” with ambiguous boundaries. For each image, generate R=4 annotations by randomly perturbing the ellipse parameters (centre, axes, rotation) with controlled variance.

  2. Implement the four components: U-Net backbone (3 encoder and 3 decoder levels with skip connections), prior network (3-layer CNN outputting 𝝁,log𝝈 for d=6), posterior network (same architecture but taking concatenated image and mask), and 1×1 combining convolution.

  3. Train with the ELBO objective. Experiment with β{0.01,0.1,1.0} and report the effect on sample diversity.

  4. Evaluate using the GED with d(y,y)=1Dice(y,y). Compare against a deterministic U-Net trained on majority-vote masks and a U-Net with Monte Carlo dropout.

  5. 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 G that maps a noise vector 𝒛p𝒛(𝒛) (or, in conditional settings, an input image 𝒙) to a synthetic output;

  • A discriminator D that receives either a real sample from the data distribution or a synthetic sample from G and outputs a scalar indicating “real” or “fake.”

The two networks play a min-max game: (Minmax)minGmaxDV(D,G)=𝔼𝒙pdata[logD(𝒙)]+𝔼𝒛p𝒛[log(1D(G(𝒛)))]. At the Nash equilibrium, G produces samples indistinguishable from real data, and D outputs 12 for every input. In practice, training alternates between updating D for k steps (typically k=1) and updating G for one step.

Remark 11.

In segmentation, the generator G is the segmentation network itself. It receives an input image 𝒙 and produces a predicted mask 𝒚^=G(𝒙). There is no noise vector 𝒛; the stochasticity comes from the training data distribution and, in some formulations, from dropout or other stochastic layers within G. The discriminator D 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 D 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 S (the generator) and a critic C (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 S is an encoder–decoder network (typically a U-Net variant) that maps an input image 𝒙H×W to a predicted mask 𝒚^=S(𝒙)[0,1]H×W. The critic C receives the concatenation of the input image and a mask - either the ground truth 𝒚 or the predicted 𝒚^ - and produces feature maps at L hierarchical scales: (Critic)C(𝒙,𝒚)={𝒇C(l)(𝒙,𝒚)}l=1L, where 𝒇C(l)Hl×Wl×Cl denotes the feature map at scale l.

Multi-scale 1 loss.

The key innovation is the multi-scale feature matching loss, which compares the critic's internal representations for real and predicted masks: (LOSS)mae(S,C)=l=1L1Nl𝒇C(l)(𝒙,𝒚)𝒇C(l)(𝒙,S(𝒙))1, where Nl=Hl×Wl×Cl normalises by the total number of elements at scale l, and 1 denotes the 1 norm.

The training objectives are: (OBJ)Segmentor:minSmae(S,C),Critic:maxCmae(S,C). 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 (l=1,2), the critic's feature maps preserve spatial detail and capture local boundary accuracy. At coarse scales (l=L1,L), 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 99% 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 0.001), 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.

SegAN architecture. The segmentor S produces a predicted mask 𝒚^ from input image 𝒙. The critic C receives image–mask pairs (both real and predicted) and extracts multi-scale feature maps {𝒇C(l)}. The multi-scale 1 loss mae compares feature representations of real and predicted masks across all scales, providing the segmentor with spatially resolved, hierarchical feedback.

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 mae provides a gradient signal whose magnitude at boundary pixels scales as 𝒪(l=1L1/sl), where sl is the spatial stride at scale l, while a pixel-wise loss provides a gradient of 𝒪(1).

Proof.

At scale l, a boundary misalignment of δ pixels in the original resolution corresponds to a displacement of δ/sl in the feature map. The critic's convolutional filters at scale l have receptive fields proportional to sl, so a single boundary error affects approximately rl/sl feature map locations, where rl is the receptive field radius. The 1 norm aggregates these contributions: (Boundary)maey^i|i𝒚^l=1LrlslNll=1L1sl, since rl/Nl is approximately constant across scales for typical encoder architectures with doubling receptive fields and quadrupling spatial dimensions. For a four-scale critic with strides {1,2,4,8}, this yields a boundary gradient amplification of 1+1/2+1/4+1/8=1.875× 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 (L=3), SegAN achieved:

MethodWhole TumourCoreEnhancing
U-Net (Dice loss)0.8780.7440.681
U-Net + pixel-wise D0.8850.7560.698
SegAN (multi-scale)0.9010.7790.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 0.88 and smooth, anatomically plausible boundaries may be more clinically useful than a mask with Dice 0.90 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 25× higher than the segmentor's, with the critic updated k=1 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 0.5% 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 𝒚^[0,1]D×H×W be the predicted 3D segmentation mask. Define the projection operators Πax,Πcor,Πsag as summations along the axial, coronal, and sagittal axes, respectively: (PROJ)Πax(𝒚^)h,w=d=1Dy^d,h,w,Πcor(𝒚^)d,w=h=1Hy^d,h,w,Πsag(𝒚^)d,h=w=1Wy^d,h,w. Three independent 2D discriminators Dax,Dcor,Dsag 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)PAN=Dice(𝒚^,𝒚)+λv{ax, cor, sag}adv(Dv,Πv(𝒚^),Πv(𝒚)), where λ>0 controls the strength of the adversarial regularisation and adv 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 1.5M parameters. Three discriminators add 4.5M parameters - less than 5% of a typical 3D segmentation network. The projection operations themselves are simple summations with negligible cost.

PAN achieved a Dice score of 0.842 on the NIH pancreas dataset, compared to 0.818 for 3D U-Net alone and 0.831 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 (30 training volumes, 20 test volumes), adding projective discriminators to a 3D nn-UNet baseline improves the average Dice from 0.817 to 0.836, with the largest gains on small organs (gallbladder: +0.041, adrenal glands: +0.038) 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 F be a shared feature encoder and Cseg a segmentation head. The source domain has labelled pairs (𝒙s,𝒚s)ps, while the target domain has only images 𝒙tpt. A domain discriminator Ddom receives feature maps F(𝒙) and predicts whether they come from the source or target domain: (Align)dom=𝔼𝒙s[logDdom(F(𝒙s))]𝔼𝒙t[log(1Ddom(F(𝒙t)))]. The feature encoder is trained adversarially to confuse Ddom, implemented via a gradient reversal layer (Ganin et al., 2016): (Total)total=seg(𝒙s,𝒚s;F,Cseg)λdomdom(F,Ddom). The negative sign on dom with respect to F (via gradient reversal) encourages F 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 0 to 1 during training using a schedule λ(p)=2/(1+exp(γp))1, where p[0,1] is the training progress and γ=10. 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 0.89 to 0.72 without adaptation, but maintained 0.86 with adversarial feature alignment. This 0.14 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 {(𝒙i,𝒚i)}i=1N, train a generator G to produce realistic outputs G(𝒙i) conditioned on the input, supervised by both a reconstruction loss and an adversarial loss.

Definition 17 (Conditional GAN Objective).

Let G:𝒳𝒴 be a generator conditioned on input 𝒙𝒳, and let D:𝒳×𝒴[0,1] be a discriminator that receives both the conditioning input and the candidate output. The conditional GAN objective is (OBJ)cGAN(G,D)=𝔼𝒙,𝒚[logD(𝒙,𝒚)]+𝔼𝒙[log(1D(𝒙,G(𝒙)))], where (𝒙,𝒚) are drawn from the joint data distribution. The generator solves minGmaxDcGAN(G,D). 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 1 reconstruction loss that encourages the generator to produce outputs close to the ground truth: (LOSS)G=arg minGmaxDcGAN(G,D)+λ𝔼𝒙,𝒚[G(𝒙)𝒚1], where λ (typically 100) balances the two terms. The 1 loss prevents mode collapse by anchoring the generator's output near the target, while the adversarial loss encourages high-frequency detail that the 1 term alone would blur.

PatchGAN discriminator.

Instead of classifying the entire image as real or fake, the pix2pix discriminator operates on overlapping 70×70 patches, producing a grid of real/fake scores. This PatchGAN architecture:

  1. Can process images of arbitrary size (the grid adapts to the input dimensions);

  2. Has fewer parameters than a full-image discriminator;

  3. Focuses on local texture and structure, which is particularly effective for enforcing sharp tissue boundaries in medical images.

pix2pix training pipeline for medical image synthesis. A segmentation mask 𝒙 is fed to the generator G (with optional noise 𝒛), producing a synthetic medical image G(𝒙). The PatchGAN discriminator D receives the conditioning mask alongside either the real image 𝒚 or the synthetic image G(𝒙) and produces a grid of real/fake predictions. The total loss combines the adversarial loss with an 1 reconstruction term.
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:

  1. Start with a small annotated dataset {(𝒙i,𝒚i)} of real images and masks;

  2. Train a pix2pix model to translate masks to images: G:𝒚𝒙;

  3. Generate new masks by applying random deformations (elastic transforms, affine warps) to existing masks;

  4. Synthesise corresponding images: 𝒙~=G(𝒚~);

  5. Augment the training set with the synthetic pairs {(𝒙~j,𝒚~j)}.

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 0.04 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 1,0002,000 images, far fewer than the tens of thousands needed to train robust detectors. A pix2pix-based augmentation pipeline addresses this bottleneck:

  1. Mask generation. Elliptical and irregular polyp masks are generated procedurally, varying size (330 mm equivalent), shape eccentricity, and position within the colon lumen.

  2. Conditional synthesis. A pix2pix generator (U-Net with 8 downsampling blocks, trained on 1,200 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.

  3. Quality filtering. A pre-trained InceptionV3 classifier scores each synthetic image; samples scoring below 0.8 probability of “polyp present” are discarded (15% rejection rate).

  4. Augmented training. Combining 1,200 real images with 5,000 synthetic images and training a YOLOv5-based detector yields a sensitivity improvement of +7.3% (82.1%89.4%) at 95% specificity, compared to training on real data alone.

The synthetic images are visually convincing: in a blinded study, five gastroenterologists classified 48% of synthetic images as real (versus 52% 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 GAB:𝒳A𝒳B and GBA:𝒳B𝒳A be two generators translating between domains A and B. The cycle consistency loss enforces that translating an image to the other domain and back recovers the original: (Cycle)cyc(GAB,GBA)=𝔼𝒙apA[GBA(GAB(𝒙a))𝒙a1]+𝔼𝒙bpB[GAB(GBA(𝒙b))𝒙b1]. The first term ensures that the composition GBAGAB approximates the identity on domain A; the second ensures GABGBA approximates the identity on domain B.

Full objective.

The CycleGAN training objective combines two adversarial losses (one for each translation direction) with the cycle consistency loss: (FULL)CycleGAN=GAN(GAB,DB)+GAN(GBA,DA)+λcyccyc(GAB,GBA), where DA and DB are discriminators for domains A and B, and λcyc=10 is the default weight.

Application to cross-modality segmentation.

The standard workflow for CycleGAN-based cross-modality segmentation is:

  1. Train a CycleGAN to translate between modalities (e.g., MRI CT);

  2. Translate all labelled source-domain images to the target domain appearance;

  3. Train a segmentation network on the translated images with the original labels (which are preserved since CycleGAN maintains structural content);

  4. Apply the segmentation network directly to real target-domain images.

CycleGAN domain adaptation pipeline. Forward cycle (top): An MRI image 𝒙a is translated to a fake CT by GAB, which must fool discriminator DB. The fake CT is then translated back by GBA to a reconstructed MRI 𝒙^a, which should match the original via the cycle consistency loss. Reverse cycle (bottom): A CT image 𝒙b undergoes the symmetric translation GBAGAB with its own cycle consistency constraint. The two cycles jointly ensure that translations preserve anatomical structure while adapting appearance.

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: 500 scans from a Siemens 3T scanner (domain A) and 500 scans from a GE 3T scanner (domain B), 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, 256×256). Each generator uses 9 ResNet blocks; each discriminator is a 70×70 PatchGAN. Training proceeds for 200 epochs with λcyc=10.

Results. After harmonisation, applying a cortical parcellation model (trained on Siemens data only) to GE data achieves:

MethodMean DiceHausdorff (mm)
No harmonisation (direct transfer)0.7613.42
ComBat statistical harmonisation0.8122.87
CycleGAN (MRI MRI)0.8432.31
Oracle (retrained on GE data)0.8711.98

CycleGAN recovers 78% of the domain gap (0.8430.761=0.082 out of 0.8710.761=0.110), 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:

  1. 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.

  2. Geometric distortion. While cycle consistency penalises large deviations, subtle geometric distortions (shifts of 12 pixels) can persist, particularly near tissue boundaries with strong intensity gradients.

  3. 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 (σ<0.01), steganographic encoding is likely present.

  4. Identity loss requirement. For medical applications, an identity loss idt=𝔼𝒙b[GAB(𝒙b)𝒙b1] 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 k-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 𝒚Nx×Ny×Nz×Nt denote the fully-sampled 4D k-space data and 𝒚u=𝐌𝒚 the under-sampled version, where 𝐌 is a binary sampling mask with acceleration factor R=N/𝐌0. The reconstruction network G maps under-sampled zero-filled images to fully-sampled estimates: (GAN)𝒙^=G(1(𝒚u)), where 1 denotes the inverse Fourier transform.

Training objective.

The Re-Con-GAN objective combines data consistency, perceptual quality, and adversarial realism: (LOSS)Re-Con=𝒙^𝒙ref1data fidelity+μϕ(𝒙^)ϕ(𝒙ref)22perceptual+νadv(G,D)adversarial, where ϕ extracts VGG features and 𝒙ref is the fully-sampled reference. The adversarial term is critical: without it, the reconstruction tends toward over-smoothed outputs that achieve low 1 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)temp=t=1Nt1𝒙^t+1𝒙^t(𝒙ref,t+1𝒙ref,t)22. 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 R=8 (acquiring only 12.5% of k-space), Re-Con-GAN achieves a structural similarity index (SSIM) of 0.942 on cardiac cine MRI, compared to 0.913 for compressed sensing and 0.928 for a U-Net without the adversarial loss. The downstream left ventricle segmentation Dice improves from 0.84 (compressed sensing input) to 0.91 (Re-Con-GAN input), approaching the 0.93 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 1520 seconds of breath-hold, which many patients with heart failure cannot sustain. An 8× acceleration reduces the breath-hold to under 3 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 8× 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 1 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)G(𝒛,c)=Expertc(Fshared(𝒛)),c{1,,K}, where K is the number of cell types (typically K=5: neutrophils, lymphocytes, monocytes, eosinophils, and basophils) and Expertc 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 Hreal(c) and Hfake(c) be the normalised colour histograms (computed in CIE Lab space) of real and generated images for channel c{L,a,b}. The Wasserstein colour distance is (Wasserstein)Wcolour=c{L,a,b}W1(Hreal(c),Hfake(c))=c{L,a,b}01|Freal(c)(t)Ffake(c)(t)|dt, where Freal(c) and Ffake(c) are the cumulative distribution functions of the respective histograms, and W1 denotes the 1-Wasserstein (earth mover's) distance.

The Wasserstein colour distance is added to the MoE-cGAN objective: (Total)MoE=cGAN+λ11+λWWcolour. In practice, λW=5 provides the best balance between colour fidelity and structural quality.

MoE-cGAN generates blood cell images at 256×256 resolution. In a downstream classification experiment, augmenting a 2,000-image training set with 10,000 synthetic images improved the classification accuracy of a ResNet-50 classifier from 91.2% to 95.8%, with the largest gains on the rare basophil class (+12.3% 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:

  1. Distribution-level. The Fréchet Inception Distance (FID) between real and synthetic image sets should be below 30 (comparable to the FID between two real datasets of similar size). MoE-cGAN achieves FID =24.7 on neutrophils and 31.2 on basophils (the harder class due to fewer training examples).

  2. 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, p>0.05).

  3. Expert-level. A panel of three haematologists reviews 200 randomly mixed real and synthetic images. Classification accuracy at chance level (50±5%) confirms visual indistinguishability. In MoE-cGAN evaluations, experts achieved 53.1% 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 64×64×64 voxel patches centred on tumour regions. The architecture is notably compact:

  • Generator: 5 transposed convolutional layers, batch normalisation, ReLU activation. Total parameters: 1.7M.

  • Discriminator: 5 strided convolutional layers, batch normalisation, LeakyReLU. Total parameters: 2.3M.

The parameter efficiency (1.72.3M parameters, compared to the 31M 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 2×-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)DRa(𝒙r,𝒙f)=σ(C(𝒙r)𝔼𝒙f[C(𝒙f)]), where C() is the critic output before the sigmoid σ.

In brain MRI experiments, ESRGAN-upscaled images achieve a peak signal-to-noise ratio (PSNR) of 34.2 dB, compared to 31.8 dB for bicubic interpolation and 33.1 dB for standard SRGAN. When used as input to a tumour segmentation network, the ESRGAN-upscaled images yield Dice scores within 0.01 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 1.7M parameters and 200 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 1.31.8, 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 pdata be the true data distribution and pG the generator distribution. Mode collapse occurs when supp(pG)supp(pdata): the generator fails to cover the full support of the data distribution. In medical imaging, this manifests as:

  1. Missing rare pathologies. A GAN trained on brain MRIs with 90% glioblastoma and 10% oligodendroglioma may only generate glioblastoma-like tumours, producing training data that underrepresents the minority class.

  2. 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).

  3. 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 D fails to provide gradient signal in regions of 𝒳 where pG has near-zero density, the generator receives no incentive to place mass in those regions. Formally, the generator gradient is (GRAD)𝜽G𝔼𝒛[log(1D(G(𝒛)))]=𝔼𝒛[𝜽GD(G(𝒛))1D(G(𝒛))]. When D(G(𝒛))0 (the discriminator easily identifies the fake), the denominator 1D(G(𝒛))1 and the gradient magnitude is proportional to 𝜽GD(G(𝒛)). If the generator has collapsed to a region where D 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 PropertyGANsDiffusion Models
Core mechanismAdversarial min-max game between generator and discriminatorIterative denoising from Gaussian noise via learned score function
[4pt] Inference speedSingle forward pass (1050 ms per image)Hundreds of denoising steps (530 s per image); accelerated samplers reduce to 0.52 s
[4pt] Sample diversityLimited by mode collapse risk; may miss rare variantsHigh diversity; stochastic sampling covers the full distribution
[4pt] Training stabilityNotoriously unstable; requires careful hyperparameter tuning, architecture design, and learning rate schedulingStable; the denoising objective is a simple regression loss with well-understood convergence properties
[4pt] Output sharpnessProduces sharp, high-contrast images; excels at fine boundariesCan produce slightly blurry outputs at low sampling steps; high-step sampling recovers sharpness
[4pt] Ambiguity modellingDeterministic mapping from input to output (for conditional GANs); cannot represent segmentation uncertaintyNaturally models ambiguity through the stochastic denoising process; multiple samples capture prediction uncertainty
[4pt] ConditioningStraightforward via concatenation or projection; well-established architectures (pix2pix, SPADE)Flexible via classifier-free guidance, cross-attention, or ControlNet; rapidly evolving landscape
[4pt] Memory footprintSingle generator network (550M parameters typical)U-Net denoiser of comparable size, but requires storing noise schedule and running multiple forward passes
[4pt] Data augmentationFast generation enables large-scale augmentation; ideal for on-the-fly augmentation during trainingSlower generation may require pre-computing synthetic datasets; higher quality per sample
[4pt] Best medical use casesReal-time synthesis, on-the-fly augmentation, super-resolution, style transfer between scannersDiverse training data generation, uncertainty-aware segmentation, inpainting, anomaly detection
[4pt] Key limitationMode collapse can miss rare but clinically critical cases; training instability wastes computeSlow inference limits real-time applications; high computational cost for training and sampling
Comprehensive comparison: GANs vs. Diffusion Models for medical image generation. Each row addresses a property relevant to medical imaging deployment.
Practical decision framework.

When selecting between GANs and diffusion models for a medical imaging project, consider the following heuristics:

  1. If inference speed matters (e.g., real-time surgical guidance, on-the-fly augmentation), use GANs. Diffusion models are 1001,000× slower at inference.

  2. If sample diversity matters (e.g., generating training data for rare disease classification), use diffusion models. Their stochastic sampling naturally avoids mode collapse.

  3. If uncertainty quantification matters (e.g., flagging ambiguous segmentations for expert review), use diffusion models. Multiple samples provide calibrated uncertainty estimates.

  4. If training stability matters (e.g., limited computational budget, no ML engineering team to tune hyperparameters), use diffusion models. GAN training requires substantial expertise.

  5. 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 (256×256 slices), a DCGAN achieves FID =42.3 with generation time 18 ms/image, while a DDPM achieves FID =28.7 at 4.2 s/image (233× slower). On the CheXpert chest X-ray dataset, a conditional StyleGAN2 achieves FID =15.8 with notable mode collapse on rare pathologies (atelectasis underrepresented by 34% in synthetic set), while a latent diffusion model achieves FID =12.1 with balanced pathology representation (maximum underrepresentation <8%).

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 (40 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 (1024×1024). 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 64% probability (near chance) (Salehinejad et al., 2018);

  • Pathologists could not distinguish GAN-generated histopathology patches from real ones at magnifications below 20×;

  • Dermatologists rated GAN-generated skin lesion images as “clinically plausible” in 72% of cases.

This realism creates several risks:

  1. Data integrity. If synthetic images infiltrate a dataset without proper labelling, models may be trained or evaluated on fake data, corrupting performance estimates.

  2. Research fraud. GAN-generated images could be used to fabricate experimental results in medical research.

  3. Medicolegal liability. If a clinical decision is influenced by a model trained on undisclosed synthetic data that introduced systematic biases, liability becomes unclear.

  4. 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 (L=3) where the feature map dimensions at each scale are 128×128×32, 64×64×64, and 32×32×128.

  1. Compute the normalisation constant Nl for each scale.

  2. Suppose the critic's features for the ground truth mask are all-zeros 𝒇C(l)(𝒙,𝒚)=0 at every scale (a simplification for analysis). If the features for the predicted mask are 𝒇C(l)(𝒙,𝒚^)=cl1 (constant at each scale), express mae as a function of c1,c2,c3.

  3. A single boundary pixel error at the finest scale displaces 4 feature map entries at scale 1, 2 entries at scale 2, and 1 entry at scale 3, each by magnitude δ. Compare the gradient signal from the multi-scale loss to that of a loss using only scale 1. By what factor is the boundary gradient amplified?

  4. Discuss why the multi-scale loss is analogous to a Laplacian pyramid decomposition of the segmentation error.

Exercise 15 (CycleGAN Consistency Properties).

Let GAB and GBA be CycleGAN generators trained to translate between MRI (domain A) and CT (domain B). Assume both generators are bijective (invertible) mappings.

  1. Show that if the cycle consistency loss reaches zero, then GBA=GAB1.

  2. The cycle consistency loss uses 1 distance. Derive what would change if 2 distance were used instead. Specifically, consider the gradient with respect to the generator parameters and discuss the effect on boundary sharpness in translated images.

  3. In practice, GAB and GBA are neural networks and therefore not exactly invertible. Define the cycle reconstruction error as ϵ(𝒙a)=GBA(GAB(𝒙a))𝒙a1. For a dataset of N images, you observe ϵ=1Niϵ(𝒙a(i))=0.023 (normalised to [0,1] pixel range). Is this acceptable for downstream segmentation? Justify by estimating the Dice score impact.

  4. 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 500 annotated CT scans and need to augment the training set with synthetic data.

  1. The system must generate 10,000 synthetic CT slices with tumour masks. Compare the wall-clock time for GAN-based generation (single forward pass at 30 ms/image) versus diffusion-based generation (500 denoising steps at 10 ms/step). What is the total generation time for each approach?

  2. The department has observed that 8% 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.

  3. 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.

  4. 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 q that gradually destroys structure, and a reverse (denoising) process p𝜽 that learns to reconstruct it. In the segmentation setting, the data being diffused is a segmentation mask 𝒚0{0,1}H×W (or its continuous relaxation), rather than a natural image.

Forward process.

The forward process adds Gaussian noise over T steps according to a variance schedule β1,,βT(0,1): (Forward STEP)q(𝒚t|𝒚t1)=Normal(𝒚t;1βt𝒚t1,βt𝐈),t=1,,T. Define αt=1βt and αt=s=1tαs. A key property of the forward process is that we can sample 𝒚t at an arbitrary timestep directly from 𝒚0 without iterating through intermediate steps: (Forward Marginal)q(𝒚t|𝒚0)=Normal(𝒚t;αt𝒚0,(1αt)𝐈). This allows efficient training, as we can compute the noised version of any mask at any timestep in closed form: (Reparameterize)𝒚t=αt𝒚0+1αt𝝐,𝝐Normal(𝟎,𝐈).

Reverse process.

The reverse process is parameterized as a Gaussian with learned mean 𝝁𝜽 and fixed (or learned) variance σt2𝐈: (Reverse STEP)p𝜽(𝒚t1|𝒚t)=Normal(𝒚t1;𝝁𝜽(𝒚t,t),σt2𝐈). Ho et al. (Ho et al., 2020) showed that parameterizing 𝝁𝜽 in terms of a noise prediction network 𝝐𝜽(𝒚t,t) leads to a simple training objective: (LOSS Simple)simple=𝔼t,𝒚0,𝝐[𝝐𝝐𝜽(𝒚t,t)2], where tUniform{1,,T}, 𝒚0q(𝒚0), 𝝐Normal(𝟎,𝐈), and 𝒚t is computed via (Reparameterize).

Noise schedule design.

The original DDPM used a linear schedule βt=βmin+t1T1(βmaxβmin), but medical segmentation masks are typically simpler and more structured than natural images. A cosine schedule (Nichol and Dhariwal, 2021), (Cosine Schedule)αt=f(t)f(0),f(t)=cos(t/T+s1+sπ2)2, with a small offset s=0.008, 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 𝒚0{0,1}H×W are not naturally suited to Gaussian diffusion. Two common strategies address this: (i) treating the mask as a continuous-valued image in [0,1]H×W 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 p𝜽(𝒚0). For segmentation, we need a conditional reverse process p𝜽(𝒚0|𝒙), 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)p𝜽(𝒚0:T|𝒙)=p(𝒚T)t=1Tp𝜽(𝒚t1|𝒚t,𝒙), where p(𝒚T)=Normal(𝟎,𝐈) is the prior, 𝒙C×H×W is the input medical image, and each denoising step conditions on 𝒙 through a mechanism 𝒞(𝒙) integrated into the noise prediction network 𝝐𝜽(𝒚t,t,𝒞(𝒙)). The training objective becomes (COND LOSS)cond=𝔼t,𝒚0,𝒙,𝝐[𝝐𝝐𝜽(𝒚t,t,𝒞(𝒙))2]. At inference, a segmentation mask is obtained by sampling 𝒚TNormal(𝟎,𝐈) 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 𝒚t along the channel dimension before feeding into the U-Net: (COND Concat)𝝐𝜽(𝒚t,t,𝒙)=U-Net𝜽([𝒚t𝒙],t), 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)Attention(𝐐,𝐊,𝐕)=softmax(𝐐𝐊d)𝐕, 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)𝝐^𝜽(𝒚t,t,𝒙)=(1+w)𝝐𝜽(𝒚t,t,𝒙)w𝝐𝜽(𝒚t,t), where w>0 is the guidance scale. During training, the conditioning input is randomly dropped (replaced with a null embedding) with probability puncond, typically 1020%. At inference, larger values of w 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 t), the reverse process recovers the overall shape and location of anatomical structures. As t 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 512×512 pixels for 2D modalities (fundoscopy, dermatoscopy) and can extend to 512×512×512 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 T 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:

  1. Stage 1: Autoencoder compression. A variational autoencoder (or VQ-VAE) maps the mask 𝒚0 to a compact latent representation 𝒛0=(𝒚0)c×h×w, where h=H/r, w=W/r, and r is the spatial downsampling factor. The decoder 𝒟 reconstructs the mask: 𝒚^0=𝒟(𝒛0)𝒚0.

  2. Stage 2: Latent diffusion. The DDPM operates on the latent code 𝒛0 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 r be the spatial compression ratio of the autoencoder (i.e., the latent spatial dimensions are H/r×W/r). For an attention-based U-Net backbone, the per-step computational cost of latent diffusion is reduced by a factor of O(r2) compared to pixel-space diffusion for self-attention layers, and by O(r2) for convolutional layers. For 3D volumetric data, the savings increase to O(r3).

Proof.

Consider a self-attention layer operating on a feature map of spatial dimensions H×W. The attention matrix has size (HW)×(HW), so the computational cost scales as O((HW)2)=O(H2W2).

In pixel-space diffusion, HH and WW, giving cost O(H2W2). In latent diffusion, HH/r and WW/r, giving cost O(H2W2/r4). The ratio of pixel-space cost to latent cost is therefore O(r4) 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 23 downsampling stages), the effective spatial reduction from latent encoding is r2 in absolute FLOPs.

For convolutional layers with fixed kernel size k, the per-layer cost is O(C2k2HW), which scales as O(HW) in the spatial dimensions. Moving to latent space reduces the spatial dimensions by r2, yielding an O(r2) reduction.

The overall per-step cost is dominated by convolutional layers in typical U-Net architectures, giving an aggregate reduction of O(r2). For 3D volumes, the spatial dimensions become H×W×D, and the convolution cost scales as O(HWD), so the savings are O(r3).

Remark 19.

In practice, medical latent diffusion models use r=4 or r=8. For r=8, a 512×512 image becomes a 64×64 latent, reducing per-step convolution cost by approximately 64×. A 3D volume of 256×256×256 compressed to 32×32×32 yields a 512× 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 t.

Definition 21 (Dynamic Conditional Coding).

Let 𝒇𝒙(l) denote the feature map extracted from the input image 𝒙 at layer l of an image encoder, and let 𝒇𝒚t(l) denote the corresponding feature map of the noisy mask 𝒚t at the same layer of the denoising U-Net. Dynamic conditional coding (DCC) computes a step-dependent fused feature (DCC)𝒇fused(l)(t)=FF-Parse(γ(l)(t)𝒇𝒙(l)+δ(l)(t)𝒇𝒚t(l)), where γ(l)(t),δ(l)(t)Cl are learned affine modulation parameters conditioned on the timestep t via (DCC Modulation)[γ(l)(t),δ(l)(t)]=MLP(l)(sinusoidal_embed(t)), denotes channel-wise multiplication (broadcast over spatial dimensions), and FF-Parse() 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 t), the mask 𝒚t is mostly noise, so the network should rely heavily on image features (γ(t) large, δ(t) small). At later steps (small t), 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)FF-Parse(𝒇)=1(𝐖(𝒇)), where and 1 denote the 2D discrete Fourier transform and its inverse, and 𝐖C×H×W 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 T=50 denoising steps. At inference, the model receives a fundus image 𝒙 and generates a segmentation mask through iterative denoising:

  1. Initialize 𝒚50Normal(𝟎,𝐈).

  2. At each step t=50,49,,1: itemize

  3. Extract image features 𝒇𝒙(l) from the frozen encoder at each U-Net level l.

  4. Compute timestep-modulated fusion via (DCC).

  5. Apply the FF-Parser to suppress noise-band frequencies.

  6. Predict noise 𝝐^=𝝐𝜽(𝒚t,t,𝒙) and compute 𝒚t1. itemize

  7. Threshold 𝒚0 at 0.5 to obtain a binary mask.

The resulting segmentation achieves a Dice score of 88.7% on the REFUGE test set, surpassing the deterministic U-Net baseline (85.1%) and nnU-Net (87.2%). 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.

Architecture of MedSegDiff. The input medical image is processed by a separate encoder, and the noisy mask passes through the denoising U-Net. Dynamic Conditional Coding (DCC) fuses the two feature streams with timestep-dependent modulation parameters γ(t),δ(t). The Feature Frequency Parser (FF-Parser) suppresses high-frequency noise in the fused representation. The entire process iterates from t=T to t=1.

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 𝒚t and the conditioning image 𝒙 are each divided into non-overlapping patches of size P×P. The mask patches are linearly projected to d-dimensional tokens {𝒎i}i=1N (where N=HW/P2), and the image patches yield conditioning tokens {𝒄i}i=1N. The transformer alternates between self-attention on {𝒎i} and cross-attention between {𝒎i} (queries) and {𝒄i} (keys/values): (V2 SELF ATTN)𝒎i=𝒎i+Self-Attn(𝒎i,{𝒎j}j=1N),𝒎i=𝒎i+Cross-Attn(𝒎i,{𝒄j}j=1N).

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 𝒚^anchor from a lightweight CNN head: (V2 Anchor)𝒚^anchor=g𝝍(𝒙), where g𝝍 is a small encoder-decoder trained jointly with the diffusion model. The anchor prediction is concatenated with the noisy mask before tokenization: [𝒚t𝒚^anchor]. 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 1.53.0 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 O(N2d) for self-attention, where N=HW/P2 is the number of tokens. For a 256×256 image with patch size P=16, we have N=256 tokens, making the O(N2) 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 O(N2d) 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 𝒃=edge(𝒚0) 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)𝒇boundary(l)=σ(Conv(𝒃(l)))𝒇(l)+𝒇(l), where 𝒃(l) is the boundary map downsampled to match layer l, σ 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)DermoSeg=cond+λbl=1L𝒃(l)(𝝐^(l)𝝐(l))2, where 𝝐^(l) is the predicted noise at layer l and λb 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 91.4% and a boundary F1 score of 82.7%, representing a 3.1% 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 w pixels captures the transition zone. In practice, w=510 pixels works well for dermoscopy images at 256×256 resolution, roughly corresponding to the 0.51.0,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 𝝐𝜽img and a mask branch 𝝐𝜽mask. At each denoising step, the branches exchange information through a cross-consistency module: (Siamese IMG)𝝐^timg=𝝐𝜽img(𝒙t,𝒚t,t),𝝐^tmask=𝝐𝜽mask(𝒚t,𝒙t,t), 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)consist=𝔼t[spatial𝝐^timgspatial𝝐^tmask2], where spatial 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)morph=k(ϕk(𝒚^0)𝔼𝒚pdata[ϕk(𝒚)])2, where ϕk 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 25% across three dermatological and two cardiac segmentation tasks, with the largest gains in low-data regimes (n<100 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 p(𝒚|𝒙), 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 𝒚TNormal(𝟎,𝐈), 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 {𝒚(1),,𝒚(A)} (one per annotator), CIMD learns to model the full conditional distribution p(𝒚|𝒙), 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 q𝝓(𝒛|𝒙,𝒚) that maps an image-mask pair (𝒙,𝒚) to a distribution over a latent ambiguity code 𝒛d: (AMN)q𝝓(𝒛|𝒙,𝒚)=Normal(𝒛;𝝁𝝓(𝒙,𝒚),diag(𝝈𝝓2(𝒙,𝒚))), 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 𝒚(a), 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 p𝝃(𝒛|𝒙) that models the distribution of ambiguity codes given only the image (without seeing any mask): (ACN)p𝝃(𝒛|𝒙)=Normal(𝒛;𝝁~𝝃(𝒙),diag(𝝈~𝝃2(𝒙))). 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)𝝐𝜽(𝒚t,t,𝒙,𝒛), where 𝒛 is sampled from q𝝓(𝒛|𝒙,𝒚) during training and from p𝝃(𝒛|𝒙) during inference.

Theorem 3 (ELBO Decomposition for CIMD).

The CIMD training objective decomposes into three terms: (CIMD ELBO)CIMD=𝔼q𝝓(𝒛|𝒙,𝒚)[diff(𝜽;𝒚,𝒙,𝒛)](i) conditional diffusion loss+λ1DKL(q𝝓(𝒛|𝒙,𝒚)p𝝃(𝒛|𝒙))(ii) AMN–ACN alignment+λ2DKL(p𝝃(𝒛|𝒙)Normal(𝟎,𝐈))(iii) prior regularization, where diff(𝜽;𝒚,𝒙,𝒛)=𝔼t,𝝐[𝝐𝝐𝜽(𝒚t,t,𝒙,𝒛)2] is the standard conditional diffusion loss with the ambiguity code 𝒛, and λ1,λ2>0 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)logp(𝒚|𝒙)=logp𝜽(𝒚|𝒙,𝒛)p𝝃(𝒛|𝒙)d𝒛. Introducing the approximate posterior q𝝓(𝒛|𝒙,𝒚) and applying Jensen's inequality: (CIMD ELBO Derive1)logp(𝒚|𝒙)=logq𝝓(𝒛|𝒙,𝒚)q𝝓(𝒛|𝒙,𝒚)p𝜽(𝒚|𝒙,𝒛)p𝝃(𝒛|𝒙)d𝒛𝔼q𝝓[logp𝜽(𝒚|𝒙,𝒛)]DKL(q𝝓(𝒛|𝒙,𝒚)p𝝃(𝒛|𝒙)). The first term is the expected reconstruction quality. For the diffusion model, logp𝜽(𝒚|𝒙,𝒛) 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 p𝝃(𝒛|𝒙) through a regularizer that prevents the ACN from collapsing to a delta distribution. Specifically, we add a penalty DKL(p𝝃(𝒛|𝒙)Normal(𝟎,𝐈)) that encourages the prior to maintain diversity. Since both p𝝃(𝒛|𝒙) and Normal(𝟎,𝐈) are Gaussian, this KL divergence has a closed-form expression: (CIMD KL Closed)DKL(p𝝃(𝒛|𝒙)Normal(𝟎,𝐈))=12j=1d(μ~j2+σ~j2logσ~j21). Combining all three terms and negating gives the ELBO in (CIMD ELBO).

Training procedure.

For each training image 𝒙 with annotator masks {𝒚(1),,𝒚(A)}:

  1. Sample an annotator index aUniform{1,,A}.

  2. Encode ambiguity: 𝒛q𝝓(𝒛|𝒙,𝒚(a)).

  3. Sample timestep t and noise 𝝐.

  4. Compute CIMD from (CIMD ELBO).

  5. Update 𝜽,𝝓,𝝃 jointly.

Inference.

At test time, the AMN is discarded (it requires a ground-truth mask). To sample S diverse segmentations:

  1. Compute the prior: p𝝃(𝒛|𝒙).

  2. For s=1,,S: itemize

  3. Sample 𝒛(s)p𝝃(𝒛|𝒙).

  4. Sample 𝒚TNormal(𝟎,𝐈).

  5. Run the reverse process conditioned on (𝒙,𝒛(s)). itemize

  6. Report the sample mean 𝒚=1Ss𝒚(s) and per-pixel variance.

Architecture of CIMD (Collectively Intelligent Medical Diffusion). During training, the AMN encodes image-mask pairs into a latent ambiguity code 𝒛, while the ACN learns a prior over 𝒛 from the image alone. A KL divergence term aligns the two distributions. At inference, only the ACN is used to sample 𝒛, which conditions the reverse diffusion process to generate diverse segmentation masks 𝒚^(1),,𝒚^(S).

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 0.20, meaning the radiologists agree on only 20% of the pixels they collectively label as nodule.

CIMD is trained on LIDC-IDRI with A=4 annotators. At test time, the model generates S=16 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 0.218, improving over the probabilistic U-Net (0.285) and the stochastic segmentation network (0.267).

  • Sample Diversity: The per-pixel variance of the S=16 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:

  1. Inpainting with text guidance. Given a healthy image 𝒙healthy and a spatial mask 𝒎 indicating where the pathology should appear, a text-conditioned diffusion model performs inpainting: (Diffaug Inpaint)𝒙synth=𝒎DiffInpaint(𝒙healthy,𝒎,𝒄text)+(1𝒎)𝒙healthy, where 𝒄text is the CLIP text embedding of a description such as “flat sessile polyp with subtle mucosal discoloration.”

  2. 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)𝒎refined=σ(h𝝍(𝒙synth,𝒎)), where h𝝍 is a small CNN and σ is the sigmoid function.

  3. Quality filtering. A latent-space validation network v𝝎 scores each synthetic pair (𝒙synth,𝒎refined): (Diffaug Validate)s=v𝝎((𝒙synth),(𝒎refined)), where is an autoencoder. Pairs with s<τ 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 35% of synthetic images contain artifacts (discontinuities at inpainting boundaries, anatomically impossible lesion shapes) that would degrade downstream segmentation performance.

DiffAug pipeline for text-guided synthetic data augmentation. A healthy scan, text description of the desired pathology, and spatial mask are fed to a diffusion inpainting model. The synthetic output undergoes mask refinement and latent-space quality validation before being accepted into the augmented training set.

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 5% 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:

“Sessile serrated lesion, 8mm diameter, subtle mucosal discoloration on normal colonic mucosa, en-face view.”

The spatial mask 𝒎 is sampled from a learned shape prior fitted to real flat polyp contours.

Starting from a training set of 87 real flat polyp images, DiffAug generates 1,200 synthetic pairs, of which 780 pass the latent-space validation filter (acceptance rate: 65%). Training a segmentation model on the combined dataset yields:

  • Dice improvement: 71.2%82.5% on flat polyps (+11.3 points).

  • False-negative reduction: 28% fewer missed flat polyps at a fixed false-positive rate.

  • Negligible degradation on pedunculated (protruding) polyps: 91.4%91.1% 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:

  1. Forward-diffuse the input image 𝒙 to an intermediate timestep t: 𝒙t=αt𝒙+1αt𝝐.

  2. Pass 𝒙t through the denoising U-Net and extract feature maps {𝒇(l)}l𝒮 at a selected set of layers 𝒮.

  3. Upsample all feature maps to the input resolution and concatenate: 𝒇agg=[up(𝒇(l1))up(𝒇(lk))].

  4. Apply unsupervised clustering (e.g., k-means or spectral clustering) on 𝒇agg 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 k: (Genselfhis Decode)𝒚^(k)=g𝝍(k)(𝒇agg),𝝍(k+1)=arg min𝝍𝔼𝒙[CE(g𝝍(𝒇agg(𝒙)),𝒚^(k)(𝒙))], where CE is the cross-entropy loss and 𝒚^(0) 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)DARL=logexp(sim(𝒓(𝒙),𝒓(𝒙^0(t)))/τ)jexp(sim(𝒓(𝒙),𝒓(𝒙j))/τ), where 𝒙^0(t) is the denoised reconstruction from timestep t, 𝒓 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.

Comparison of supervised, self-supervised, and unsupervised diffusion-based segmentation paradigms. Supervised methods achieve the highest accuracy but require expensive annotations. Self-supervised methods iterate between pseudo-labels and decoder training. Unsupervised methods directly cluster diffusion features without any labels. The choice represents a fundamental tradeoff between accuracy and annotation cost.

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:

  1. 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.

  2. Latent mapper. A small network ψ:c×h×wc×h×w transforms the image latent 𝒛𝒙=(𝒙) into a conditioning signal suitable for the segmentation task: (GMS Mapper)𝒄=ψ(𝒛𝒙). The mapper has only 25 million parameters, compared to the hundreds of millions in the frozen backbone.

  3. 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)GMS=𝔼t,𝝐[𝝐𝝐𝜽(𝒛𝒚t,t,ψ(𝒛𝒙))2], where 𝒛𝒚t 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: 120M trainable parameters, Dice 82.7%.

  • MedSegDiff-V2: 180M trainable parameters, Dice 84.9%.

  • GMS: 3M trainable parameters, Dice 83.5%.

GMS achieves accuracy between the two MedSegDiff variants while training 4060× 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@ MethodKey InnovationBackboneAmbiguityLabels
MedSegDiffDynamic conditional codingU-NetImplicitFull
MedSegDiff-V2Transformer + anchor cond.ViTImplicitFull
DermoSegDiffBoundary attentionU-NetImplicitFull
Siamese-DiffNoise-consistent aug.Dual U-NetN/AFull
CIMDAMN + ACNU-NetExplicitFull
DiffAugText-guided inpaintingLDMN/APartial
GenSelfDiffSelf-supervised featuresFrozen U-NetImplicitNone
GMSFoundation model adapterFrozen LDMImplicitFull
Summary comparison of diffusion-based medical segmentation methods discussed in sec:medseg:diff-methods,sec:medseg:diff-ambiguity.

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 (50ms on a modern GPU), a diffusion model requires T=501,000 sequential denoising steps, each involving a full U-Net pass. Even with accelerated sampling (DDIM, DPM-Solver), inference times of 210 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 β1=104 and βT=0.02 over T=1,000 steps.

  1. (a)

    Compute αT and show that 𝒚T is approximately standard Gaussian for any 𝒚0[0,1]H×W.

  2. (b)

    Now consider a cosine schedule with the same T. At what timestep t does the cosine schedule reach αtα500 of the linear schedule? What does this imply about information preservation?

  3. (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 𝝁𝝓=[1.2,0.5,0.8] and 𝝈𝝓2=[0.3,0.5,0.2], while the ACN outputs 𝝁~𝝃=[0.9,0.3,0.6] and 𝝈~𝝃2=[0.5,0.7,0.4].

  1. (a)

    Compute the KL divergence DKL(q𝝓(𝒛|𝒙,𝒚)p𝝃(𝒛|𝒙)) in closed form, given that both distributions are diagonal Gaussians.

  2. (b)

    Compute DKL(p𝝃(𝒛|𝒙)Normal(𝟎,𝐈)).

  3. (c)

    If λ1=1 and λ2=0.1, 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 256×256×128. A latent diffusion model uses a 3D autoencoder with spatial compression ratio r=4.

  1. (a)

    What are the latent dimensions? How many latent “pixels” (voxels) does the diffusion model operate on, assuming c=8 channels?

  2. (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?

  3. (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:

  1. Train a CIMD model on a multi-annotator medical segmentation dataset (e.g., LIDC-IDRI or QUBIQ).

  2. 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.

  3. Train a fast deterministic segmentation network (e.g., nnU-Net) on the augmented dataset.

  4. 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.

  5. 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 f𝜽:𝒳×𝒫 that maps an image 𝒙𝒳 and a prompt 𝒑𝒫 to a binary mask 𝒎={0,1}H×W, where 𝒫 denotes the space of all valid prompts. The prompt space is a union of heterogeneous modalities: (Prompt Space)𝒫=𝒫point𝒫box𝒫mask𝒫text𝒫composite, where 𝒫point={(x,y,):{+,}} is the set of positive and negative point prompts, 𝒫box={(x1,y1,x2,y2)} denotes bounding box prompts, 𝒫mask=[0,1]H×W denotes soft mask prompts, 𝒫text denotes text descriptions, and 𝒫composite 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 1024×1024 pixels and divided into 64×64=4096 non-overlapping patches of size 16×16. Each patch is linearly embedded into a d=1280-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 64×64×256, obtained by projecting the final transformer output from dimension 1280 to 256 via a 1×1 convolution followed by a 3×3 convolution.

Let 𝒙3×1024×1024 denote the input image. The image encoder produces (Image ENC)𝑭=Encoderimg(𝒙)256×64×64, where 𝑭 is a dense feature map that captures the spatial structure of the image at a resolution of 16× 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 (x,y,) 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)𝒆point=PE(x,y)+𝒆,{+,}.

  • Box prompts. A bounding box (x1,y1,x2,y2) 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 𝒎prior[0,1]256×256 is downsampled and processed through two 2×2 convolutions with stride 2, producing a 64×64 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 {𝒆i}i=1Np, 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 {𝒆i} as input and produces output masks. The decoder consists of two transformer layers, each performing four types of attention:

  1. Self-attention among the output tokens (including prompt tokens and learned mask tokens).

  2. Cross-attention from output tokens to the image embedding 𝑭.

  3. Cross-attention from the image embedding to the output tokens (allowing the image features to be updated by the prompt).

  4. A token-to-image attention step using the updated image embedding.

The decoder produces three output masks {𝒎k}k=13, corresponding to whole, part, and subpart segmentations, along with three associated confidence scores (Intersection over Union predictions) {s^k}k=13. 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)𝒎k=σ(𝒕kUpsample(𝑭))[0,1]H×W, where 𝒕k is the k-th output token and 𝑭 is the updated image embedding from the decoder.

The SAM architecture consists of three components: a heavyweight image encoder (ViT-H with 632 million parameters) that processes the image once, a lightweight prompt encoder that handles diverse prompt types, and a lightweight mask decoder that produces three masks at different granularity levels along with IoU confidence scores. The asymmetric design enables real-time interactive prompting: the expensive image encoding runs once and is cached, while the prompt encoder and mask decoder run for each new prompt.
The SA-1B dataset.

The training dataset, SA-1B, was collected through a three-stage data engine:

  1. 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.

  2. Semi-automatic stage (180K images). The improved model automatically detected confident objects, and annotators focused on labeling the remaining unannotated regions, increasing mask diversity.

  3. Fully automatic stage (11M images). The nearly final model was applied to 11 million images with a 32×32 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 (x,y,+) 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 (x,y,) 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 (x1,y1,x2,y2) 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 𝒎prior[0,1]H×W 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 I(𝒑), we observe empirically that (Prompt Quality)Dice(I)Dmax(1eαI(𝒑)), where Dmax 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 >90% 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 16×16 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 𝒪={o1,,oK} be a set of K organs evaluated with zero-shot SAM using bounding box prompts. For each organ ok, let Vk denote its average volume (in cm3), Ck denote its boundary contrast (measured as the average absolute intensity gradient across the organ boundary in Hounsfield units), and Dk denote the achieved Dice score. The empirical relationship follows (Complexity)Dkβ0+β1logVk+β2logCk+εk, where β1,β2>0 indicate that Dice increases with both organ volume and boundary contrast. Fitting this model to a multi-organ abdominal CT dataset yields β10.06 (a 10× increase in volume improves Dice by 6 percentage points) and β20.09 (a 10× increase in boundary contrast improves Dice by 9 percentage points). The residual εk 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,cm3 to the liver at 1500,cm3) and contrasts. The fitted model explains approximately R2=0.78 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 (ε<0.12) and the gallbladder (ε>+0.08), 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 z-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 (,ϕenc,ϕatt) where:

  • ={(𝑭j,𝒎j,𝒑j)}j𝒥 is a memory bank storing image features 𝑭j, predicted masks 𝒎j, and prompt information 𝒑j from a subset 𝒥 of previously processed frames;

  • ϕenc:(𝑭t,𝒎t)𝑴t is a memory encoder that converts the current frame's features and predicted mask into a compact memory representation;

  • ϕatt:(𝑭t+1,)𝑭t+1 is a memory attention module that conditions the next frame's features on the stored memories, producing context-aware features 𝑭t+1.

The mechanism operates in a streaming fashion: at each time step t, 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 ||=Nmem, 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)𝑭t=𝑭t+CrossAttn(𝑭tquery,[𝑴j1;;𝑴jN]keys/values from memory), 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 𝑭t are then passed to the mask decoder, which operates identically to the original SAM decoder.

SAM 2 streaming memory architecture. A user provides a prompt on frame t, and the memory bank stores features and masks from previously processed frames. Memory attention conditions the current frame's segmentation on accumulated temporal context. The predicted mask for frame t is encoded into the memory bank and propagated to subsequent frames, enabling object tracking without additional prompts.

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 Nmem slots, typically set to Nmem=6 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:

  1. 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”).

  2. 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 K exemplar pairs {(𝒙kex,𝒎kex)}k=1K, SAM 3 computes a concept embedding by:

  1. Encoding each exemplar image through the image encoder to obtain features 𝑭kex.

  2. Masking the features with the exemplar mask to isolate the target concept: 𝑭k=𝑭kexUpsample(𝒎kex).

  3. Averaging the masked features across exemplars to form a concept prototype: (Prototype)𝒄concept=1Kk=1KGlobalPool(𝑭k).

  4. 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)MedSAM=λBCEBCE(𝒎^,𝒎)+λDiceDice(𝒎^,𝒎), where 𝒎^ is the predicted mask, 𝒎 is the ground truth, and λBCE=λDice=1 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 z-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:

  1. High-performing targets (Dice >80%): 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.

  2. 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.

  3. Low-performing targets (Dice <50%): 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 z-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.

Bidirectional propagation strategy for 3D volumetric segmentation using SAM 2. The user provides a bounding box prompt on the central slice (selected as the slice with the largest cross-section of the target organ). The segmentation is propagated in both directions along the z-axis using SAM 2's streaming memory mechanism. Slice colours indicate mask confidence, which decreases with distance from the prompted slice.

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:

  1. 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 𝒎prior. 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.

  2. Stage 2: Learnable refinement decoder. The prior mask 𝒎prior is fed to a second decoder that employs two novel attention mechanisms: itemize

  3. 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 𝑨mask=σ(Conv(𝒎prior)) be a learned attention map derived from the prior mask. The cross-attention is: (Maskcross)MaskCrossAttn(𝑸,𝑲,𝑽)=softmax(𝑸𝑲d𝑨mask)𝑽, where denotes element-wise multiplication and the mask attention map upweights boundary regions.

  4. 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)ClassBalAttn(𝑸,𝑲,𝑽)=softmax(𝑸𝑲d+𝑩class)𝑽, where 𝑩class is a learned bias matrix that increases attention to foreground tokens relative to the overwhelmingly more numerous background tokens. itemize

H-SAM two-stage architecture. Stage 1 uses the frozen SAM decoder to produce a coarse prior mask. Stage 2 feeds the prior mask and the image features to a learnable refinement decoder equipped with mask-guided cross-attention and class-balanced self-attention. Only Stage 2 parameters are trained, while the image encoder and Stage 1 decoder remain frozen.

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 f𝜽 with parameters 𝜽, parameter-efficient adaptation modifies the model to f𝜽,𝝓 by introducing a small set of additional parameters 𝝓 (with |𝝓||𝜽|) while keeping 𝜽 frozen. The adapted model satisfies (PEA)f𝜽,𝝓(𝒙)=f𝜽(𝒙)+Δf𝝓(𝒙), where Δf𝝓 represents the task-specific modification introduced by the adapter parameters. The adaptation is parameter-efficient if |𝝓|/|𝜽|<ϵ for some small threshold ϵ (typically ϵ<0.05, 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)Adapter(𝒉)=𝒉+𝑾upReLU(𝑾down𝒉), where 𝒉d is the hidden representation, 𝑾downr×d projects to a low-rank bottleneck of dimension rd, and 𝑾upd×r projects back. The residual connection ensures that the adapter starts as an identity function (when 𝑾up 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:

  1. 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).

  2. 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 r=64 and d=1280 (SAM ViT-H dimensions), each adapter adds 2×64×1280=163,840 parameters. With two adapters per transformer block and 32 blocks, the total adapter parameter count is 32×2×163,84010.5M, 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 N slices and a prompt on slice k, the maximum propagation distance is max(k,Nk) for unidirectional and max(k,Nk)/2 for bidirectional (when the prompt is on the central slice). The error accumulation follows approximately (Propagation Error)ε(d)ε0dγ, where d is the propagation distance (in slices), ε0 is the per-slice error rate, and γ(0.5,1.0) is an empirical exponent. Bidirectional propagation from the optimal central slice minimises max(dleft,dright)=N/2, compared to N1 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:

  1. The organ is most clearly visible and distinguishable from surrounding structures.

  2. A bounding box prompt on the largest cross-section provides the strongest spatial constraint.

  3. 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 z-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 (x,y,) 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 16×16 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 Aorgan be the organ area in the prompted slice and Abox be the bounding box area. The box fill ratio ρ=Aorgan/Abox predicts whether negative prompts help or hurt: (Negprompt)ΔDiceneg{>0if ρ<0.4(large background area; negatives help),0if 0.4ρ0.6(marginal effect),<0if ρ>0.6(tight box; negatives hurt). 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 “z-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 𝒙1×D×H×W (where D is the depth/number of slices) by dividing it into 3D patches of size pd×ph×pw and embedding each patch as a token. The encoder produces a 3D feature volume 𝑭C×D×H×W.

  • 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 z-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 512×512×300, which, when divided into 16×16×16 patches, produces approximately 19,200 tokens-far too many for standard self-attention. The zoom-in mechanism proceeds in two phases:

  1. Coarse localisation. The volume is downsampled by a factor of 4 in each spatial dimension, producing a manageable 128×128×75 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.

  2. 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 8× 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 N=200 slices containing the liver and pancreas. You have access to SAM 2 with bidirectional propagation and a single bounding box prompt per organ.

  1. (a)

    The liver's largest cross-section is at slice kL=105 and the pancreas's largest cross-section is at slice kP=130. Using the error model ε(d)=ε0d0.7 with ε0L=0.001 (liver) and ε0P=0.005 (pancreas), compute the maximum propagation error for each organ under bidirectional propagation. Compare to the unidirectional case where propagation starts from slice 1.

  2. (b)

    The liver has a box fill ratio ρL=0.35 and the pancreas has ρP=0.72. Based on (Negprompt), should you use negative prompts for each organ? Explain the reasoning in terms of the patch size–organ boundary interaction.

  3. (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 z-extent.

Exercise 21.

H-SAM uses a two-stage architecture where Stage 2 has a mask-guided cross-attention mechanism ((Maskcross)).

  1. (a)

    Suppose the prior mask 𝒎prior from Stage 1 has a Dice score of 0.72 with respect to the ground truth for a pancreas segmentation. The mask attention map 𝑨mask 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?

  2. (b)

    Med-SA uses adapter modules with bottleneck dimension r=64 and hidden dimension d=1280. 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)?

  3. (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 β0=0.32, β1=0.06, and β2=0.09:

  1. (a)

    Predict the zero-shot SAM Dice score for the following organs: (i) liver (V=1500,cm3, C=120,HU), (ii) kidney (V=150,cm3, C=80,HU), (iii) pancreas (V=70,cm3, C=25,HU), and (iv) aorta (V=20,cm3, C=200,HU).

  2. (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?

  3. (c)

    The model predicts the same Dice for two organs with (V1,C1) and (V2,C2) when β1logV1+β2logC1=β1logV2+β2logC2. Derive the iso-Dice curve in the (V,C) plane and plot it for Dice =0.70. Interpret this curve: for a given target Dice, how much additional contrast compensates for a halving of volume?

  4. (d)

    The residual term εk 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 {Si}i=1N be the set of N ground-truth cell masks and {S^j}j=1M the set of M predicted masks. For each ground-truth mask Si, let S^j(i) be the predicted mask with maximal Jaccard overlap: (SEG Metric)j(i)=arg maxjJ(Si,S^j),J(A,B)=|AB||AB|. The SEG metric is the average Jaccard index over all ground-truth instances: (SEG Value)SEG=1Ni=1NJ(Si,S^j(i)). A score of SEG=1 indicates perfect overlap for every cell; SEG=0 indicates no overlap. Note that j(i) 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 G=(VG,EG) 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 G^=(VG^,EG^) be the predicted tracking graph. The tracking accuracy is defined as (TRA Metric)TRA=1minπkwkck(π)kwk|VG|, where π ranges over all sequences of graph-edit operations (insertions, deletions, splits, merges) that transform G^ into G, each operation type k has weight wk, and ck(π) counts the number of operations of type k. This is the normalised acyclic oriented graph matching (AOGM) distance. A score of TRA=1 indicates a perfect tracking graph.

Remark 24.

The combined Cell Tracking Challenge score is the geometric mean OPCSB=SEGTRA, 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 Ω2 be the image domain and let {Ck}k=1K be the set of K cell regions with centroids {𝝁k}k=1K. Cellpose defines two flow fields, horizontal and vertical: (Cellpose Flows)𝒇(h)(𝒙)=x1ϕk(𝒙),𝒇(v)(𝒙)=x2ϕk(𝒙),for 𝒙Ck, where ϕk:Ck is a smooth potential whose gradient points from every pixel in cell k toward its centroid 𝝁k. In practice, ϕk is constructed by solving a diffusion equation on the cell mask: (Cellpose Diffusion)2ϕk(𝒙)=0in Ck,ϕk(𝝁k)=1,ϕk(𝒙)=0on Ck. The resulting gradient ϕk is a smooth vector field that converges to 𝝁k from every point inside the cell.

At inference, the network predicts three outputs: the horizontal flow 𝒇^(h), the vertical flow 𝒇^(v), and a cell-probability map p^:Ω[0,1]. Instance masks are recovered by gradient tracking: starting from every pixel with p^(𝒙)>τ, follow the predicted flow for T steps using Euler integration: (Cellpose Euler)𝒙(t+1)=𝒙(t)+δ(𝒇^(h)(𝒙(t)),𝒇^(v)(𝒙(t))),t=0,1,,T1. 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 Cellpose pipeline. A neural network predicts horizontal and vertical gradient flow fields from the input cell image. Each flow field points every pixel toward the centroid of its parent cell. Gradient tracking (Euler integration of the predicted flows) groups pixels by their convergence point, yielding instance-level segmentation without requiring a fixed number of output channels.

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)Cellpose=λflow𝒙Ω𝒇^(𝒙)𝒇(𝒙)22+λprob𝒙ΩBCE(p^(𝒙),p(𝒙)), where 𝒇 and p 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.

StarDist predicts n radial distances from each candidate centre point to the cell boundary. The resulting star-convex polygon (dashed orange) approximates the true cell contour (solid green). Non-maximum suppression removes overlapping proposals, yielding one polygon per cell.

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:

  1. An object probability p^(𝒙)[0,1] indicating whether 𝒙 is inside a cell.

  2. A vector of n radial distances 𝒓^(𝒙)=(r^1,,r^n)0n, where r^k is the predicted distance from 𝒙 to the cell boundary along direction θk=2πk/n.

The polygon vertices are then (Stardist Vertices)𝒗k=𝒙+r^k(cosθk,sinθk),k=1,,n. Pixels with p^(𝒙)>τ 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=λcls𝒙BCE(p^(𝒙),p(𝒙))+λreg𝒙:p(𝒙)=1k=1n|r^k(𝒙)rk(𝒙)|.

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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 1-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:

  1. The user annotates 5 cells in the first 3D volume using point clicks in the napari plugin.

  2. μSAM fine-tunes the decoder on these annotations in approximately 2 minutes on a single GPU.

  3. The automatic mask generator segments all cells in each volume (approximately 30 seconds per volume).

  4. The tracking-by-propagation module links cells across time by using the mask from frame t as a prompt for frame t+1.

The resulting 4D tracks achieve SEG=0.87 and TRA=0.92, 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 0.5 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:

  1. CellFinder: detection. A DETR-style transformer detector processes the image and outputs a set of bounding boxes {Bk}k=1K, 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.

  2. SAM: segmentation. Each bounding box Bk 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 N cells in frame t and M cells in frame t+1, there are O(NM) 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 {It}t=1T be a time-lapse image sequence and let 𝒟t={dt(i)}i=1Nt be the set of cell detections (positions or segmentation masks) in frame t. A cell tracking is a mapping π that assigns to each detection dt(i) at most one detection dt+1(j) in the next frame, subject to the constraints:

  1. Uniqueness: Each detection in frame t+1 is assigned to at most one detection in frame t (no merging of distinct cells).

  2. Division: A detection dt(i) may be assigned to exactly two detections in frame t+1 if cell i undergoes mitosis.

  3. Appearance/disappearance: Unassigned detections in frame t correspond to cells leaving the field of view (or dying); unassigned detections in frame t+1 correspond to cells entering the field of view (or being born from a division event elsewhere).

The full tracking result is the collection Π={πt}t=1T1, 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 TRA>0.99 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 TRA0.85, 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 OPCSB 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 t as a prior for frame t+1. Concretely, propagate the mask from t to t+1 (using optical flow, a learned warping, or a mask-conditioned segmentation model), refine it using image evidence at t+1, and iterate. This paradigm is natural for SAM-style models, which accept a mask prompt: the mask from t serves as the prompt for t+1. 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 t: cell A is assigned cell B's identity, and vice versa. Every subsequent frame inherits this error. If cell A later divides, its daughters are now incorrectly attributed to cell B'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 𝒟t and 𝒟t+1 in consecutive frames, the association problem is to find the optimal mapping πt:𝒟t𝒟t+1{} that links each cell to its successor (or to if the cell disappears).

Definition 29 (Lineage Tree).

A lineage tree 𝒯=(V,E) is a rooted directed tree where:

  • Each vertex vV represents a cell detection at a specific time point, labelled (v,tv).

  • Each edge (u,v)E with tv=tu+1 represents a temporal link (the cell persisted from frame tu to tu+1).

  • A vertex u with two children v1,v2 (both at time tu+1) represents a mitosis event: cell u divided into daughter cells v1 and v2.

  • 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 t is a triple (dt(m),dt+1(a),dt+1(b)) where the mother cell dt(m) divides into two daughter cells dt+1(a) and dt+1(b). In the lineage tree, this corresponds to a vertex with out-degree 2. Formally, for a mitosis event to be valid:

  1. The mother cell must exist at time t: dt(m)𝒟t.

  2. Both daughters must exist at time t+1: dt+1(a),dt+1(b)𝒟t+1.

  3. The daughters must be spatially close to the mother: 𝒙t+1(a)𝒙t(m)rmax and 𝒙t+1(b)𝒙t(m)rmax.

  4. The mother cell must not appear at time t+1 (it has been replaced by its daughters).

Proposition 7 (Optimal Assignment as Bipartite Matching).

Consider the assignment problem between detections 𝒟t={dt(1),,dt(N)} and 𝒟t+1={dt+1(1),,dt+1(M)}. Define a cost matrix 𝐂(N+M)×(N+M) where: (COST Matrix)Cij={c(dt(i),dt+1(j))if iN,jM,cdisappearif iN,j>M,cappearif i>N,jM,0if i>N,j>M, with c(dt(i),dt+1(j)) the cost of linking detection i at time t to detection j at time t+1 (e.g., Euclidean distance between centroids, or negative IoU between masks), and cdisappear,cappear the costs of track termination and initiation, respectively. The augmented rows i>N and columns j>M represent dummy detections for appearance and disappearance.

Then the optimal one-to-one assignment πt=arg minπ𝒫iCi,π(i) over all permutations 𝒫 of {1,,N+M} can be computed in O((N+M)3) 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 O(n3) 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 c(,) can be much richer than Euclidean distance. Modern methods use learned embeddings: each detection is mapped to a vector 𝒆t(i)=fθ(dt(i))d, and the cost is the embedding distance c(dt(i),dt+1(j))=𝒆t(i)𝒆t+1(j)2. The encoder fθ 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 t reappears at frame t+2 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 G=(V,E) 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 G, 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 dt(i) 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)𝒆t(i)=MHA(𝒒t(i),{𝒌t(j)}j𝒩(i),{𝒗t(j)}j𝒩(i))+𝒑t(i), where 𝒒t(i) is the query from cell i's appearance, 𝒌t(j),𝒗t(j) are keys and values from neighbouring cells 𝒩(i), and 𝒑t(i) 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 {𝒆t(i)} at time t, a conditional diffusion model predicts the displacement vectors {Δ𝒙t(i)} that map each cell to its position at time t+1. The diffusion model is conditioned on the CytoEmbeddings and trained to denoise displacement vectors: (Cytotracker Diffusion)motion=𝔼s,𝝐[𝝐𝝐θ(Δ𝒙ts,s,{𝒆t(i)})22], where Δ𝒙ts is the noised displacement at diffusion step s 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 𝒙^t+1(i)=𝒙t(i)+Δ^𝒙t(i) are compared with the actual detections 𝒟t+1 using a transformer-based matcher. The matcher takes as input the predicted embeddings and actual embeddings at t+1, applies cross-attention between the two sets, and outputs a soft assignment matrix: (Cytotracker Assignment)𝐀=softmax(𝐄^t𝐄t+1/d)N×M, where 𝐄^tN×d collects the predicted embeddings and 𝐄t+1M×d 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.

CytoTracker architecture. Cell detections at times t and t+1 are encoded by CytoEmbedding modules that fuse appearance, position, and neighbourhood context via cross-attention. A conditional diffusion model predicts motion vectors from the time-t embeddings. The transformer associator matches predicted positions to actual detections at t+1 using cross-attention and the Sinkhorn algorithm, producing the final tracks.

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 TRA=0.985 and DET=0.991, 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:

  1. Initialisation. Run the SAM2 automatic mask generator on the first frame to detect all cells without any user prompts.

  2. 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 K frames, providing temporal context.

  3. New cell detection. Periodically (every Δ frames), run the automatic mask generator to detect cells that entered the field of view after initialisation.

  4. 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 t, SAM2's memory attention module attends to the stored features from frames t1,t2,,tK: (SAM2 Memory)𝒉t=MemoryAttn(𝒒t,{𝒌τ,𝒗τ}τ=tKt1), where 𝒒t 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 (TRA0.95 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 in time-lapse microscopy. The mother cell (M) rounds up before division (t1), elongates during cytokinesis (t), splits into two daughters D1 and D2 (t+1), which then separate (t+2). The lineage tree (right) records the branching event. Detecting the division frame t is the key computational challenge.

Mitosis detection approaches fall into three categories:

  1. 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.

  2. 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.

  3. Integrated tracking. Build mitosis detection directly into the tracking framework. At each frame, the tracker considers both continuation hypotheses (cell i at t becomes cell j at t+1) and division hypotheses (cell i at t becomes cells j and k at t+1). 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 G=(V,ElinkEdiv) where Elink contains temporal-link edges (one-to-one) and Ediv contains division edges (one-to-two). The optimal lineage is the minimum-cost subgraph of G 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 {St(i)} 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)I^t=Gθ(St,𝒛t),𝒛t𝒩(0,𝐈), where Gθ is a mask-conditioned diffusion model trained on paired real images and their annotations. The stochastic noise 𝒛t 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 SEG=0.92 and TRA=0.96, compared to SEG=0.85 and TRA=0.89 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 SEG=0.82 on phase-contrast data, compared to SEG=0.65 for the generalist Cellpose model and SEG=0.48 for classical thresholding. When combined with CytoTracker for temporal association, the pipeline achieves TRA=0.88, 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 r>0.9 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.

The cell tracking pipeline. Cells are detected (segmented) independently in each frame, then associated across frames using bipartite matching or learned methods. The resulting tracks are assembled into lineage trees by detecting division events. Errors at any stage propagate downstream.

Exercise 23 (Cellpose Flow Field Computation).

Consider a circular cell of radius R centred at the origin, so C={𝒙2:𝒙2R}.

  1. Write down the boundary conditions for the Cellpose potential ϕ: ϕ(0)=1 and ϕ(𝒙)=0 for 𝒙2=R. Using the radial symmetry, show that the Laplace equation 2ϕ=0 in 2D polar coordinates yields ϕ(r)=ln(R/r)lnR for 0<rR (with the convention ϕ(0)=1).

  2. Compute the gradient flow field ϕ=(ϕx1,ϕx2) and verify that it points radially inward toward the centroid at every interior point.

  3. Now consider two circular cells of radius R with centres at (Rε/2,0) and (R+ε/2,0), separated by a gap of width ε. Explain qualitatively why the gradient flows remain well-separated as long as ε>0 but fail catastrophically when ε=0 (cells touching). How does Cellpose handle this in practice?

  4. 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 O(R/δ).

Exercise 24 (Bipartite Matching for Cell Tracking).

A time-lapse sequence contains 3 cells at time t with centroid positions 𝒙t(1)=(10,20), 𝒙t(2)=(30,15), 𝒙t(3)=(25,40), and 4 cells at time t+1 with positions 𝒙t+1(1)=(12,22), 𝒙t+1(2)=(28,14), 𝒙t+1(3)=(26,38), 𝒙t+1(4)=(50,50).

  1. Compute the Euclidean distance matrix Dij=𝒙t(i)𝒙t+1(j)2 for all i{1,2,3}, j{1,2,3,4}.

  2. Augment the cost matrix as in (COST Matrix) with cdisappear=cappear=30. Write out the full (4+3)×(4+3) matrix (padding with appropriate dummy rows/columns).

  3. Solve the assignment problem by inspection or by applying the Hungarian algorithm. Which cell at t+1 is identified as a newly appearing cell?

  4. Suppose cell 3 at time t actually divided, producing cells 3 and 4 at t+1 (with 𝒙t+1(4)=(24,42) instead of (50,50)). 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).

  1. Draw the ground-truth tracking graph G with 7 vertices (5 for cell A, 2 for cell B) and the appropriate edges.

  2. Suppose the predicted tracking graph G^ is identical to G except that cell B is incorrectly linked to cell A at frame 3 (an identity swap). Compute the AOGM operations needed to transform G^ into G. How many operations are required?

  3. 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?

  4. 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.

  1. 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.

  2. Formalise your metric mathematically, defining the inputs, the computation, and the range of values.

  3. 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).

  4. Discuss the computational complexity of your metric. Can it be computed efficiently for large-scale tracking results (thousands of cells over hundreds of frames)?

  5. 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 256×256 matrix of pixel values and must produce a 256×256 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 fimg (typically a Vision Transformer or ResNet) and a text encoder ftxt (typically a Transformer)-map their respective inputs into a shared embedding space d. 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 =(fimg,ftxt,g) consisting of:

  1. An image encoder fimg:𝒳d that maps a medical image 𝒙𝒳 (which may be 2D, 3D, or a video sequence) to a d-dimensional visual embedding;

  2. A text encoder ftxt:𝒯d that maps a natural language description t𝒯 (a radiology report, clinical prompt, or anatomical description) to the same d-dimensional space;

  3. A fusion mechanism g:d×d𝒴 that combines visual and textual embeddings to produce a task-specific output y𝒴 (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 d, 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 N matched image–text pairs {(𝒙i,ti)}i=1N, let 𝒗i=fimg(𝒙i)/fimg(𝒙i) and 𝒖i=ftxt(ti)/ftxt(ti) denote the 2-normalised image and text embeddings, respectively. The InfoNCE loss is the symmetric cross-entropy (Infonce)InfoNCE=12Ni=1N[logexp(𝒗i𝒖i/τ)j=1Nexp(𝒗i𝒖j/τ)+logexp(𝒖i𝒗i/τ)j=1Nexp(𝒖i𝒗j/τ)], where τ>0 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 N items in the batch, treating the N1 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 I(𝑽;𝑼) between the image and text embedding random variables. Specifically, if the optimal critic achieves the maximum of the bound, then I(𝑽;𝑼)logNInfoNCE, where InfoNCE is the minimum achievable loss. This means that larger batch sizes N 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 {c1,c2,,cK}, one constructs text prompts such as “a photo of a ck” and computes the text embeddings 𝒖k=ftxt(“a photo of a ck). For a new image 𝒙, the predicted class is (CLIP Zeroshot)k^=arg maxk{1,,K}exp(𝒗𝒖k/τ)j=1Kexp(𝒗𝒖j/τ), where 𝒗=fimg(𝒙)/fimg(𝒙). 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:

  1. 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.

  2. 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.

  3. 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:

  • t1 = “chest X-ray showing pneumothorax”

  • t2 = “chest X-ray showing pleural effusion”

  • t3 = “chest X-ray showing cardiomegaly”

  • t4 = “chest X-ray showing pulmonary nodule”

  • t5 = “normal chest X-ray with no acute findings”

For each prompt tk, we compute the cosine similarity sk=𝒗𝒖k between the image embedding 𝒗=fimg(𝒙) and the text embedding 𝒖k=ftxt(tk). On the CheXpert benchmark, BiomedCLIP achieves zero-shot AUC scores of 0.820.91 across 14 pathology categories, compared to 0.550.70 for general CLIP. This 1520 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 72.8% for image-to-text retrieval and 69.4% for text-to-image retrieval, compared to 41.2% and 38.7% for general CLIP.

  • Visual question answering: On the VQA-RAD benchmark (radiology visual question answering), BiomedCLIP's embeddings used as input features achieve 68.3% accuracy, compared to 52.1% 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 512 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:

  1. A vision encoder (typically a CLIP ViT-L/14) that produces a sequence of visual tokens 𝒗1,𝒗2,,𝒗P from the input image, where P is the number of image patches;

  2. A projection layer 𝐖proj that maps visual tokens into the input space of the language model: 𝒗^p=𝐖proj𝒗p;

  3. 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 𝐖proj 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 t, the similarity score is (Type1)s(𝒙,t)=fimg(𝒙)ftxt(t)fimg(𝒙)ftxt(t).

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)CrossAttn(𝐐,𝐊,𝐕)=softmax(𝐐txt𝐊imgd)𝐕img, where 𝐐txtLt×d are query vectors derived from text tokens and 𝐊img,𝐕imgLv×d 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)p(yt|y<t,𝒙)=LM𝜽(y<t,𝐖projfimg(𝒙)). 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.

Three canonical VLM architecture types for medical imaging. Type 1 uses separate encoders with cosine similarity for efficient retrieval and zero-shot classification. Type 2 introduces cross-attention between modalities for fine-grained interaction. Type 3 feeds visual tokens into a generative language model for open-ended reasoning. Each type trades off efficiency against expressive power: Type 1 is fastest at inference but captures only global similarity; Type 3 can generate arbitrary clinical text but requires autoregressive decoding.

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 t processed through a multimodal encoder to produce a fused representation 𝒉=g(𝒙,t), the image–text matching score is (ITM)sITM(𝒙,t)=σ(𝒘ITM𝒉+bITM), where σ is the sigmoid function and 𝒘ITMd, bITM are learnable parameters. The ITM objective is the binary cross-entropy ITM=𝔼[ylogsITM(𝒙,t)+(1y)log(1sITM(𝒙,t))], where y=1 for matched pairs and y=0 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)MLM=𝔼[mlogp𝜽(tm|t\,𝒙)], where is the set of masked positions and t\ 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:

  1. Text encoder. A frozen BiomedCLIP text encoder processes the clinical instruction t to produce a text embedding 𝒖d and a sequence of token-level features 𝐔=[𝒖1,,𝒖L]L×d.

  2. Image encoder. SAM 2's Hiera image encoder extracts multi-scale visual features 𝐅(s)Hs×Ws×Cs at scales s{1,2,3,4}.

  3. 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)𝐅~(s)=𝐅(s)+αCrossAttn(𝐅(s),𝐔,𝐔), 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.

  4. Streaming memory. SAM 2's memory bank stores per-frame embeddings for temporal propagation. In TGSAM-2, the text-conditioned features 𝐅~(s) 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.

  5. 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 TGSAM-2 pipeline. A clinical text instruction is encoded by a frozen BiomedCLIP text encoder and injected into SAM 2's visual features via a text-conditioned perception module (TCPM) using cross-attention. The conditioned features update a streaming memory bank that propagates the text guidance across video frames. The mask decoder produces segmentation masks guided by both the text instruction and temporal context.

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 0.847 compared to 0.812 for point-prompted SAM 2 and 0.791 for fully automatic (no prompt) baselines. More importantly, the text-guided approach reduces false positives by 34% 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:

  1. A query encoder q:𝒳×𝒯d that maps an image–text query pair (the medical image and an optional clinical question) to a query embedding;

  2. A knowledge base 𝒦={(ki,di)}i=1M consisting of M indexed entries, where kid is the embedding and di is the content (a clinical guideline, case report, textbook passage, or annotated prior case);

  3. A retriever (q,𝒦)={di1,,dir} that returns the top-r documents whose embeddings are closest to the query embedding;

  4. A generator 𝒢 (typically a VLM) that produces an output conditioned on both the original input and the retrieved documents: (RAG)y=𝒢(𝒙,t,(q(𝒙,t),𝒦)).

The output y 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 𝒢RAG denote the same model augmented with retrieval. Define the hallucination rate as the fraction of generated clinical assertions that are factually incorrect: H(𝒢)=|{a𝒜(𝒢):a is 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 prel, the hallucination rate of the RAG-augmented model satisfies (RAG Hallucination)H(𝒢RAG)(1prel)H(𝒢)+prelεres, where εres 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 prel is high and εresH(𝒢), 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 prel), and those for which it does not (probability 1prel). In the first case, the model has access to correct information and hallucinates with probability εres. In the second case, the model operates without relevant retrieved context and hallucinates at its baseline rate H(𝒢). By the law of total expectation, H(𝒢RAG)=prelεres+(1prel)H(𝒢), which is exactly (RAG Hallucination). Since εres<H(𝒢) whenever the retrieved documents are informative, we have H(𝒢RAG)<H(𝒢).

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 pipeline for clinical segmentation. The clinical query (image plus text) is encoded and used to retrieve the most relevant documents from a knowledge base comprising medical literature, annotated case studies, and patient history. The retrieved documents and original query are jointly processed by a VLM reasoning engine, which produces a grounded segmentation report whose assertions are traceable to specific source documents.
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 p=0.63 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:

  1. 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 u(𝒙)[0,1]H×W, where high values indicate uncertain predictions.

  2. Uncertainty region extraction. Connected components of the thresholded uncertainty map {(i,j):uij>τu} 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).

  3. 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 ±0.08 in this region. Consider requesting a delayed-phase contrast sequence for better boundary delineation.”

  4. 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 𝒮:[0,1]H×W×𝒳𝒯 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 𝒜u denote the set of actionable recommendations that could be derived from the uncertainty map. A semantic summary s=𝒮(u,𝒙) is complete if every recommendation a𝒜u is either explicitly stated in s or logically entailed by the statements in s. It is sound if every recommendation stated in s belongs to 𝒜u. 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 41% compared to 78% 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 (x,y,t) 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 𝒂rad[0,1]H×W and the model's attention map 𝒂model[0,1]H×W, the attention alignment loss is (Attention Alignment)attn=KL(𝒂rad𝒂model)=i,j𝒂rad(i,j)log𝒂rad(i,j)𝒂model(i,j), 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:

  1. 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.

  2. 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.

  3. Resolution mismatch. Medical images often contain subtle findings (a 3 mm nodule in a 512×512 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.

  4. 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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)CHAIRmed=|{a𝒜:a(𝒙)}||𝒜|, where 𝒜 is the set of clinical assertions in the generated text and (𝒙) is the set of ground-truth findings in image 𝒙. A CHAIRmed score of 0.15 means that 15% of the model's assertions are hallucinated.

However, CHAIRmed 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 N image–text pairs.

  1. Show that as τ0+, 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 limτ0+InfoNCE=0 if and only if 𝒗i𝒖i>𝒗i𝒖j for all ji and all i.

  2. Show that as τ, the gradients of the InfoNCE loss vanish, so the model learns nothing. Specifically, compute 𝒗iInfoNCE and show that 𝒗iInfoNCE0 as τ.

  3. In practice, CLIP uses a learned temperature initialised at τ=0.07. 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.

  4. (Bonus.) Suppose the embeddings are uniformly distributed on the unit sphere in d. Derive the expected InfoNCE loss as a function of N, d, and τ, under the assumption that positive pairs have cosine similarity ρ>0 and negative pairs have expected cosine similarity 0.

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.

  1. 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.

  2. Design the query encoder q(𝒙,t). The input is a contrast-enhanced CT image 𝒙 and a clinical question t (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.

  3. Derive an expression for the expected number of retrieved documents r needed to achieve a target hallucination rate Htarget, as a function of the base model's hallucination rate H(𝒢), the retriever's relevance probability prel(r) (which increases with r), and the residual hallucination rate εres.

  4. 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.

  1. Propose a self-verification protocol for medical VLMs. Given a generated report r and the input image 𝒙, design a procedure that identifies which assertions in r 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.

  2. The CHAIRmed metric defined in (Chair) treats all hallucinations equally. Design a severity-weighted variant CHAIRmedw that assigns higher weight to clinically dangerous hallucinations. Define a severity function w(a) for assertions a and write the formula for CHAIRmedw. Discuss how the severity weights should be determined (by clinical experts, by consequence analysis, or by other means).

  3. 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 1.2 cm nodule is seen in the right upper lobe.” The ground-truth findings are: left-sided pleural effusion and adjacent atelectasis. Compute CHAIRmed and, using a severity scheme of your design, compute CHAIRmedw. Discuss which hallucinated assertion is more clinically concerning and why.

  4. (Bonus.) Prove that the multi-model consensus approach (running K independent VLMs and accepting only assertions that appear in all K outputs) reduces the hallucination rate exponentially in K, under the assumption that each model hallucinates independently with probability h. 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 p(y|x)=p(y|z)p(z|x)dz where z 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 𝒱train denote the set of class labels seen during training and 𝒱test the set of class labels encountered at test time, with 𝒱test⊈𝒱train in general. An open-vocabulary segmentation model is a mapping (OPEN Vocab)f:𝒳×𝒱{0,1}H×W, where 𝒳 is the image space, 𝒱 is the space of all natural-language class descriptions, and f(x,v) produces a binary mask for the concept described by v in image x. The model must generalise to v𝒱test𝒱train 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 xH×W×3 and a text query v (e.g., “polyp”), the CLIP image encoder ϕimg and text encoder ϕtxt produce feature maps and embeddings, respectively. Let 𝐅imgh×w×d be the spatial feature map from an intermediate layer of the CLIP vision transformer, and 𝐞txtd be the text embedding. The correlation map is (CORR MAP)𝐂(i,j)=𝐅img(i,j)𝐞txt𝐅img(i,j)𝐞txt,(i,j){1,,h}×{1,,w}. This produces a heatmap 𝐂h×w 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-K locations in 𝐂 are extracted as point prompts: (Pseudo Prompts)𝒫={(ik,jk)}k=1K,where 𝐂(ik,jk)τprompt, with τprompt 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)𝐛=[minkikδ,minkjkδ,maxkik+δ,maxkjk+δ].

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)𝐅fused=CrossAttn(𝐅SAM,𝐅CLIP)+𝐅SAM, where 𝐅SAMh×w×d is SAM's image embedding and 𝐅CLIP is projected to compatible dimensions. The fused features are decoded by SAM's lightweight mask decoder to produce the final segmentation y^[0,1]H×W.

Example 26 (ESC-Net for Polyp Detection without Manual Prompts).

Consider a colonoscopy video frame x and the text query v= “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 K=5 point prompts clustered on the polyp surface and a tight bounding box with δ=8 pixels of dilation. These are passed to SAM's decoder, which produces a mask achieving a Dice score of 0.89 on this frame-comparable to the 0.91 achieved by an expert gastroenterologist's manual annotation and significantly surpassing the 0.72 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 0.874 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:

  1. The prompt generator 𝒢:𝒳𝒫 maps an input image x to a set of prompts p𝒫 (points, bounding boxes, or dense embeddings) without human intervention.

  2. The foundation segmenter 𝒮:𝒳×𝒫[0,1]H×W produces a segmentation mask given the image and prompts.

The pipeline is self-contained in the sense that no external input beyond the image x is required at inference time: (SELF Prompting)y^=𝒮(x,𝒢(x)).

Diffusion-based prompt generation.

Consider a denoising diffusion model ϵθ(xt,t) trained on medical images with associated segmentation masks. At inference, rather than generating a full image, we run the reverse process for only TT steps from a partially noised version of the input image. The intermediate activations of the U-Net at time step t 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)𝐀t(l)=softmax(𝐐t(l)(𝐊t(l))dk), where 𝐐t(l) and 𝐊t(l) are the query and key matrices at layer l and time step t. 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 (x,y) pairs, where y is a segmentation mask. The encoder qϕ(z|x) maps images to a latent space that captures the location and extent of structures of interest. A lightweight decoder gψ(z) then produces prompt coordinates: (VAE Prompt)({(ik,jk)}k=1K,𝐛)=gψ(𝔼qϕ(z|x)[z]), outputting K point prompts and a bounding box. The entire system is trained end-to-end with a composite loss: (SELF Prompt LOSS)self-prompt=seg(𝒮(x,gψ(z)),y)segmentation quality+λKL𝖣KL(qϕ(z|x)p(z))+λpromptloc(gψ(z),𝒫(y))prompt localisation, where 𝒫(y) denotes ground-truth prompts derived from mask y (e.g., centroid points and tight bounding boxes), and loc is a smooth-1 localisation loss.

Iterative self-refinement.

Self-prompting pipelines can be made iterative. Let y^(0)=𝒮(x,𝒢(x)) be the initial segmentation. The prompt generator can then be re-run on the composite input (x,y^(0)) to produce refined prompts: (Iterative Refine)y^(r+1)=𝒮(x,𝒢(x,y^(r))),r=0,1,,R1. Empirically, convergence to a stable mask is typically achieved within R=3 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 p(y^|x,promptϵ), 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 p2 denote a point prompt and y=SAM(x,p) the corresponding mask. The joint distribution over prompt locations and resulting masks, conditioned on image x, is (Joint Prompt MASK)p(y,p|x)=p(y|x,p)p(p|x). The first factor is deterministic (SAM's decoder is deterministic given a prompt), so all stochasticity comes from p(p|x), the distribution over “reasonable” prompt locations. The marginal mask distribution is obtained by integrating out prompts: (Marginal MASK)p(y|x)=p(y|x,p)p(p|x)dp. This integral is intractable because p(y|x,p) 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 zdz be a latent variable. The generative model and inference network are: (Taming Prior)Prior:pθ(z|x)=𝒩(z;μθ(x),σθ2(x)𝐈),Decoder:pθ(p,y|x,z)=pθ(p|x,z)δ(ySAM(x,p)),Encoder:qϕ(z|x,p,y)=𝒩(z;μϕ(x,p,y),σϕ2(x,p,y)𝐈). The decoder first predicts a prompt location p from the latent code z and image x, then passes this prompt through SAM's frozen decoder to produce the mask y. The Dirac delta in Equation encodes the fact that SAM is deterministic.

The training objective is the conditional ELBO: (Taming ELBO)cVAE=𝔼qϕ(z|x,p,y)[logpθ(y|x,z)]+β𝖣KL(qϕ(z|x,p,y)pθ(z|x)), where β controls the trade-off between reconstruction quality and latent space regularity.

Proposition 9 (Taming SAM's Prompt Sensitivity).

Let SAM(x,):2{0,1}H×W denote SAM's deterministic mask decoder for image x, and let pθ(p|x,z) be the prompt distribution learned by the cVAE decoder. Then:

  1. Diversity: Sampling z(1),,z(S)pθ(z|x) and decoding y^(s)=SAM(x,𝔼pθ(p|x,z(s))[p]) produces a set of masks whose pairwise Dice dissimilarity 1Dice(y^(s),y^(s)) approximates the inter-annotator variability observed in multi-reader studies.

  2. Controllability: The granularity of the sampled masks is monotonically related to the norm z: small z produces conservative (smaller) masks while large z produces liberal (larger) masks, reflecting different levels of boundary inclusion.

  3. Calibration: The pixel-wise entropy of the averaged prediction y=1Ss=1Sy^(s) is a calibrated measure of segmentation uncertainty: the expected calibration error satisfies ECE(y)ECE(y^single)+O(1/S), where y^single 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 pθ(z|x) 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 pθ(p|x,z) learns to map the radial component z 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 y is a Monte Carlo estimate of p(yij=1|x)=p(yij=1|x,z)pθ(z|x)dz. By the law of large numbers, yijp(yij=1|x) as S. Standard calibration theory then gives ECE(y)ECE(p(|x))+O(1/S), and p(|x) 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 3M parameters compared to SAM's 632M, and training converges in under 50 epochs on a single GPU. At inference, one samples S latent codes, decodes each to a prompt, runs SAM S times (the image encoding is cached and reused), and aggregates the resulting masks. With S=16, this adds less than 0.5s 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:

  1. SegmentNet fseg: A standard encoder–decoder (e.g., U-Net or nnU-Net) that produces an initial coarse segmentation mask y^coarse and extracts the initial contour 𝒞(0) as the zero-level set of the signed distance function of y^coarse.

  2. LatentNet flat: A conditional VAE whose encoder maps the image x and a specific expert's ground-truth mask ye to a latent code zedz, capturing that expert's annotation style: (Latentnet)qϕ(ze|x,ye)=𝒩(ze;μϕ(x,ye),σϕ2(x,ye)𝐈). At inference, sampling zep(z) yields different expert styles without access to any expert's ground truth.

  3. ContourNet fctr: A deformation network that takes the initial contour 𝒞(0), the image features, and the expert-style latent ze, and produces a per-vertex displacement field: (Contournet)𝒞e=𝒞(0)+fctr(x,𝒞(0),ze).

Training objective.

The full ContourMS loss combines segmentation quality, contour accuracy, expert-style fidelity, and latent regularisation: (Contourms LOSS)ContourMS=Dice(y^coarse,y)SegmentNet+λctrCD(𝒞e,𝒞e)Chamfer distance+λKL𝖣KL(qϕ(ze|x,ye)p(ze)), where CD 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: ze(s)p(ze)=𝒩(0,𝐈) for s=1,,S. The resulting contours {𝒞e(s)}s=1S 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 ϵθimg and ϵψmask denote the image and mask diffusion models, respectively. The forward process corrupts both with the same noise realisation: (Siamese IMG FWD)xt=αtx0+1αtϵ,mt=αtm0+1αtϵ, where ϵ𝒩(0,𝐈) 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)ϵ^img=ϵθimg(xt,t,StopGrad(𝐡tmask)),ϵ^mask=ϵψmask(mt,t,StopGrad(𝐡timg)), where 𝐡timg and 𝐡tmask are intermediate feature maps from the respective U-Nets, and StopGrad 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 x^0=denoise(xt;ϵθimg) and m^0=denoise(mt;ϵψmask) be the predicted clean image and mask at time step t. The consistency loss is: (Consistency LOSS)consist=x^0(1m^0)1+λedgem^0x^0m^01, 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 (x^0,m^0) are generated by sampling shared noise ϵ𝒩(0,𝐈) 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 3:1 (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:

  1. Contextual understanding (VLM): A medical VLM (e.g., Med-PaLM M or LLaVA-Med) receives the scan x and patient metadata (age, clinical indication, imaging modality) and generates a structured context description: (VLM Context)c=VLMcontext(x,metadata).

  2. Prompt synthesis (VLM Prompt Generator): The context description c is converted into segmentation prompts via the self-prompting pipeline of Section Automated Prompt Generation via Generative Models: (Prompt Synth)𝒫=𝒢(x,c).

  3. 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)y^init=SAM(x,𝒫).

  4. Generative refinement (Diffusion + cVAE): The initial segmentation is refined by a conditional diffusion model that corrects boundary errors and, optionally, samples S alternative masks via the cVAE mechanism of Section Taming SAM with Conditional VAEs: (Diffusion Refine){y^(s)}s=1Spθ(y|x,y^init).

  5. 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)report=VLMreport(x,{y^(s)}s=1S,measurements).

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, 256×256×64 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 K=8 point prompts on the enhancing mass and a bounding box of 42×38×24 voxels.

Stage 3 (Segmentation): MedSAM processes each axial slice with the projected 2D prompts, producing an initial 3D segmentation with Dice =0.83 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 S=16 samples, the mean Dice improves to 0.88, and the boundary uncertainty map correctly highlights the posterior margin as the region of highest ambiguity (pixel-wise entropy >0.7).

Stage 5 (Report): The VLM generates: “Segmentation identifies a 2.1×1.8×1.4,cm enhancing mass in the left breast, upper outer quadrant. Irregular margins with spiculations anteriorly. Volume: 2.7±0.3,mL (95% CI from 16 segmentation samples). Posterior margin poorly defined with high segmentation uncertainty (entropy 0.72), suggesting possible chest wall involvement-recommend dedicated chest wall protocol. BIRADS-5: Highly suggestive of malignancy.

The entire pipeline executes in 47 seconds on a single A100 GPU, with the diffusion refinement stage consuming 31 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 ϕFM:𝒳h×w×d be the frozen feature extractor from a vision foundation model. The GMS framework consists of:

  1. A feature projector gα:h×w×dh×w×d that adapts the foundation features to the medical domain (a single 1×1 convolution layer with dd).

  2. A latent segmentation head hβ:h×w×d[0,1]H×W×C comprising a lightweight decoder (two transposed convolution layers and a sigmoid output) that predicts per-class segmentation probabilities.

The full model is: (GMS)y^=hβ(gα(ϕFM(x))), with only α and β being trainable. The number of trainable parameters is typically <1M, compared to 30M for a standard U-Net and 300M for nnU-Net with large encoders.

Why “generative”?

The framework earns the “generative” label because the pre-trained features ϕFM(x) 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 0.8M trainable parameters achieves:

  • Mean Dice =0.847, compared to 0.831 for a fully trained U-Net with 31M parameters.

  • Mean Dice =0.847, compared to 0.852 for nnU-Net with 93M parameters (a difference within the standard error).

  • Training time: 15 minutes per task on a single GPU, compared to 8 hours for nnU-Net.

  • Data efficiency: with only 10% of training data, GMS achieves 0.812 mean Dice compared to 0.743 for U-Net and 0.798 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 38× 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 1M 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:

  1. A generator Gω:𝒵𝒳×𝒴 that maps latent codes zp(z) to image–mask pairs (xsyn,ysyn).

  2. A task model Tξ:𝒳𝒴 (the segmentor) trained on both real and generated data.

  3. A multi-level optimisation coupling the two: (Genseg Outer)ω=arg minωval(Tξ(ω),𝒟val),whereξ(ω)=arg minξtrain(Tξ,𝒟trainGω(𝒵)).

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 𝒟train and generated data Gω(𝒵). 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)valω=valξξ(ω)ω, 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 K gradient steps on the segmentor and uses the resulting ξK(ω) as a proxy for ξ(ω). The outer gradient is then: (Genseg Approx)valωvalξKk=0K1(𝐈η2train(k)ξ2)train(0)ω, where η is the inner learning rate. In practice, K=5 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 val(ξ(ω)) be the outer objective in the GenSeg bi-level optimisation (Equations (Genseg Outer)(Genseg Outer)), where ξ(ω) denotes the minimiser of the inner problem. Assume:

  1. (A1)

    The inner loss train(ξ;ω) is μ-strongly convex in ξ for each ω.

  2. (A2)

    The outer loss val(ξ) is Lout-smooth.

  3. (A3)

    The cross-derivative 2trainξω is bounded in spectral norm by ρ.

  4. (A4)

    The inner loop runs for K gradient descent steps with learning rate η<2/Lin, where Lin is the smoothness constant of the inner loss.

  5. (A5)

    The outer loop uses learning rate ηout with stochastic gradient estimates of variance σ2.

Then after T outer iterations, the expected gradient norm satisfies: (Genseg Convergence)1Tt=1T𝔼[ωval(ξ(ωt))2]2(val(ξ(ω0))val)ηoutT+ηoutLoutσ2+Loutρ2μ2(1ημ)2K, where val is the infimum of the outer objective. The three terms represent, respectively, the optimisation error (decreasing with T), the stochastic gradient noise floor, and the inner-loop approximation error (decreasing exponentially with K).

Proof.

The proof proceeds in three steps.

Step 1: Inner-loop approximation error. Since train(;ω) is μ-strongly convex (A1) and Lin-smooth, gradient descent with η<2/Lin converges linearly: (Inner Converge)ξK(ω)ξ(ω)(1ημ)Kξ0(ω)ξ(ω).

Step 2: Gradient estimation error. The approximate outer gradient using ξK instead of ξ introduces a bias. By the chain rule and smoothness of val (A2): (GRAD BIAS)ωval(ξK(ω))ωval(ξ(ω))LoutξKωξω. By the implicit function theorem, ξω=(2trainξ2)12trainξω, which has norm bounded by ρ/μ using (A1) and (A3). The difference between K-step and exact implicit derivatives is bounded by (ρ/μ)(1ημ)K.

Step 3: Outer-loop convergence. Applying standard analysis for SGD on Lout-smooth functions with biased, noisy gradients yields: (Final Bound)1Tt=1T𝔼[ωval(ξ(ωt))2]2Δ0ηoutT+ηoutLoutσ2+Loutρ2μ2(1ημ)2K, where Δ0=val(ξ(ω0))val, completing the proof.

Remark 35.

The bound in Equation has an elegant interpretation. The first term is the standard optimisation convergence rate O(1/T). 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 K inner steps instead of solving to convergence introduces an exponentially decaying error. For K=5 and typical values ημ0.1, the inner-loop error is (0.9)100.35, which is already small. Increasing to K=10 reduces it to 0.12. In practice, K=5 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 Ntrain=10 annotated images. The experimental setup is as follows:

Generator: A conditional diffusion model Gω 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 Tξ trained from scratch.

Baselines:

  • U-Net trained on 10 images only: Dice =0.52.

  • U-Net with standard augmentation (rotation, flipping, elastic deformation): Dice =0.61.

  • U-Net with task-agnostic diffusion augmentation (generate 200 synthetic pairs, no feedback): Dice =0.68.

  • U-Net with GenSeg (task-coupled, K=5 inner steps, T=100 outer iterations): Dice =0.79.

Analysis: GenSeg improves over task-agnostic augmentation by +0.11 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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)𝒰:𝒳×𝒱Δ({0,1}H×W)×𝒱, where 𝒳=m𝒳m 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 x𝒳m and a query v𝒱, the system produces: (Universal Output)(p(y|x,v),r)=𝒰(x,v), where p(y|x,v) is a distribution over segmentation masks and r 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.

  1. (a)

    Let 𝐀t(l)h×w be the aggregated attention map at layer l and time step t (Equation (DIFF ATTN)). Define the multi-scale aggregated attention as 𝐀t=1||lResizeh×w(𝐀t(l)), where is a set of selected layers and Resize bilinearly interpolates to a common resolution. Derive the time-averaged map 𝐀=1Tt=1T𝐀t and show that if attention maps across time steps are i.i.d. with mean μA and variance σA2, the variance of 𝐀 at each pixel is σA2/T.

  2. (b)

    Design a criterion for selecting the threshold τprompt 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.

  3. (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).

  1. (a)

    Suppose the inner loss is train(ξ;ω)=1Ni=1N(Tξ(xi),yi)+1Mj=1M(Tξ(Gω(zj)),Gωy(zj)), where Gω(z)=(Gωx(z),Gωy(z)) produces image–mask pairs. Derive the implicit gradient ξω using the implicit function theorem, and show that it requires computing (2trainξ2)1.

  2. (b)

    Prove that the first-order approximation used in GenSeg (taking K inner gradient steps and differentiating through them) recovers the exact implicit gradient in the limit K when the inner problem is strongly convex.

  3. (c)

    In the GenSeg convergence theorem (Theorem Theorem 4), determine the optimal choice of K (number of inner steps) and ηout (outer learning rate) as functions of T (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 𝐝=fctr(x,𝒞(0),ze) that deforms the initial contour.

  1. (a)

    To ensure that the deformed contour 𝒞e=𝒞(0)+𝐝 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 𝐯: 𝒞e=ϕ1(𝒞(0)),dϕtdt=𝐯(ϕt,t),ϕ0=id. Show that if 𝐯 is Lipschitz continuous with constant L, then ϕ1 is a diffeomorphism and the Jacobian determinant satisfies exp(L)|detJϕ1|exp(L).

  2. (b)

    Propose a regularisation loss for ContourNet that penalises non-diffeomorphic deformations. How does this relate to the smoothness of the generated expert contours?

  3. (c)

    Given E expert annotators with latent codes z1,,zE, define a consensus contour as 𝒞consensus=1Ee=1E𝒞e. 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 𝒰:{0,1} be a clinical utility function that maps a model to a deployment decision. Then (Clinical Utility)𝒰()=1Acc()τaccFair()τfairCost()τcostReg()=1, where Acc, Fair, Cost, and Reg 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 512×512×128 volume can consume 40–80,GB of GPU memory per patient.

The computational budget of a segmentation pipeline can be decomposed as follows. Let T denote the number of diffusion steps, C the number of channels at the bottleneck resolution, S the spatial resolution of the volume (voxels per dimension), and B the batch size. The peak memory footprint scales as (Memory Scaling)MemBTCS3κoverhead factor, where κ1 accounts for activation checkpointing, optimizer states, and gradient accumulation buffers. For a typical 3D medical diffusion model with T=100, C=256, S=128, and κ4 (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 𝑾d×d and learns a low-rank update Δ𝑾=𝑨𝑩 with 𝑨d×r, 𝑩d×r, and rank rd. The number of trainable parameters drops from d2 to 2dr, a reduction of d/(2r). For a model with d=1024 and r=16, this represents a 32× reduction. Adapter layers insert small bottleneck modules into each transformer block: (Adapter)𝒉out=𝒉in+σ(𝒉in𝑾down)𝑾up, where 𝑾downd×r, 𝑾upr×d, 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 48×.

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 8×A100 GPUs for inference or 64×A100 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 fT be the teacher (foundation model) and fS the student. The distillation loss combines task supervision with feature alignment: (Distillation)distill=seg(fS(𝒙),𝒚)+λ=1Lϕ(fS(𝒙))ϕ(fT(𝒙))22, where ϕ extracts the feature map at layer and λ controls the alignment strength. Recent work has demonstrated that student networks with 10× 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 {H1,H2,,HK} denote K hospitals, each holding a private dataset 𝒟k={(𝒙i(k),𝒚i(k))}i=1nk of medical images 𝒙i(k) and corresponding segmentation masks 𝒚i(k). Federated learning (FL) trains a shared global model f𝜽 by iterating the following protocol:

  1. Broadcast: The server sends the current global parameters 𝜽(t) to all participating hospitals.

  2. Local training: Each hospital Hk performs E epochs of local optimisation: (Local Update)𝜽k(t+1)=𝜽(t)ηe=1E𝜽k(𝜽;𝒟k), where k is the local segmentation loss.

  3. Aggregation: The server computes a weighted average of the local updates: (Fedavg)𝜽(t+1)=k=1Knkj=1Knj𝜽k(t+1).

No raw patient data 𝒙i(k) ever leaves hospital Hk. 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 P parameters requires transmitting P floating-point numbers per communication round. For a model with P=500 million parameters in 32-bit precision, each round requires transmitting approximately 2,GB per hospital. With K=10 hospitals and R=200 communication rounds, the total communication volume is (COMM COST)Comm=2KRP(bytes per param)=2×10×200×2GB=8TB, 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-k gradient components: (TOPK)𝒈~k=TopK(𝜽k(𝜽;𝒟k),s), where s is the sparsity ratio (e.g., s=0.01 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 (𝑨k,𝑩k), reducing communication by d/(2r) as in the centralised setting.

Cross-centre domain shift.

Perhaps the most insidious challenge is heterogeneous data distributions across hospitals. Hospital H1 may use a Siemens 3T MRI scanner, while H2 uses a GE 1.5T scanner. The resulting distribution shift, p1(𝒙|y)p2(𝒙|y), means that the global model 𝜽(t) may be far from optimal for any individual hospital. In the federated optimisation landscape, this manifests as conflicting gradient directions: (Gradient Conflict)1(𝜽),2(𝜽)<0, causing the global update to oscillate rather than converge. FedProx (Li et al., 2020) mitigates this by adding a proximal term μ2𝜽k𝜽(t)2 to each local objective, preventing local models from drifting too far from the global consensus.

Federated learning architecture for multi-hospital medical segmentation. Each hospital trains locally on its private data 𝒟k and transmits only model parameters to the aggregation server. The server computes a weighted average (FedAvg) and broadcasts the updated global model back to all hospitals. No raw patient data crosses institutional boundaries.

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 𝒟k but also uses a local generative model Gk to synthesise additional training examples 𝒟~k. The augmented local dataset 𝒟k𝒟~k improves local model quality, and the federated aggregation then combines these improvements across all hospitals. Crucially, the synthetic data 𝒟~k 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)kaug(𝜽)=1nk+mk(i=1nk(f𝜽(𝒙i(k)),𝒚i(k))+j=1mk(f𝜽(𝒙~j(k)),𝒚~j(k))), where mk=|𝒟~k| is the number of synthetic samples and (𝒙~j(k),𝒚~j(k))Gk.

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 r=8), the global model achieves:

SettingMean DiceWorst-Site Dice
Hospital A only (centralised)0.89-
Each hospital alone (isolated)0.72±0.110.58
FedAvg (no augmentation)0.840.74
FedAvg + local generative aug.0.870.81
The federated model with generative augmentation closes 70% of the gap to the centralised ceiling while never sharing a single patient image. Notably, the largest improvement occurs at Hospital E (the most data-scarce site), whose local Dice increases from 0.58 to 0.81, a clinically meaningful improvement.

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)𝒚^=𝒙0=f𝜽(𝒙T,𝒙T1,,𝒙1,𝒄), where 𝒙T𝒩(0,𝑰) is pure noise, each 𝒙t1 is sampled from p𝜽(𝒙t1|𝒙t,𝒄), 𝒄 is the conditioning image, and the final 𝒙0 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 𝑨(1) reflects the specific noise trajectory (𝒙T(1),,𝒙1(1)) that was sampled. A second run with different noise 𝒙T(2) produces a different attribution map 𝑨(2), 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 T denoising steps. At step T, the boundary does not exist; at step T/2, 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 M stochastic runs. The expected attribution map is (Ensemble Attribution)𝑨=1Mm=1M𝑨(m),Var[𝑨]j=1Mm=1M(Aj(m)Aj)2, where 𝑨(m) is the attribution map from the m-th run and j indexes spatial locations. Regions with high Var[𝑨]j 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:

  1. Mean performance: The expected Dice score 𝔼𝒙T[Dice(f𝜽(𝒙T,𝒄),𝒚)] exceeds a clinically meaningful threshold τD.

  2. Worst-case performance: The α-quantile of the Dice score distribution exceeds τDδ for specified tolerance δ: (Regulatory Quantile)Pr[Dice(f𝜽(𝒙T,𝒄),𝒚)τDδ]1α.

  3. Calibration: The predicted uncertainty (variance across samples) is well-calibrated with respect to actual errors.

  4. 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 {βt}t=1T and its effect on output variability.

  • Characterisation of the output distribution p𝜽(𝒚^|𝒄) 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 f𝜽:𝒳𝒴 be a segmentation model, let g:𝒳𝒢 be a function mapping each input to a sensitive attribute g(𝒙)𝒢 (e.g., 𝒢={skin tone I,,skin tone VI} on the Fitzpatrick scale), and let Perf(f𝜽,𝒟g) denote a performance metric evaluated on the subgroup 𝒟g={(𝒙,𝒚):g(𝒙)=g}. The model f𝜽 satisfies ϵ-group fairness if (Group Fairness)maxg,g𝒢|Perf(f𝜽,𝒟g)Perf(f𝜽,𝒟g)|ϵ. The model satisfies δ-minimax fairness if (Minimax Fairness)ming𝒢Perf(f𝜽,𝒟g)δ. 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:

  1. 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.

  2. 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).

  3. Scanner bias: If hospitals serving different demographic populations use different scanner brands, the model may learn scanner-specific shortcuts that correlate with demographics.

  4. 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 w:𝒢+ that adjusts the training loss to equalise performance across groups: (Fairness Reweight)fair(𝜽)=g𝒢w(g)(𝜽;𝒟g),w(g)1Perf(f𝜽,𝒟g), 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 TypeDice Scoren (test set)
Type I (very fair)0.91±0.04842
Type II (fair)0.90±0.051,203
Type III (medium)0.88±0.05674
Type IV (olive)0.83±0.07189
Type V (brown)0.76±0.0973
Type VI (dark)0.71±0.1131
The performance gap between Type I and Type VI is 0.910.71=0.20, far exceeding any reasonable ϵ for group fairness. This 20-point Dice gap is clinically dangerous: melanoma detection is already more difficult on darker skin (due to reduced contrast between the lesion and surrounding skin), and a model that segments poorly on exactly these patients compounds existing health disparities rather than mitigating them.

The root cause is stark: the test set contains 842 images of Type I but only 31 images of Type VI, a 27× 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 TypeBeforeAfter DRO
Type I0.910.89
Type VI0.710.82
Gap0.200.07
The Type I Dice decreases by 0.02 (clinically negligible), while the Type VI Dice increases by 0.11 (clinically significant), reducing the fairness gap from 0.20 to 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 𝒟src denote the source domain (training hospital) and 𝒟tgt the target domain (deployment hospital). The generalisation gap is (GEN GAP)Δgen=Perf(f𝜽,𝒟src)Perf(f𝜽,𝒟tgt). Empirically, Δgen 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:

  1. 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).

  2. Domain randomisation: Augmenting training data with synthetic domain shifts (intensity transformations, synthetic artefacts, resolution changes) to make the model invariant to scanner-specific characteristics.

  3. 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.

  4. Style transfer: Using generative models (GANs, diffusion models) to transform source-domain images into target-domain style while preserving anatomical content: (Style Transfer)𝒙~src=Gstyle(𝒙src,stgt), where stgt 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)Perf(f𝜽,𝒟tgt)Perf(f𝜽,𝒟src)Cd(𝒟src,𝒟tgt)λ, where d 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 𝑿H×W×D×T. 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 𝑿H×W×D×T that produces spatiotemporal uncertainty maps 𝑼[0,1]H×W×D×T satisfying the following calibration property: for any spatiotemporal region Ω{1,,H}××{1,,T} and any confidence level α(0,1), (4D Calibration)Pr[1|Ω|(i,j,k,t)Ω𝟏[y^ijktyijkt]1|Ω|(i,j,k,t)ΩUijkt]1α. 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 256×256×128×25 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 t depends on the segmentation at frames t1 and t+1. Capturing this coupling requires either:

  1. A joint diffusion process over the entire 4D volume, which is computationally intractable with current architectures.

  2. An autoregressive approach that conditions each temporal frame on the preceding frames, which introduces error accumulation and breaks temporal symmetry.

  3. 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 T=1000 denoising steps; even accelerated samplers (DDIM, DPM-Solver) require T=20100 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 {βt}t=1T and learned score function s𝜽(𝒙t,t), there exists a fundamental lower bound on the number of function evaluations (NFE) required to achieve a given segmentation quality q: (Speed Quality)NFE(q)clog(11q), where c>0 is a constant depending on the data dimension, the score estimation error 𝔼[s𝜽logpt2], and the curvature of the probability flow ODE. In particular, achieving q0.99 (e.g., Dice0.99) requires NFEclog(100)4.6c, while q0.999 requires NFEclog(1000)6.9c. The logarithmic scaling is optimistic in theory but the constant c is large in practice (typically c5), 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 fψ that maps directly from noise to clean segmentation: (Consistency)fψ(𝒙t,t)𝒙0for all t[0,T], 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 ={f1,f2,,fN} be a set of N specialised segmentation models, where fi is optimised for task τi𝒯 (e.g., τ1= “cardiac MRI segmentation”, τ2= “retinal OCT layer segmentation”). Let funiv be any single universal model trained on the union i=1N𝒟i of all training datasets. Then for any funiv with parameter count P, there exists a task τ𝒯 and a specialised model f with parameter count PP/N such that (NO Universal)Perf(f,τ)>Perf(funiv,τ). 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)fMoE(𝒙)=i=1Ngi(𝒙)fi(𝒙),gi(𝒙)=ewiϕ(𝒙)j=1Newjϕ(𝒙), where ϕ(𝒙) is a shared feature representation, gi is the gating weight for expert i, and each expert fi 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 N experts and a stream of segmentation tasks from diverse modalities and organ systems, design a routing algorithm g:𝒳ΔN1 (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)Regret(g)=1|𝒯|τ𝒯[Perf(fi(τ),τ)Perf(fMoEg,τ)], where i(τ)=arg maxiPerf(fi,τ) 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: (Navier Stokes)ρ(𝒗t+(𝒗)𝒗)=p+μ2𝒗+𝒇,𝒗=0, where 𝒗 is the velocity field, p 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)phys=seg(𝒚^,𝒚)segmentation loss+λNSρ(t𝒗+(𝒗)𝒗)+pμ2𝒗Ω(𝒚^)2Navier–Stokes residual, 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:

  1. Differentiable: Gradients 𝒚^NS residual2 must be computable via automatic differentiation.

  2. Efficient: The cost of evaluating the physics loss must be at most 𝒪(NlogN) per training step, where N is the number of voxels, to remain tractable for 3D volumes.

  3. 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.

The interpretability–performance frontier in medical image segmentation. Each point represents a class of methods. The Pareto frontier (dashed grey curve) shows the empirically observed tradeoff: higher performance comes at the cost of lower interpretability. The amber box indicates the ideal region (high performance and high interpretability) that current methods cannot reach.
Can we have both?

Several recent approaches attempt to break the interpretability–performance tradeoff:

  1. 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.

  2. Post-hoc diffusion explanations: The ensemble attribution method of (Ensemble Attribution) provides statistical explanations for diffusion models, sacrificing per-run determinism for aggregate interpretability.

  3. 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.

  4. 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.

The active learning + generative augmentation loop for self-improving medical segmentation. The model segments new volumes, estimates uncertainty, selects high-uncertainty cases for human annotation, and retrains on the augmented dataset. A generative model produces additional synthetic training data seeded by the newly annotated cases (dashed arrows), amplifying the value of each human annotation.
Acquisition functions for segmentation.

The active learning framework requires an acquisition function a:𝒳 that assigns a score to each unlabelled volume, indicating how informative its annotation would be. For segmentation, natural choices include:

  1. Predictive entropy: The average per-voxel entropy of the model's predictive distribution: (Entropy ACQ)aent(𝒙)=1Nvj=1NvH[p(yj|𝒙)], where Nv is the number of voxels and H[] is the Shannon entropy.

  2. Boundary uncertainty: The average uncertainty along the predicted segmentation boundary: (Boundary ACQ)abnd(𝒙)=1|𝒚^|j𝒚^Var[y^j(m)]m=1M, where 𝒚^ denotes the set of voxels on the predicted boundary and the variance is computed across M stochastic forward passes.

  3. Expected model change: The expected change in model parameters if the volume were annotated and the model retrained: (EMC ACQ)aemc(𝒙)=𝔼𝒚|𝒙[𝜽new(𝒙,𝒚)𝜽2], 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 G can produce K variations: (GEN Amplification){(𝒙~k,𝒚~k)}k=1KG(|𝒙,𝒚), each preserving the anatomical structure of 𝒙 while varying scanner characteristics, noise levels, and contrast. The effective training set grows by K 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 t produces a model f𝜽(t) and incurs an annotation cost ct. The cumulative cost is CT=t=1Tct, and the model quality is QT=Perf(f𝜽(T),𝒟test). The optimal stopping problem is: (Optimal Stopping)T=arg minT1{CT:QTQtarget}, where Qtarget 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 k 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:

  1. Prompt compositionality: Performance when combining text, visual, and interactive prompts.

  2. Prompt robustness: Sensitivity to prompt variations (e.g., rephrasing text, shifting click points by a few pixels).

  3. Iterative refinement: Performance improvement over multiple interaction rounds.

  4. Multi-metric evaluation: Dice, Hausdorff distance, boundary F1, topological accuracy, and clinical-task-specific metrics.

  5. Fairness stratification: All metrics reported per demographic subgroup.

  6. 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 K=5 hospitals, each with local loss function k(𝜽). Assume each local loss is L-smooth and μ-strongly convex, and that the local gradients have bounded variance: 𝔼[k(𝜽)(𝜽)2]σ2 for all k, where (𝜽)=1Kk=1Kk(𝜽) is the global objective.

  1. Show that after R communication rounds of FedAvg with learning rate η and E local epochs per round, the convergence rate of the global objective satisfies (𝜽(R))(𝜽)(1ημ)RE((𝜽(0))(𝜽))+ηLσ2E2μK. Identify the terms corresponding to optimisation error and statistical error respectively.

  2. The second term increases with the number of local epochs E. Explain intuitively why more local computation can hurt convergence in the presence of heterogeneous data (σ2>0).

  3. Propose a modification to FedAvg that reduces the statistical error term without increasing communication frequency. Hint: Consider FedProx with proximal parameter μprox.

  4. If Hospital E has only n5=75 patients while Hospital A has n1=800, should the aggregation weights wk=nk/jnj 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 f𝜽 evaluated on |𝒢|=6 demographic groups (Fitzpatrick Types I–VI). Let dg=Dice(f𝜽,𝒟g) denote the Dice score on group g.

  1. Define the fairness–accuracy Pareto frontier as the set of all models 𝜽 for which no other model 𝜽 achieves both higher average Dice d=16g=16dg and lower fairness gap Δ=maxg,g|dgdg| simultaneously. Sketch what this frontier might look like and argue whether it is convex or non-convex.

  2. Prove that the distribution-aware reweighting scheme of (Fairness Reweight), in the limit of perfect optimisation, converges to a minimax-fair solution satisfying d1=d2==d6. Under what conditions on the data does this minimax-fair solution also maximise average Dice?

  3. 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 ϵ<dmaxdmin.

  4. Propose a Pareto-aware training algorithm that explores the fairness–accuracy frontier by solving a sequence of scalarised objectives λ=(1λ)d+λΔ for λ[0,1]. What are the endpoints of this family (λ=0 and λ=1), 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 A,BΩ be two binary segmentation masks defined on a discrete image domain Ω with |Ω|=N pixels. The Dice coefficient and Intersection-over-Union (IoU, also called the Jaccard index) are defined as (DICE DEF)Dice(A,B)=2|AB||A|+|B|,IoU(A,B)=|AB||AB|.

  1. Dice–IoU relationship. Prove that the Dice coefficient and IoU are related by (DICE IOU)Dice=2IoU1+IoU. Hint: Start from |AB|=|A|+|B||AB| and substitute into the definitions. Show also the inverse: IoU=Dice/(2Dice).

  2. Dice is not a metric. Recall that a function d:2Ω×2Ω[0,1] is a metric if it satisfies (i) d(A,B)=0A=B, (ii) d(A,B)=d(B,A), and (iii) d(A,B)+d(B,C)d(A,C) (triangle inequality). Define the Dice distance as dDice(A,B)=1Dice(A,B).

    Show that dDice satisfies (i) and (ii) but fails the triangle inequality (iii). Construct an explicit counterexample with three sets A,B,C{1,2,,10} where the triangle inequality is violated.

    Hint: Choose A and C with no overlap and B overlapping partially with both.

  3. Gradient of the soft Dice loss. In practice we work with soft predictions. Let pi[0,1] denote the predicted probability at pixel i and gi{0,1} the ground truth. The soft Dice loss is (SOFT DICE)Dice=12i=1Npigi+ϵi=1Npi+i=1Ngi+ϵ, where ϵ>0 is a smoothing constant. Compute the gradient Dice/pj for an arbitrary pixel j. Express the result in terms of the numerator 𝒩=2ipigi+ϵ and denominator 𝒟=ipi+igi+ϵ.

    Verify that the gradient magnitude is larger for false positives (pixels where pj is high but gj=0) than for true positives (pixels where both pj and gj are high), and explain why this property is beneficial for imbalanced segmentation tasks.

  4. When does Dice loss outperform cross-entropy? Consider a binary segmentation problem where the foreground occupies only 1% of the image. Let CE denote the standard binary cross-entropy loss.

    enumerate[label=()]

  5. Show that a trivial classifier predicting pi=0 for all pixels achieves CE0.01|logϵ| (small) but Dice1 (maximal).

  6. Argue that cross-entropy is dominated by the easy-to-classify background pixels, while Dice loss focuses on the overlap with the foreground.

  7. Discuss practical scenarios (e.g., small polyp segmentation, retinal vessel segmentation) where this difference is clinically significant.

  8. Under what conditions might a combined loss =αCE+(1α)Dice outperform either loss alone? enumerate

Exercise 35 (U-Net Architecture Analysis).

Consider a standard U-Net with L=4 encoder levels. At each level, the encoder applies two 3×3 convolutions (each followed by batch normalisation and ReLU) and then a 2×2 max pooling. The decoder applies a 2×2 transposed convolution for upsampling, concatenates the corresponding encoder feature map via a skip connection, and then applies two 3×3 convolutions. Let the initial number of channels be C0=64, doubling at each level: C=642 for =0,1,2,3. The bottleneck has C4=1024 channels.

  1. Receptive field computation. Compute the theoretical receptive field of the U-Net at the output layer. Recall that for a single 3×3 convolution, the receptive field increases by 2 pixels per layer. Account for: enumerate[label=()]

  2. The two convolutions at each encoder level.

  3. The 2×2 max pooling, which doubles the effective receptive field of subsequent layers.

  4. The bottleneck convolutions.

  5. 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)R=1+=0L222=1+4(2L+11). Evaluate R for L=4 and discuss whether this is sufficient to capture global context in a 512×512 CT slice.

  6. Parameter count. Compute the total number of trainable parameters in the network. For each 3×3 convolutional layer with Cin input channels and Cout output channels, the parameter count is 9CinCout+Cout (weights plus biases). Carefully account for: enumerate[label=()]

  7. Encoder: the first convolution at level maps C1C (with C1=1 for grayscale input), and the second maps CC.

  8. Bottleneck: two convolutions at the deepest level.

  9. Decoder: the transposed convolution maps CC1; after skip concatenation, the input has C1+C1=2C1 channels; two convolutions then map 2C1C1 and C1C1.

  10. Final 1×1 convolution for classification. enumerate Express the total as a function of C0 and L, and evaluate numerically.

  11. Skip connections and gradient flow. Consider training the U-Net with the Dice loss from Exercise 34. Let 𝐡enc denote the encoder feature map at level , and let 𝐡dec denote the corresponding decoder feature map.

    enumerate[label=()]

  12. Without skip connections, write the backpropagation path from the loss to 𝐡0enc and count the number of nonlinear layers the gradient must traverse.

  13. With skip connections, identify the shortest gradient path from the loss to 𝐡0enc and compare.

  14. Relate this to the vanishing gradient problem: if each nonlinear layer attenuates gradients by a factor γ<1, by what factor is the gradient attenuated in each case? enumerate

  15. Minimal U-Net design. Design a minimal U-Net variant for 64×64 grayscale images with only L=2 levels and C0=16. 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 𝐂(s)=(x(s),y(s)) for s[0,1] and minimises the energy functional (Snake Energy)E(𝐂)=01[α|𝐂(s)|2+β|𝐂(s)|2]ds+01Eext(𝐂(s))ds, where α>0 controls elasticity (resistance to stretching), β>0 controls rigidity (resistance to bending), and Eext(x,y) is an external energy derived from the image (typically Eext=|I(x,y)|2 for an image I).

  1. 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)α𝐂(s)+β𝐂(s)+Eext(𝐂(s))=𝟎 for all s(0,1), 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 dE/dϵ|ϵ=0=0.

  2. Discrete approximation. Discretise the contour as N points {𝐯i=(xi,yi)}i=1N with uniform spacing h=1/N. Approximate the derivatives: 𝐂(si)𝐯i+1𝐯i12h,𝐂(si)𝐯i+12𝐯i+𝐯i1h2. Write the resulting discrete Euler–Lagrange system in matrix form: (Discrete Snake)(α𝐀+β𝐁)𝐯=𝐟ext, where 𝐯=(𝐯1,,𝐯N) and 𝐟ext collects the external forces. Identify the structure of the matrices 𝐀 and 𝐁 (they should be banded and circulant for a closed contour).

  3. Failure modes. Describe and explain at least three situations where the classical snake model fails: enumerate[label=()]

  4. The contour is initialised too far from the target boundary.

  5. The target object has a concave boundary.

  6. 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 Eext).

  7. Connection to level sets. The level set method represents the contour implicitly as the zero level set of a function ϕ:Ω: 𝐂={(x,y):ϕ(x,y)=0}. The evolving curve is governed by the PDE (Level SET)ϕt=F|ϕ|, where F is a speed function. Show that if F=ακEext𝐧^, 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 β0).

    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 G produces segmentation masks y^=G(x) from input images x, and a multi-scale discriminator D distinguishes between (image, ground truth mask) pairs (x,y) and (image, generated mask) pairs (x,y^). The training objective is (Segan LOSS)minGmaxD𝔼(x,y)[logD(x,y)]+𝔼x[log(1D(x,G(x)))]+λMAE(G(x),y), where MAE is the mean absolute error and λ>0 is a balancing hyperparameter.

  1. Optimal discriminator. Fix the generator G and derive the optimal discriminator D. Show that for each pair (x,m) (where m is a candidate mask), the optimal discriminator is (Optimal DISC)D(x,m)=pdata(m|x)pdata(m|x)+pG(m|x), where pdata(m|x) is the probability of m being the true mask given x, and pG(m|x) 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.

  2. Mode collapse: a one-dimensional example. Consider a simplified one-dimensional setting where the image x is fixed and the ground truth mask distribution is a mixture of two delta functions: pdata(m)=12δ(ma)+12δ(mb),ab. This models a genuinely ambiguous segmentation with two valid masks.

    enumerate[label=()]

  3. Show that a deterministic generator G can only capture one mode at a time, i.e., pG(m)=δ(mc) for some c.

  4. Compute the Jensen–Shannon divergence JSD(pdatapG) as a function of c and show it is minimised when c=a or c=b (but not at the midpoint (a+b)/2).

  5. Explain why this demonstrates mode collapse and how it manifests in medical image segmentation with ambiguous boundaries. enumerate

  6. 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 {0,1}N).

    enumerate[label=()]

  7. Show that the Jensen–Shannon divergence between two distributions with disjoint supports is always log2, regardless of how “close” the distributions are geometrically.

  8. In contrast, show that the Wasserstein-1 distance W1(p,q)=infγΠ(p,q)𝔼(m,m)γ[mm1] is continuous in the geometric sense: if p and q are supported on nearby (but disjoint) sets, W1 can be arbitrarily small.

  9. Argue why this property makes Wasserstein GANs more suitable for medical image segmentation, where slight boundary shifts should incur small losses. enumerate

  10. 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=()]

  11. Design a protocol for validating the quality and diversity of generated polyps. What quantitative metrics (FID, precision/recall, clinical Turing test) would you use?

  12. 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.

  13. 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 𝐱0 according to (Forward STEP)q(𝐱t|𝐱t1)=𝒩(𝐱t;1βt𝐱t1,βt𝐈),t=1,,T, where {βt}t=1T is the noise schedule with 0<βt<1.

  1. Closed-form marginal. Define αt=1βt and αt=s=1tαs. Prove by induction that (Closed FORM Marginal)q(𝐱t|𝐱0)=𝒩(𝐱t;αt𝐱0,(1αt)𝐈).

    Hint: For the base case t=1, verify directly. For the inductive step, use the fact that if 𝐱t=αt𝐱t1+βt𝝐t and 𝐱t1=αt1𝐱0+1αt1𝝐t1 with independent standard Gaussians 𝝐t and 𝝐t1, then substitute and collect terms.

  2. Signal-to-noise ratio. Define the signal-to-noise ratio at time t as (SNR DEF)SNR(t)=αt1αt. Show that SNR(t) is strictly decreasing in t for any valid noise schedule. That is, show: enumerate[label=()]

  3. αt is strictly decreasing (since each αt<1).

  4. The function f(a)=a/(1a) is strictly increasing on (0,1).

  5. Therefore SNR(t)>SNR(t+1) for all t. enumerate Compute SNR(0), SNR(T) in terms of αT, and verify that SNR(T)0 as αT0.

  6. Number of diffusion steps for medical images. In natural image diffusion, T=1000 is standard. For medical images, several factors differ: enumerate[label=()]

  7. 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.

  8. 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.

  9. Suppose the noise schedule is linear: βt=β1+(t1)(βTβ1)/(T1) with β1=104 and βT=0.02. Compute αT for T=500,1000,2000 and determine the minimum T such that SNR(T)<0.01 (i.e., the signal is essentially destroyed).

  10. Discuss the trade-off between sampling quality and inference time in a clinical setting where real-time segmentation is desirable. enumerate

  11. 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=()]

  12. Argue intuitively that Gaussian noise destroys high-frequency components first. Formalise this by computing the expected power spectrum of 𝐱t: 𝔼[|𝐱^t(k)|2]=αt|𝐱^0(k)|2+(1αt)σk2, where 𝐱^0(k) is the Fourier coefficient at frequency k and σk2 is the noise power (flat for white noise). Show that high-frequency signal components are masked by noise at smaller t than low-frequency components.

  13. 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 y given an image x using a latent variable model. A prior network produces pθ(𝐳|x) and a posterior network produces qϕ(𝐳|x,y), both Gaussian. A U-Net backbone fψ(x) extracts features, and the latent code 𝐳 is injected (e.g., via tiling and concatenation) to produce the final segmentation p(y|x,𝐳).

  1. ELBO derivation. Write the evidence lower bound (ELBO) for this model. Starting from the marginal log-likelihood logpθ(y|x)=logp(y|x,𝐳)pθ(𝐳|x)d𝐳, apply Jensen's inequality (or equivalently, introduce the variational posterior qϕ(𝐳|x,y)) to obtain: (ELBO)logpθ(y|x)𝔼qϕ(𝐳|x,y)[logp(y|x,𝐳)]DKL(qϕ(𝐳|x,y)pθ(𝐳|x)). Identify each term: the reconstruction term (expected negative Dice loss or cross-entropy) and the KL regulariser.

  2. KL + reconstruction decomposition. Show that maximising the ELBO is equivalent to simultaneously minimising the reconstruction error and the KL divergence. Formally, if we denote ELBO=RKL (where R is the reconstruction term and KL is the KL divergence), then: enumerate[label=()]

  3. Increasing R improves mask quality.

  4. Decreasing KL ensures the posterior matches the prior, enabling sampling at test time (when y is not available).

  5. Show that logpθ(y|x)=ELBO+DKL(qϕp(𝐳|x,y)), where p(𝐳|x,y) 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

  6. Latent dimension and diversity. Let 𝐳d where d is the latent dimension. enumerate[label=()]

  7. When d=1, argue that the model can only capture a one-parameter family of segmentation variants (e.g., slight boundary shifts in one direction).

  8. When d is very large (e.g., d=128), 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.

  9. Propose a practical strategy for choosing d. Consider using the number of distinct annotator masks in the training set as a guide. If there are K=4 annotators, what range of d would you recommend and why? enumerate

  10. Sampling and GED evaluation. At test time, sample S=16 latent codes 𝐳(1),,𝐳(S)pθ(𝐳|x) and generate masks y^(1),,y^(S). Suppose the ground truth consists of K=4 annotator masks y(1),,y(4). Compute the Generalised Energy Distance (GED) as defined in ex:medseg:ged.

    Using the following toy Dice values (where d(a,b)=1Dice(a,b)):

    y(1)y(2)y(3)y(4)
    y^(1)0.100.250.300.22
    y^(2)0.280.080.150.20
    y^(3)0.150.180.120.25
    y^(4)0.300.220.280.09
    y^(5)0.200.140.180.16
    and intra-set distances: mean d(y^(i),y^(j))=0.20, mean d(y(i),y(j))=0.18, compute a numerical estimate of the GED.

Exercise 40 (Generalized Energy Distance).

The Generalized Energy Distance (GED) between two distributions P and Q over segmentation masks, using a base distance d, is defined as (GED DEF)DGED2(P,Q)=2𝔼YP,YQ[d(Y,Y)]𝔼Y,YP[d(Y,Y)]𝔼Y,YQ[d(Y,Y)].

  1. Formal definition and interpretation. Explain each of the three terms in (GED DEF): enumerate[label=()]

  2. The cross-term 2𝔼[d(Y,Y)] measures the average distance between samples from P and Q.

  3. The term 𝔼P[d(Y,Y)] measures the spread (diversity) of P.

  4. The term 𝔼Q[d(Y,Y)] measures the spread of Q. enumerate Argue that DGED2 is small when the cross-distances are similar to the within-distribution distances, i.e., when P and Q have similar means and similar variances.

  5. GED equals zero iff distributions match. This is a deep result that depends on d being a negative definite kernel (which the 1 and 2 distances satisfy). Prove the result for the special case where P and Q are finite discrete distributions:

    Let P=i=1npiδai and Q=j=1mqjδbj with d(x,y)=xy. Show that DGED2(P,Q)=0 implies P=Q by arguing that: enumerate[label=()]

  6. Define the energy distance in terms of characteristic functions. For d(x,y)=xyα with α(0,2), the GED can be written as a weighted integral of the squared difference of characteristic functions: DGED2|φP(t)φQ(t)|2w(t)dt for a positive weight w.

  7. Since w(t)>0 everywhere, the integral is zero iff φP=φQ almost everywhere.

  8. Characteristic functions uniquely determine distributions. enumerate

  9. Discrete computation. Let P be the uniform distribution over masks {A1,A2,A3} and Q be the uniform distribution over {B1,B2}, with the following distance matrix (using d=1Dice):

    B1B2
    A10.100.40
    A20.350.15
    A30.200.25
    and intra-distances d(A1,A2)=0.30, d(A1,A3)=0.15, d(A2,A3)=0.25, d(B1,B2)=0.35.

    Compute DGED2(P,Q) explicitly.

  10. 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=()]

  11. If we use the standard Dice coefficient with a single majority vote ground truth, what information is lost?

  12. Show with an example that a deterministic model achieving Dice =0.90 against the majority vote could have DGED2=0.15, while a probabilistic model with Dice =0.85 against the majority vote might achieve DGED2=0.05.

  13. 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.

  1. Point prompt perturbation. Let y^p=SAM(x,p) denote the binary mask produced by SAM for image x with a single positive point prompt at pixel location p=(px,py). Define the local sensitivity as (Prompt Sensitivity)S(p,δ)=1|𝒩δ(p)|p𝒩δ(p)(1Dice(y^p,y^p)), where 𝒩δ(p) is the set of pixel locations within distance δ of p.

    For δ=5 pixels on a 512×512 image: enumerate[label=()]

  2. How many perturbations are in 𝒩5(p)?

  3. If the average Dice between the original and perturbed masks is 0.92, what is S(p,5)?

  4. Argue that S(p,δ) should be higher near object boundaries than in object interiors. Why?

  5. How does prompt sensitivity relate to the clinical risk of using SAM for interactive segmentation? enumerate

  6. Experimental design. Design a rigorous experiment to measure SAM's prompt sensitivity across different medical imaging modalities. Specify: enumerate[label=()]

  7. The dataset: at least 3 modalities (e.g., CT, MRI, endoscopy) with at least 100 images each.

  8. The prompt sampling strategy: how to select initial prompt locations (random within ground truth, centroid, boundary).

  9. The perturbation protocol: range of δ values to test.

  10. The evaluation metrics: sensitivity S, mask stability (IoU between consecutive perturbations), and clinical acceptability.

  11. Statistical analysis: how to determine whether sensitivity differences across modalities are significant. enumerate

  12. Negative prompts for small organs. Consider segmenting a small structure (e.g., the pancreas, which occupies <1% of a CT volume).

    enumerate[label=()]

  13. Explain why a negative prompt placed inside a nearby large organ (e.g., the liver) might inadvertently suppress parts of the small target organ.

  14. 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.

  15. Under what conditions (relative organ size, distance between organs) is this effect most severe? enumerate

  16. Robust prompting strategy. Propose a multi-prompt strategy that reduces sensitivity to individual prompt placement. Your strategy should: enumerate[label=()]

  17. Use K positive prompts sampled from a prior distribution over likely foreground locations.

  18. Aggregate multiple SAM outputs (e.g., via majority voting, STAPLE, or averaging logits).

  19. Provide a theoretical justification for why aggregation reduces variance. If individual masks have sensitivity S, show that majority voting over K independent masks reduces the effective sensitivity by a factor of approximately 1/K.

  20. Discuss the computational overhead: if SAM runs in t0 ms per prompt, what is the total time for K prompts, and what K is feasible for interactive (sub-second) segmentation? enumerate

Exercise 42 (CycleGAN for Medical Domain Adaptation).

CycleGAN learns mappings G:XY and F:YX between two unpaired image domains using cycle consistency. Consider domain X as CT images from hospital A and domain Y as CT images from hospital B, acquired with different scanners (different reconstruction kernels, noise characteristics, and contrast protocols).

  1. Full CycleGAN loss. Write out the complete CycleGAN training objective: (Cyclegan LOSS)(G,F,DX,DY)=GAN(G,DY,X,Y)+GAN(F,DX,Y,X)+λcyccyc(G,F)+λidid(G,F), where: enumerate[label=()]

  2. GAN(G,DY,X,Y)=𝔼y[logDY(y)]+𝔼x[log(1DY(G(x)))] is the adversarial loss for G.

  3. cyc(G,F)=𝔼x[F(G(x))x1]+𝔼y[G(F(y))y1] is the cycle consistency loss.

  4. id(G,F)=𝔼y[G(y)y1]+𝔼x[F(x)x1] is the identity loss. enumerate Explain the role of each term and typical values for λcyc and λid.

  5. Cycle consistency for medical images. enumerate[label=()]

  6. Explain why cycle consistency is particularly important for medical images: the mapping should change the style (scanner characteristics) without altering the content (anatomy, pathology).

  7. Consider a patient with a small lung nodule in domain X. If G maps this image to domain Y 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 F(G(x))x, then G(x) must contain enough information to reconstruct x, including the nodule.

  8. Give an example where cycle consistency is satisfied but content is still altered. Hint: Consider steganographic encoding. enumerate

  9. CycleGAN artifacts. Enumerate and explain at least four types of artifacts that CycleGAN can introduce in medical images: enumerate[label=()]

  10. Checkerboard artifacts from transposed convolutions in the generator.

  11. Hallucinated structures (e.g., adding or removing lesions) that satisfy cycle consistency via steganography.

  12. Geometric distortions that warp anatomical structures.

  13. 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.

  14. Validation protocol. Design a comprehensive validation protocol for using CycleGAN-adapted images to train a segmentation model. Your protocol should include: enumerate[label=()]

  15. A quantitative check for anatomical preservation (e.g., segmenting structures before and after translation and comparing masks).

  16. A distribution-level check (e.g., comparing HU histograms of translated images against real images from the target domain).

  17. A downstream task evaluation: train a segmentation model on adapted data and evaluate on real target domain data.

  18. 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 t with detected cells in frame t+1. Let 𝒟t={d1t,,dmt} be detections in frame t and 𝒟t+1={d1t+1,,dnt+1} be detections in frame t+1.

  1. Bipartite matching formulation. Formalise cell tracking between consecutive frames as a bipartite matching problem. Define a cost matrix 𝐂m×n where (COST Matrix)Cij=w1𝐩it𝐩jt+12+w2|aitajt+1|+w3(1IoU(dit,djt+1)), where 𝐩it is the centroid position, ait is the area, and IoU is the mask overlap of detection i in frame t. The weights w1,w2,w30 control the relative importance.

    Write the integer linear program (ILP) for the assignment: (ILP)min𝐗i=1mj=1nCijXijs.t.j=1nXij1i,i=1mXij1j,Xij{0,1}. Explain why the constraint allows jXij=0 (a cell in frame t disappears) and iXij=0 (a new cell appears in frame t+1).

  2. Hungarian algorithm complexity. The Hungarian algorithm solves the assignment problem in O(max(m,n)3) time.

    enumerate[label=()]

  3. For a typical cell tracking scenario with m=n=500 cells per frame, estimate the computation time assuming 108 operations per second. Is this feasible for real-time tracking?

  4. Describe how to augment the cost matrix to handle the rectangular case mn by adding dummy rows or columns with cost Cmax (a threshold for accepting new tracks/terminations).

  5. Discuss alternative algorithms (auction algorithm, Jonker–Volgenant) and their practical advantages. enumerate

  6. Handling cell division. Standard bipartite matching assumes one-to-one assignment, but cells can divide (mitosis), creating a one-to-two correspondence.

    enumerate[label=()]

  7. Propose a modification to the ILP that allows one detection in frame t to be matched to at most two detections in frame t+1. Write the modified constraint.

  8. 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).

  9. How would you detect a division event retroactively: if cell i at time t has two potential matches j1,j2 at time t+1, what features of dit, dj1t+1, and dj2t+1 would you check? enumerate

  10. 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=()]

  11. Dense cell populations: when cells are tightly packed, detection errors (merges, splits) propagate to tracking errors.

  12. Low frame rate: when the time between frames is large relative to cell displacement, the cost matrix becomes ambiguous (many plausible matches).

  13. 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.

  1. Dynamic conditional encoding. In MedSegDiff, the conditioning image x is not simply concatenated with the noisy mask yt. Instead, a dynamic conditional encoder Eθ processes x at multiple scales and modulates the denoising U-Net's feature maps via feature-wise linear modulation (FiLM): (FILM)𝐡=γ(Eθ(x))𝐡+β(Eθ(x)), where 𝐡 is the feature map at level in the denoising U-Net, and γ,β are learned affine parameters derived from the image encoder.

    enumerate[label=()]

  2. Explain why this is called “dynamic”: the modulation parameters γ and β change for each input image x.

  3. Compare this to concatenation-based conditioning, where [yt;x] is fed as input. What additional expressiveness does FiLM provide?

  4. Count the additional parameters introduced by FiLM at each level compared to concatenation. enumerate

  5. Concatenation vs. cross-attention conditioning. Compare three conditioning strategies for diffusion-based segmentation:

    enumerate[label=()]

  6. Concatenation: ϵ^θ(yt,t,x)=Uθ([yt;x],t), where [;] denotes channel-wise concatenation.

  7. Cross-attention: ϵ^θ(yt,t,x)=Uθ(yt,t) with cross-attention layers where Q comes from yt and K,V come from an encoding of x.

  8. FiLM: as in part (a). enumerate

    For each, analyse: (1) the computational cost in terms of the spatial resolution H×W and channel count C; (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 x and yt?).

  9. Feature Frequency Parser (FF-Parser). MedSegDiff-V2 introduces an FF-Parser that operates on the frequency spectrum of intermediate features.

    enumerate[label=()]

  10. The FF-Parser applies a 2D discrete Fourier transform to the feature map 𝐡, applies a learnable mask 𝐌 in frequency space, and transforms back: 𝐡parsed=1(𝐌(𝐡)). Explain the purpose of this operation: it allows the model to selectively amplify or suppress different frequency components.

  11. 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).

  12. What is the computational cost of the FF-Parser relative to spatial convolution? Compare the cost of a 2D FFT (O(HWlog(HW))) to a 3×3 convolution (O(9CHW)). enumerate

  13. Extension to 3D volumes. Design a conditioning mechanism for diffusion-based segmentation of 3D medical volumes (e.g., D×H×W CT scans). enumerate[label=()]

  14. Discuss whether the 2D FiLM approach extends naturally to 3D or whether modifications are needed for the depth dimension.

  15. Propose a “2.5D” approach that processes individual 2D slices but aggregates 3D context via a separate module. Describe the architecture.

  16. Discuss memory constraints: a 128×256×256 volume with 64 channels requires approximately 128×256×256×64×4 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.

  1. Hallucination in medical VLMs. Define hallucination formally in the context of medical image segmentation. A VLM hallucinates when it produces a segmentation mask y^ such that: enumerate[label=()]

  2. y^ includes a region that does not correspond to any anatomical structure matching the text prompt (fabrication).

  3. y^ omits a region that clearly matches the text prompt (omission).

  4. y^ 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.

  5. RAG for reducing hallucination. Retrieval-augmented generation (RAG) can ground VLM outputs in verified knowledge.

    enumerate[label=()]

  6. 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.

  7. Formally, let (x,q) be the retrieval function that returns k reference pairs (xiref,yiref) for query image x and text q. The augmented VLM produces: y^=VLM(x,q,(x,q)). Argue that grounding in retrieved examples reduces fabrication by providing visual evidence of what the target structure looks like.

  8. 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

  9. Text prompt design. Design a text prompt for segmenting the liver in an abdominal CT scan. Consider multiple levels of specificity: enumerate[label=()]

  10. Simple: “Segment the liver.”

  11. 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.”

  12. 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).

  13. 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=()]

  14. Define the experimental protocol: same base model (e.g., SAM-Med2D), same test set, same evaluation metrics (Dice, HD95).

  15. For text-guided: use standardised anatomical prompts for each of the 13 organs.

  16. 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).

  17. 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 K hospitals, each with a local dataset 𝒟k={(xik,yik)}i=1nk.

  1. FedAvg for segmentation. Write the Federated Averaging (FedAvg) algorithm for training a U-Net segmentation model.

    enumerate[label=()]

  2. Server initialisation: initialise global model parameters θ0.

  3. Local training: at round r, each hospital k receives θr, performs E local epochs of SGD on 𝒟k to obtain θkr+1: (Local SGD)θkr+1=θrηe=1Eθk(θ;e), where e is a mini-batch from 𝒟k.

  4. Aggregation: the server computes (Fedavg)θr+1=k=1Knkknkθkr+1. enumerate Write pseudocode for the complete algorithm including the communication protocol.

  5. Domain shift between hospitals. Different hospitals use different scanners, protocols, and patient populations, creating domain shift.

    enumerate[label=()]

  6. Formalise domain shift: hospital k has data distribution Pk(x,y)=Pk(x)Pk(y|x), where both the marginal Pk(x) (covariate shift) and the conditional Pk(y|x) (concept shift, e.g., different annotation guidelines) may differ.

  7. Show that FedAvg implicitly optimises minθk(nk/n)k(θ), which may not converge to a good solution when the Pk are very different. Construct an example with K=2 hospitals where the FedAvg solution is worse than either local model.

  8. Propose a modification (e.g., FedProx, personalised layers, domain-specific batch normalisation) and explain how it addresses the domain shift problem. enumerate

  9. 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 C and noise 𝒩(0,σ2C2𝐈) is added, with σc2ln(1.25/δ)/ϵ for a constant c.

    enumerate[label=()]

  10. For ϵ=1,δ=105,C=1, compute the noise standard deviation σ.

  11. Estimate the impact on segmentation quality. If the model has P=31 million parameters and the signal-to-noise ratio of the aggregated update is SNR=Δθ2/(σCP), compute the SNR for Δθ2=0.1 and the σ from (i).

  12. Based on empirical studies, a rule of thumb is that Dice drops by approximately 25% for ϵ1. Discuss whether this trade-off is acceptable for different clinical applications (screening vs. surgical planning).

  13. How does the privacy budget compose over R rounds of federated training? Use the moments accountant to give a tighter bound than naive composition (ϵtotal=Rϵ). enumerate

  14. Communication-efficient protocol. Each round of FedAvg requires transmitting the full model (120 MB for a large U-Net) from each hospital to the server and back.

    enumerate[label=()]

  15. Propose three methods to reduce communication cost: gradient compression (top-k sparsification), quantisation (from 32-bit to 8-bit or 1-bit), and local SGD with fewer communication rounds.

  16. For top-k sparsification with k=1% of parameters, compute the compression ratio and estimate the Dice degradation (empirically, <0.5% for k1%).

  17. Design a complete protocol specifying the communication schedule, compression method, and convergence criterion. How many rounds R are typically needed for convergence with K=10 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.

  1. Formalising domain shift. Let 𝒮={(xis,yis)} be labelled source data from distribution PS and 𝒯={xjt} be unlabelled target data from PT. The domain shift can be decomposed as: (Domain Shift)PS(x,y)=PS(x)PS(y|x)PT(x)PT(y|x)=PT(x,y).

    enumerate[label=()]

  2. Covariate shift: PS(x)PT(x) but PS(y|x)=PT(y|x). Give a medical imaging example (e.g., different MRI field strengths produce different image appearances but the segmentation labels are the same).

  3. Label shift: PS(y)PT(y) but PS(x|y)=PT(x|y). Give a medical imaging example (e.g., different disease prevalence between sites).

  4. Concept shift: PS(y|x)PT(y|x). Give a medical imaging example (e.g., different annotation guidelines between institutions).

  5. Write the Ben-David domain adaptation bound: (BEN David)ϵT(h)ϵS(h)+dΔ(PS,PT)+λ, where ϵT(h) is the target error, ϵS(h) is the source error, dΔ is the Δ-divergence, and λ is the optimal joint error. Explain each term. enumerate

  6. CycleGAN-based adaptation. CycleGAN (Exercise 42) can reduce domain shift by translating source images to look like target images.

    enumerate[label=()]

  7. Let G:𝒮𝒯 be the CycleGAN generator. The adapted training set is {(G(xis),yis)}. Under what assumptions on G are the source labels yis still valid for the translated images?

  8. Show that if G 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.

  9. Discuss failure modes: when might the translated images G(xis) be out-of-distribution for the target domain? enumerate

  10. 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)xadapted=denoise(ατxs+1ατϵ,condition=“target domain”).

    enumerate[label=()]

  11. 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.

  12. 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.

  13. 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

  14. GAN-based vs. diffusion-based adaptation. Design a head-to-head comparison experiment.

    enumerate[label=()]

  15. Source domain: cardiac MRI from one scanner (e.g., 1.5T Siemens). Target domain: cardiac MRI from another scanner (e.g., 3T Philips).

  16. 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).

  17. Evaluation: Dice, Hausdorff distance, and a novel metric you propose that captures both segmentation accuracy and anatomical plausibility.

  18. What sample sizes are needed for the comparison to be statistically powered? Use a power analysis assuming effect size δ=2% in Dice, standard deviation σ=5%, significance level α=0.05, and power 1β=0.80. 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 y(1),y(2),y(3),y(4) be four annotator masks for a single image.

  1. Majority vote and information loss. The majority vote mask is defined pixel-wise: (Majority VOTE)yiMV={1if k=14yi(k)2,0otherwise, for pixel i.

    enumerate[label=()]

  2. 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.

  3. 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.

  4. Show that the Dice score between any individual annotator mask and the majority vote is bounded: Dice(y(k),yMV)1 with equality only when all annotators agree everywhere.

  5. Define the inter-annotator agreement using pairwise Dice: A=(42)1k<kDice(y(k),y(k)). Show that if A=0.85, the inherent segmentation uncertainty is approximately 1A=0.15, which sets a ceiling on achievable performance. enumerate

  6. Probabilistic multi-annotator model. Design a model that preserves individual annotator characteristics instead of collapsing to a single ground truth.

    enumerate[label=()]

  7. Model architecture: Extend the Probabilistic U-Net (Exercise 39) with an annotator embedding. For each annotator k, learn an embedding vector 𝐞kd. The generative model produces p(y|x,𝐳,𝐞k), allowing it to generate masks in the “style” of annotator k.

  8. Training objective: Write the modified ELBO that sums over annotators: (Multi Annot ELBO)=k=1K𝔼q(𝐳|x,y(k))[logp(y(k)|x,𝐳,𝐞k)]+k=1KDKL(q(𝐳|x,y(k))p(𝐳|x)).

  9. At test time: how do you generate a “consensus” mask and an “uncertainty” map? Propose sampling from p(𝐳|x) and marginalising over annotator embeddings. enumerate

  10. Annotator weighting. Not all annotators are equally reliable. Some annotators may be more experienced (e.g., a senior radiologist vs. a trainee).

    enumerate[label=()]

  11. The STAPLE algorithm estimates annotator reliability parameters {pk,qk} (sensitivity and specificity for each annotator k) 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).

  12. 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.

  13. 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

  14. Connection to the ambiguity problem. The multi-annotator setting is a special case of the broader ambiguity problem in segmentation.

    enumerate[label=()]

  15. 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 P(y|x). Explain why training with a single sample and cross-entropy loss biases the model towards the mode of P(y|x).

  16. Show that training with multiple annotator masks using the model in part (b) approximates the full distribution P(y|x), not just its mode.

  17. 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 T=501000 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 <50 ms per frame (20 fps).

The Challenge. Design a diffusion-based segmentation system that achieves:

  • Latency: <50 ms end-to-end on a single GPU (including image loading, preprocessing, inference, and postprocessing).

  • Accuracy: within 2% Dice of the full T-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:

  1. Progressive distillation. Train a student model sϕ that reproduces the output of two teacher denoising steps in a single step. Iterating log2T times yields a model that performs the full diffusion in a single step. The distillation loss for step halving is (Distillation)distill(ϕ)=𝔼t,𝐱0[sϕ(𝐱t,t)𝐱^02step22], where 𝐱^02step is the two-step teacher prediction. Analyse: how many rounds of distillation are needed to go from T=1000 to T=1? What accuracy is lost at each stage?

  2. Consistency models. Consistency models learn to map any point on the diffusion trajectory directly to the clean data: fθ(𝐱t,t)=𝐱0 for all t. The consistency condition is (Consistency)fθ(𝐱t,t)=fθ(𝐱t,t)t,t[0,T], where 𝐱t and 𝐱t 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?

  3. Architectural optimisation. Replace the standard U-Net backbone with an efficient architecture: itemize

  4. MobileNet-style depthwise separable convolutions.

  5. Linear attention mechanisms (O(n) instead of O(n2)).

  6. 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.

  7. 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 S=16 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.

  1. Self-supervised pre-training. Design a pre-training objective that learns cell representations from unlabelled microscopy videos. Consider: itemize

  2. Masked autoencoding (MAE) on spatiotemporal patches.

  3. Contrastive learning: pull together representations of the same cell across time, push apart representations of different cells.

  4. Predictive coding: given frames 1,,t, predict the cell configuration at frame t+1. itemize Which objective best captures the dynamics needed for tracking?

  5. Modality-agnostic representation. Different modalities produce fundamentally different image statistics. Propose a representation that is invariant to imaging modality: (Modality Invariant)fθ:𝒳any𝒵,d(fθ(xfluor),fθ(xphase))0 when xfluor and xphase 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.

  6. Division-aware architecture. Standard tracking models use bipartite matching (one-to-one assignment). For cell division, extend the architecture to predict: itemize

  7. A division probability pdiv(i,t) for each cell i at time t.

  8. The expected positions of daughter cells.

  9. The optimal cost assignment under the modified ILP from Exercise 43. itemize

  10. 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 ϵ10 and δ105.

  • 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 55% (near random).

Technical Directions.

  1. 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 C and Gaussian noise 𝒩(0,σ2C2) is added to the aggregated gradient: (Dpsgd)g~t=1Bi=1Bclip(θi,C)+𝒩(0,σ2C2𝐈). Analyse: (1) how does the noise level σ affect image quality? (2) how does the clipping norm C affect training stability? (3) what is the privacy cost per epoch, and how many epochs can you afford?

  2. PATE for generative models. An alternative to DP-SGD is Private Aggregation of Teacher Ensembles (PATE). Train an ensemble of K “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.

  3. Post-hoc sanitisation. Rather than training with DP-SGD, train a standard generative model and then sanitise the synthetic data by: itemize

  4. Removing outliers that are too close to real training images (measured by perceptual distance).

  5. Adding noise to the latent codes before generating images.

  6. 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?

  7. Evaluation of privacy. Design a comprehensive privacy evaluation: itemize

  8. Black-box membership inference: train an attack model to distinguish training set members from non-members.

  9. 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.

  10. Re-identification: attempt to match synthetic images to specific patients using anatomical landmarks.

  11. 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 ϵ1 (strong privacy) while maintaining Dice 85% 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 x (CT, MRI, ultrasound, endoscopy, or histology),

  • A text description q (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 y^ without having seen any labelled examples of that specific structure, achieving Dice 0.70 on previously unseen target types.

Technical Directions.

  1. VLM reasoning + SAM execution pipeline. Decompose the problem into two stages: enumerate[label=()]

  2. Reasoning: A medical VLM (e.g., Med-PaLM, BiomedCLIP) interprets the text q and the image x 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.

  3. 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)y^=SAM(x,VLMprompt(x,q)). 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?

  4. 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

  5. Pre-training on radiology reports paired with images (weak supervision: reports mention structures but do not provide masks).

  6. Fine-tuning on a small set of text–mask pairs using visual grounding loss.

  7. Retrieval augmentation: retrieve similar cases from a database to provide in-context examples. itemize

  8. 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=()]

  9. The system produces an initial segmentation and a confidence map.

  10. If confidence is low in certain regions, the system asks a clarifying question (e.g., “Should I include the surrounding oedema?”).

  11. The user responds, and the system refines the segmentation. enumerate Formalise this as an iterative process: y^k+1=f(x,q,y^k,rk), where rk is the user's response at iteration k.

  12. 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)𝐞text=TextEnc(q,m), where m{CT,MRI,US,} 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 pi at each pixel is calibrated, as measured by the pixel-level Expected Calibration Error (ECE): (ECE)ECE=b=1B|Sb|N|acc(Sb)conf(Sb)|, where Sb is the set of pixels in confidence bin b, acc(Sb) is the empirical accuracy, and conf(Sb) is the mean confidence. Target: ECE <0.05.

  • 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 0.90,” 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.

  1. Sources of uncertainty. Medical image segmentation uncertainty arises from multiple sources: itemize

  2. Aleatoric uncertainty (data noise): irreducible uncertainty due to image acquisition noise, motion artefacts, and inherent ambiguity in boundary delineation.

  3. Epistemic uncertainty (model uncertainty): reducible with more data, arising from limited training data and model capacity.

  4. 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.

  5. 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=()]

  6. Propose an extension of temperature scaling to segmentation: apply a spatially varying temperature T(i) at each pixel i: p~i=σ(logit(pi)/T(i)). How should T(i) be learned? Consider: global T, class-specific Tc, or a learned spatial map Tθ(x).

  7. 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.

  8. 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

  9. Decision-theoretic evaluation. Define a clinical decision problem: enumerate[label=()]

  10. The clinician must decide between two treatment options (e.g., surgery vs. watchful waiting) based on tumour volume.

  11. The tumour volume is estimated from the segmentation mask.

  12. 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)C=cFPP(unnecessary surgery)+cFNP(missed tumour)+crefP(referral to expert). 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.

  13. Generative uncertainty quantification. Use the multi-sample capability of generative models (Probabilistic U-Net, diffusion models) to estimate uncertainty: itemize

  14. Generate S segmentation samples y^(1),,y^(S).

  15. Compute the pixel-wise entropy: H(i)=pilogpi(1pi)log(1pi), where pi=S1sy^i(s).

  16. Compute the structure-level uncertainty: the variance of Dice across samples: Var[Dice(y^(s),y)]. 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?