Algorithms

Multi-step processing pipelines built on the Algorithm base class.

Algorithm (Abstract Base)

class medical_image.algorithms.algorithm.Algorithm[source]

Bases: ABC

__init__(device=None, precision=Precision.FULL)[source]
Parameters:
abstractmethod apply(image, output)[source]

Apply the defined operations to the input image.

Parameters:
  • image (Image) – The input image.

  • output (Image) – The output image to store results.

Returns:

The output image after applying the operations.

Return type:

Image

apply_batch(images, outputs)[source]

Process a batch of images. Default: loop over apply(). Subclasses can override for truly batched GPU processing.

Parameters:
Return type:

List[Image]

FebdsAlgorithm

class medical_image.algorithms.FEBDS.FebdsAlgorithm[source]

Bases: Algorithm

Fourier Enhancement and Band-pass Filtering Algorithm for Microcalcification Segmentation.

References:

@article{article,
    author = {Lopez, Elizabeth and Urcid, Gonzalo},
    year = {2016},
    month = {05},
    pages = {},
    title = {Mammograms calcifications segmentation based on band-pass Fourier filtering and adaptive statistical thresholding},
    volume = {5}
}
Math and Logic:

This algorithm aims to enhance microcalcifications by highlighting high-frequency components while removing noise and low-frequency background signals. It supports filtering in the spatial domain using Difference of Gaussians (DoG) or Laplacian of Gaussian (LoG), or in the frequency domain using a Fast Fourier Transform (FFT) with a Butterworth band-pass filter. After enhancement, the image is denoised via median filtering and gamma correction is applied to amplify the calcifications, followed by adaptive thresholding (like Otsu’s) or binarization, and morphological closing to reconstruct regions.

Pipeline:
  1. Apply base enhancement filter depending on the method (dog, log, fft).

  2. Denoise and smooth by taking the absolute value and applying a median filter.

  3. Apply gamma correction to increase the contrast of microcalcifications.

  4. Apply global thresholding (binarize for fft, Otsu for dog/log).

  5. Apply morphological closing and region filling to restore shape and connectivity.

Example:

from medical_image.algorithms.FEBDS import FebdsAlgorithm
from medical_image.data.dicom_image import DicomImage

img = DicomImage("20527054.dcm")
img.load()

algo = FebdsAlgorithm(method="dog", device="cpu")
output = img.clone()
algo(img, output)
__init__(method, device='cpu')[source]
Parameters:
apply(image, output)[source]

Applies the selected method pipeline in-place on output.

Parameters:
Return type:

Image

TopHatAlgorithm

class medical_image.algorithms.top_hat.TopHatAlgorithm[source]

Bases: Algorithm

White Top-Hat enhancement algorithm for microcalcification detection.

Highlights bright structures (e.g., microcalcifications) that are smaller than the selected structuring element.

Math and Logic:

TopHat(I) = I - opening(I, SE)

Pipeline:
  1. Create a disk structuring element of the specified radius.

  2. Perform morphological opening (erosion followed by dilation).

  3. Subtract the opened image from the original image.

Parameters:
  • radius – Disk SE radius (default 4 -> 9x9 footprint).

  • device – Torch device (e.g. “cpu”, “cuda:0”).

__init__(radius=4, device='cpu')[source]
Parameters:
apply(image, output)[source]

Apply white top-hat to the image.

Parameters:
  • image (Image) – Input Image (2D float, e.g. normalized [0,1]).

  • output (Image) – Output Image — pixel_data will contain top-hat result.

Returns:

The output Image.

Return type:

Image

KMeansAlgorithm

class medical_image.algorithms.kmeans.KMeansAlgorithm[source]

Bases: Algorithm

K-Means clustering algorithm for microcalcification segmentation.

Math and Logic:

K-Means partitions image pixels into K distinct, non-overlapping clusters based on pixel intensity. The output is a binary mask where pixels in the brightest cluster are marked as microcalcification candidates.

Pipeline:
  1. Flatten the input image into a 1D feature matrix.

  2. Initialize centroids using k-means++.

  3. Iteratively assign pixels to the nearest centroid and update centroids.

  4. Build a quantized output image and isolate the brightest cluster as the mask.

Attributes after apply():

centroids: (k, d) cluster centroids. labels: (H, W) int hard cluster assignments. quantized: (H, W) float quantized image. stats: List of dicts with cluster statistics. mc_label: int index of the brightest (MC) cluster.

__init__(k=2, max_iter=100, tol=0.0001, random_state=42, device='cpu')[source]
Parameters:
apply(image, output)[source]

Apply k-Means clustering.

Parameters:
  • image (Image) – Input Image (2D float tensor).

  • output (Image) – Output Image — pixel_data = binary MC mask.

Returns:

The output Image.

Return type:

Image

FCMAlgorithm

class medical_image.algorithms.fcm.FCMAlgorithm[source]

Bases: Algorithm

Fuzzy C-Means (FCM) clustering algorithm for microcalcification segmentation.

References:

