Algorithms¶
Multi-step processing pipelines built on the Algorithm base class.
Algorithm (Abstract Base)¶
FebdsAlgorithm¶
- class medical_image.algorithms.FEBDS.FebdsAlgorithm[source]¶
Bases:
AlgorithmFourier 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:
Apply base enhancement filter depending on the method (
dog,log,fft).Denoise and smooth by taking the absolute value and applying a median filter.
Apply gamma correction to increase the contrast of microcalcifications.
Apply global thresholding (binarize for
fft, Otsu fordog/log).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)
TopHatAlgorithm¶
- class medical_image.algorithms.top_hat.TopHatAlgorithm[source]¶
Bases:
AlgorithmWhite 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:
Create a disk structuring element of the specified radius.
Perform morphological opening (erosion followed by dilation).
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”).
KMeansAlgorithm¶
- class medical_image.algorithms.kmeans.KMeansAlgorithm[source]¶
Bases:
AlgorithmK-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:
Flatten the input image into a 1D feature matrix.
Initialize centroids using k-means++.
Iteratively assign pixels to the nearest centroid and update centroids.
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.
FCMAlgorithm¶
- class medical_image.algorithms.fcm.FCMAlgorithm[source]¶
Bases:
AlgorithmFuzzy 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:
Flatten the input image into a 1D feature matrix.
Randomly initialize the fuzzy membership matrix.
Iteratively compute distances, update membership probabilities, and update cluster centroids.
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.
PFCMAlgorithm¶
- class medical_image.algorithms.pfcm.PFCMAlgorithm[source]¶
Bases:
AlgorithmPossibilistic 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:
Run standard FCM to warm-start cluster centroids and memberships.
Compute initial gamma values and typicality matrix T.
Iteratively update prototypes, memberships, gammas, and typicalities.
Detect MCs by thresholding the maximum typicality map (atypical pixels).
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.
BreastMaskAlgorithm¶
- class medical_image.algorithms.breast_mask.BreastMaskAlgorithm[source]¶
Bases:
AlgorithmBreast 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”).
DicomWindowAlgorithm¶
- class medical_image.algorithms.dicom_window.DicomWindowAlgorithm[source]¶
Bases:
AlgorithmSimple 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.
GrailWindowAlgorithm¶
- class medical_image.algorithms.dicom_window.GrailWindowAlgorithm[source]¶
Bases:
AlgorithmGRAIL 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 asself.grail_aandself.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.
BitDepthNormAlgorithm¶
- class medical_image.algorithms.bit_depth_norm.BitDepthNormAlgorithm[source]¶
Bases:
AlgorithmBit 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.
SbrgAlgorithm¶
- class medical_image.algorithms.sbrg.SbrgAlgorithm[source]¶
Bases:
AlgorithmSeed-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.”
DeepSegmentationAlgorithm¶
- class medical_image.algorithms.deep_segmentation.DeepSegmentationAlgorithm[source]¶
Bases:
AlgorithmRun 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
outputimage receives:pixel_data—(H, W)binary mask (0.0 / 1.0).annotations— oneAnnotationper detected lesion (POLYGONcontour + metadata with confidence, area, bbox).
Construction¶
Pass either
checkpoint_pathto load from a saved checkpoint (requiressegmentation_models_pytorch), ormodelto supply anynn.Moduledirectly.- param checkpoint_path:
Path to a
.ptcheckpoint (must containmodel_state_dictand optionallyconfig).- 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 ifNone).- 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]¶
- 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.