@article{quintanilla2011image,
  title={Image segmentation by fuzzy and possibilistic clustering algorithms
         for the identification of microcalcifications},
  author={Quintanilla-Dominguez, Joel and others},
  journal={Scientia Iranica},
  volume={18}, number={3}, pages={580--589}, year={2011},
  publisher={Elsevier}
}
Math and Logic:

FCM clusters data points by assigning a fuzzy membership degree to each cluster. It minimizes an objective function based on the distance between pixels and cluster centroids, weighted by their membership degree.

Pipeline:
  1. Flatten the input image into a 1D feature matrix.

  2. Randomly initialize the fuzzy membership matrix.

  3. Iteratively compute distances, update membership probabilities, and update cluster centroids.

  4. Build a quantized output image and isolate the brightest cluster as the mask.

Attributes (populated after apply()):

centroids: (c, d) cluster centroids. membership: (c, N) fuzzy membership matrix U. labels: (H, W) int hard cluster assignments. quantized: (H, W) float quantized image. stats: List of dicts with cluster statistics.

__init__(c=2, m=2.0, max_iter=100, tol=0.001, random_state=42, device='cpu')[source]
Parameters:
apply(image, output)[source]

Apply FCM clustering.

Parameters:
  • image (Image) – Input Image (2D float tensor).

  • output (Image) – Output Image — pixel_data = binary MC mask.

Returns:

The output Image.

Return type:

Image

PFCMAlgorithm

class medical_image.algorithms.pfcm.PFCMAlgorithm[source]

Bases: Algorithm

Possibilistic Fuzzy C-Means (PFCM) algorithm for microcalcification detection.

References:

@article{quintanilla2011image,
  title={Image segmentation by fuzzy and possibilistic clustering algorithms
         for the identification of microcalcifications},
  author={Quintanilla-Dominguez, Joel and others},
  journal={Scientia Iranica},
  volume={18}, number={3}, pages={580--589}, year={2011},
  publisher={Elsevier}
}
Math and Logic:

PFCM extends FCM by adding typicality values that measure how “typical” a sample is for each cluster. Microcalcifications are detected as atypical pixels — those with a low maximum typicality.

Pipeline:
  1. Run standard FCM to warm-start cluster centroids and memberships.

  2. Compute initial gamma values and typicality matrix T.

  3. Iteratively update prototypes, memberships, gammas, and typicalities.

  4. Detect MCs by thresholding the maximum typicality map (atypical pixels).

  5. Exclude the darkest background cluster.

Attributes (populated after apply()):

typicality: (c, N) typicality matrix T. T_max_map: (H, W) max typicality per pixel. centroids: (c, d) cluster centroids. membership: (c, N) fuzzy membership matrix. labels: (H, W) int hard cluster assignments. quantized: (H, W) float quantized image. gamma: (c,) gamma values per cluster.

__init__(c=2, m=2.0, eta=2.0, a=1.0, b=4.0, tau=0.04, max_iter=100, tol=0.001, fcm_max_iter=100, random_state=42, device='cpu')[source]
Parameters:
apply(image, output)[source]

Apply PFCM: warm-start from FCM, iterate PFCM, detect MCs by atypicality.

Parameters:
  • image (Image) – Input Image (2D float tensor).

  • output (Image) – Output Image — pixel_data = binary MC mask.

Returns:

The output Image.

Return type:

Image

BreastMaskAlgorithm

class medical_image.algorithms.breast_mask.BreastMaskAlgorithm[source]

Bases: Algorithm

Breast region masking algorithm for mammograms.

Uses Otsu thresholding + largest connected component to isolate the breast from the background, then applies the mask to the original image.

Parameters:
  • mask_only – If True, output contains the binary mask (0/1) instead of the masked image. Default False.

  • device – Torch device (e.g. “cpu”, “cuda:0”).

__init__(mask_only=False, device=None)[source]
Parameters:
apply(image, output)[source]

Apply breast region masking.

Parameters:
  • image (Image) – Input mammogram.

  • output (Image) – Output Image — will contain either the binary mask (if mask_only=True) or the masked mammogram.

Returns:

The output Image.

Return type:

Image

DicomWindowAlgorithm

class medical_image.algorithms.dicom_window.DicomWindowAlgorithm[source]

Bases: Algorithm

Simple DICOM Window Center / Window Width algorithm.

Maps pixel intensities to [0, 255] using the standard formula:

output = clamp((pixel - (WC - WW/2)) / WW, 0, 1) * 255

If WC/WW are not provided, they are read from the DICOM header. Falls back to the full dynamic range if unavailable.

Parameters:
  • window_center – Explicit window center (None = read from header).

  • window_width – Explicit window width (None = read from header).

  • device – Torch device.

__init__(window_center=None, window_width=None, device=None)[source]
Parameters:
  • window_center (float | None)

  • window_width (float | None)

  • device (str)

apply(image, output)[source]

Apply DICOM windowing to the image.

Parameters:
  • image (Image) – Input image (ideally DicomImage with dicom_data).

  • output (Image) – Output Image — pixel_data will be in [0, 255].

Returns:

The output Image.

Return type:

Image

GrailWindowAlgorithm

class medical_image.algorithms.dicom_window.GrailWindowAlgorithm[source]

Bases: Algorithm

GRAIL automatic intensity windowing algorithm.

Finds optimal lower (a) and upper (b) intensity bounds by maximising a Gabor-filtered mutual information metric between the 12-bit original and 8-bit windowed representations, then applies linear intensity windowing IW(i, a, b) → [0, 255].

After apply(), the optimal bounds are available as self.grail_a and self.grail_b.

Reference:

Albiol, Corbi & Albiol (2017), Medical Physics 44(4).

Parameters:
  • n_scales – Number of Gabor frequency scales (default 3).

  • n_orientations – Number of Gabor orientations (default 6).

  • delta – Initial search grid spacing (default 300).

  • k_max – Maximum optimisation iterations (default 3).

  • device – Torch device.

__init__(n_scales=3, n_orientations=6, delta=300, k_max=3, device=None)[source]
Parameters:
apply(image, output)[source]

Apply GRAIL windowing to the image.

Parameters:
  • image (Image) – Input 12-bit mammogram image.

  • output (Image) – Output Image — pixel_data will be in [0, 255].

Returns:

The output Image. self.grail_a and self.grail_b are set.

Return type:

Image

BitDepthNormAlgorithm

class medical_image.algorithms.bit_depth_norm.BitDepthNormAlgorithm[source]

Bases: Algorithm

Bit depth normalization algorithm for DICOM images.

Detects bit depth automatically from the DICOM header (BitsStored) and normalizes pixel values from [0, 2^bits - 1] to [0, target_max].

Parameters:
  • bits_stored – Explicit bit depth override. If None, read from the DICOM header or inferred from the pixel range.

  • target_max – Upper bound of the output range (default 255.0).

  • device – Torch device.

__init__(bits_stored=None, target_max=255.0, device=None)[source]
Parameters:
  • bits_stored (int | None)

  • target_max (float)

  • device (str)

apply(image, output)[source]

Normalize pixel values to the target range.

Parameters:
  • image (Image) – Input image (ideally DicomImage with dicom_data).

  • output (Image) – Output Image — pixel_data in [0, target_max].

Returns:

The output Image.

Return type:

Image

SbrgAlgorithm

class medical_image.algorithms.sbrg.SbrgAlgorithm[source]

Bases: Algorithm

Seed-Based Region Growing (SBRG) microcalcification segmentation.

Two-stage algorithm: seed-based region growing followed by boundary segmentation using mathematical morphology.

References

Malek, R. et al. (2010). “Region and Boundary Segmentation of Microcalcifications using Seed-Based Region Growing and Mathematical Morphology.”

__init__(device=None)[source]
apply(image, output)[source]

Apply the defined operations to the input image.

Parameters:
  • image (Image) – The input image.

  • output (Image) – The output image to store results.

Returns:

The output image after applying the operations.

Return type:

Image

DeepSegmentationAlgorithm

class medical_image.algorithms.deep_segmentation.DeepSegmentationAlgorithm[source]

Bases: Algorithm

Run a trained segmentation model as a framework Algorithm.

After apply(), the following attributes are populated:

  • probability_map — (H, W) float tensor in [0, 1].

  • lesion_count — number of detected lesions after filtering.

The output image receives:

  • pixel_data — (H, W) binary mask (0.0 / 1.0).

  • annotations — one Annotation per detected lesion (POLYGON contour + metadata with confidence, area, bbox).

Construction

Pass either checkpoint_path to load from a saved checkpoint (requires segmentation_models_pytorch), or model to supply any nn.Module directly.

param checkpoint_path:

Path to a .pt checkpoint (must contain model_state_dict and optionally config).

param model:

A pre-built nn.Module (mutually exclusive with checkpoint_path).

param use_clahe:

Whether to apply CLAHE before inference. When loading from checkpoint this is read from config.preprocessing.clahe.

param patch_size:

Sliding-window patch size for inference.

param stride:

Stride between patches (default: patch_size // 2).

param threshold:

Probability threshold for binarisation.

param min_lesion_area:

Minimum connected-component area (pixels) to keep.

param device:

"cuda" or "cpu" (auto-detected if None).

param precision:

Mixed-precision mode.

__init__(checkpoint_path=None, model=None, use_clahe=False, patch_size=512, stride=None, threshold=0.5, min_lesion_area=4, device=None, precision=Precision.FULL)[source]
Parameters:
classmethod list_available_models(server_url=None)[source]

Query the model server and return metadata for each available model.

Returns a list of dicts with keys: name, architecture, loss, patch_size, dataset, uses_clahe, url.

Parameters:

server_url (str)

Return type:

list[dict]

classmethod from_pretrained(model_name, server_url=None, cache_dir=None, device=None, precision=Precision.FULL, force_download=False)[source]

Download a pretrained model from the server and return a ready-to-use algorithm.

Parameters:
Return type:

DeepSegmentationAlgorithm

property model_info: dict | None

Return metadata about the loaded model, or None if name unknown.

apply(image, output)[source]

Apply the defined operations to the input image.

Parameters:
  • image (Image) – The input image.

  • output (Image) – The output image to store results.

Returns:

The output image after applying the operations.

Return type:

Image