Skip to content

API reference

import intensity_normalization as inorm

numpy arrays in → numpy out; nibabel images in → nibabel images out (affine/header preserved). float64 inputs stay float64; other dtypes become float32. All stochastic steps take seed= (default 0, deterministic).

Individual methods

Plain functions of one image — parameters are estimated from the image itself, so there is nothing to fit or save.

Z-score normalization: standardize foreground intensities to zero mean, unit variance.

zscore_array(data, foreground, *, norm_value=1.0)

Z-score normalize an intensity array by its foreground intensities.

Subtracts the foreground mean and divides by the foreground standard deviation, then scales to norm_value. Works for any anatomy/modality (not brain-specific).

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask (see :func:intensity_normalization._image.resolve_foreground).

required
norm_value float

multiply the standardized array by this value.

1.0

Returns:

Type Description
IntensityArray

The normalized intensity array.

zscore(image, mask=None, *, norm_value=1.0)

Z-score normalize an MR image (numpy or nibabel); see :func:zscore_array.

Parameters:

Name Type Description Default
image Image

numpy array or nibabel image; the same type is returned.

required
mask Mask | None

foreground (brain) mask. If None, the foreground is estimated as positive voxels (i.e., the image is assumed skull-stripped).

None
norm_value float

multiply the standardized image by this value.

1.0

Returns:

Type Description
Image

The normalized image, same type as image.

FCM-based normalization: scale a tissue's fuzzy mean intensity to a fixed value.

tissue_means(data, foreground_mask, *, seed=0, max_samples=200000)

Weighted tissue means (CSF, GM, WM) of an image via fuzzy c-means.

Centers are fit on a seeded subsample of the foreground; memberships are then computed for every foreground voxel, so results are statistically identical to a full fit but much faster on large images.

Returns:

Type Description
IntensityArray

(means, membership_map) where membership_map has shape

IntensityArray

(*data.shape, 3) in ascending-center order (CSF, GM, WM).

fcm_array(data, foreground, *, modality='t1', tissue='wm', membership=None, norm_value=1.0, seed=0)

Normalize an intensity array to the fuzzy c-means mean of a tissue class.

For T1-w images, three-class fuzzy c-means segments the foreground into CSF/GM/WM memberships and the array is scaled so the tissue mean equals norm_value. This is the recommended starting point for T1-w brain images.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
modality str

"t1" computes memberships from data itself. For other modalities, pass membership (from a co-registered T1-w image, e.g. via :func:intensity_normalization.tissue_membership); otherwise foreground is used as hard tissue weights.

't1'
tissue str

"csf", "gm", or "wm".

'wm'
membership IntensityArray | None

precomputed tissue membership map (same shape as data).

None
norm_value float

intensity the tissue mean is mapped to.

1.0
seed int | None

RNG seed for the FCM fit; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

fcm(image, mask=None, *, modality='t1', tissue='wm', membership=None, norm_value=1.0, seed=0)

Normalize an MR image (numpy or nibabel); see :func:fcm_array.

Parameters:

Name Type Description Default
image Image

numpy array or nibabel image; the same type is returned.

required
mask Mask | None

foreground (brain) mask. If None, estimated as positive voxels.

None
modality str

"t1" computes memberships from image itself. For other modalities, pass membership (from a co-registered T1-w image, e.g. via :func:intensity_normalization.tissue_membership) or a mask to use as hard tissue weights.

't1'
tissue str

"csf", "gm", or "wm".

'wm'
membership IntensityArray | None

precomputed tissue membership map (same shape as image).

None
norm_value float

intensity the tissue mean is mapped to.

1.0
seed int | None

RNG seed for the FCM fit; None is nondeterministic.

0

Returns:

Type Description
Image

The normalized image, same type as image.

KDE-based normalization: scale the tissue mode of the smoothed histogram to a fixed value.

kde_array(data, foreground, *, peak, norm_value=1.0, seed=0)

Normalize an intensity array by the tissue mode of its smoothed histogram.

Fits a kernel density estimate to the foreground intensities, finds the mode of the tissue of interest (white matter by default for T1-w), and scales the array so that mode equals norm_value.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
peak Peak

which histogram peak carries the tissue of interest ("last", "largest", "first"); resolve modality names with :func:intensity_normalization.histogram.resolve_peak.

required
norm_value float

intensity the tissue mode is mapped to.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

kde(image, mask=None, *, modality='t1', peak=None, norm_value=1.0, seed=0)

Normalize an MR image (numpy or nibabel); see :func:kde_array.

Parameters:

Name Type Description Default
image Image

numpy array or nibabel image; the same type is returned.

required
mask Mask | None

foreground (brain) mask. If None, estimated as positive voxels.

None
modality str

one of "t1", "t2", "flair", "pd", "md", "other"; selects which histogram peak is the tissue of interest.

't1'
peak Peak | None

explicit peak override ("last", "largest", "first") for non-standard data.

None
norm_value float

intensity the tissue mode is mapped to.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
Image

The normalized image, same type as image.

WhiteStripe normalization: standardize by the normal-appearing white matter statistics.

WhiteStripeSpec dataclass

WhiteStripe parameters as data, for embedding WhiteStripe in larger workflows (e.g. RAVEL's normalization step). seed and norm_value are excluded: the embedding workflow owns those.

whitestripe_array(data, foreground, *, peak, width=0.05, width_l=None, width_u=None, norm_value=1.0, seed=0)

WhiteStripe normalization of an intensity array (Shinohara et al., 2014).

Finds the normal-appearing white matter (NAWM) as the intensities within width quantile around the white matter mode of the smoothed foreground histogram (the "white stripe"), then standardizes the array to the mean and standard deviation of that stripe, scaled by norm_value.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
peak Peak

which histogram peak anchors the stripe ("last", "largest", "first"); resolve modality names with :func:intensity_normalization.histogram.resolve_peak.

required
width float

quantile half-width of the stripe around the tissue mode.

0.05
width_l float | None

asymmetric override for the lower width.

None
width_u float | None

asymmetric override for the upper width.

None
norm_value float

multiply the standardized array by this value.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

whitestripe(image, mask=None, *, modality='t1', peak=None, width=0.05, width_l=None, width_u=None, norm_value=1.0, seed=0)

WhiteStripe normalize an MR image (numpy or nibabel); see :func:whitestripe_array.

Parameters:

Name Type Description Default
image Image

numpy array or nibabel image; the same type is returned.

required
mask Mask | None

foreground (brain) mask. If None, estimated as positive voxels.

None
modality str

one of "t1", "t2", "flair", "pd", "md", "other"; selects which histogram peak anchors the stripe.

't1'
peak Peak | None

explicit peak override ("last", "largest", "first") for non-standard data.

None
width float

quantile half-width of the stripe around the tissue mode.

0.05
width_l float | None

asymmetric override for the lower width.

None
width_u float | None

asymmetric override for the upper width.

None
norm_value float

multiply the standardized image by this value.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
Image

The normalized image, same type as image.

Population methods

fit(images, masks) returns a fitted, callable, savable transform. fit_transform returns the transform and the normalized inputs.

Nyúl & Udupa piecewise-linear histogram matching normalization.

NyulTransform dataclass

Bases: FittedTransform

Piecewise-linear histogram matching learned from a set of images.

Maps each image's landmark percentiles onto the population's standard scale. Frozen and write-protected: the learned parameters cannot change after construction, so a saved transform always matches the in-memory one.

landmark_intensities(intensities)

Landmark intensities of a 1D foreground array.

fit_array(datas, foregrounds, *, landmarks=None, output_min_value=1.0, output_max_value=100.0)

Learn the standard histogram scale from a population of intensity arrays.

Streams one array at a time, keeping only per-array landmark percentiles — the dataset size never bounds memory.

Parameters:

Name Type Description Default
datas Sequence[IntensityArray]

intensity arrays, all one modality.

required
foregrounds Sequence[BinaryMask]

boolean foreground (brain) mask per array.

required
landmarks Sequence[float] | None

landmark percentiles, strictly increasing within (0, 100); defaults to the standard grid 1, 10, ..., 90, 99.

None
output_min_value float

intensity the first landmark maps to.

1.0
output_max_value float

intensity the last landmark maps to.

100.0

Returns:

Type Description
NyulTransform

A fitted :class:NyulTransform.

fit(images, masks=None, *, landmarks=None, output_min_value=1.0, output_max_value=100.0)

Learn the standard histogram scale from a population of images; see :func:fit_array.

Parameters:

Name Type Description Default
images Sequence[Image]

MR images (numpy arrays or nibabel images), all one modality.

required
masks Sequence[Mask | None] | None

optional foreground (brain) mask per image; where omitted, the foreground is estimated as positive voxels.

None
landmarks Sequence[float] | None

landmark percentiles, strictly increasing within (0, 100); defaults to the standard grid 1, 10, ..., 90, 99.

None
output_min_value float

intensity the first landmark maps to.

1.0
output_max_value float

intensity the last landmark maps to.

100.0

Returns:

Type Description
NyulTransform

A fitted :class:NyulTransform.

fit_transform(images, masks=None, **kwargs)

Fit on images and return the transform plus the normalized images.

Least-squares tissue mean normalization of a set of images.

Scales each image so its CSF/GM/WM tissue means match, in a least-squares sense, the standard tissue means learned from a reference image.

LSQTransform dataclass

Bases: FittedTransform

Least-squares scaling toward standard tissue means.

reference_membership is the reference image's CSF/GM/WM membership map (shape image.shape + (3,)), always computed during fitting — for diagnostics and tissue-map export, not for transforming new images (a new image is segmented from itself unless it is co-registered to the reference). Frozen and write-protected: the learned parameters cannot change after construction.

transform(image, mask=None, *, membership=None)

Apply the learned transform; membership overrides the FCM fit (non-T1-w data).

transform_array(data, foreground, *, membership=None)

Apply the learned least-squares scale to an intensity array.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
membership IntensityArray | None

precomputed tissue membership map (same shape as data) for non-T1-w images; computed from data when None.

None

fit_array(datas, foregrounds, *, norm_value=1.0, seed=0, membership=None)

Learn standard tissue means from a reference intensity array.

The first array is the reference (per the original method): its tissue means, computed after scaling its CSF mean to norm_value, become the standard that other arrays are scaled toward.

Parameters:

Name Type Description Default
datas Sequence[IntensityArray]

T1-w intensity arrays.

required
foregrounds Sequence[BinaryMask]

boolean foreground (brain) mask per array (the reference's is used).

required
norm_value float

intensity the reference CSF mean is mapped to.

1.0
seed int | None

RNG seed for the FCM tissue fit; None is nondeterministic.

0
membership IntensityArray | None

precomputed membership map of the reference (shape data.shape + (3,)) for non-T1-w references; computed from the reference itself when None.

None

Returns:

Type Description
LSQTransform

A fitted :class:LSQTransform. Its reference_membership attribute

LSQTransform

holds the reference's CSF/GM/WM membership map.

fit(images, masks=None, *, norm_value=1.0, seed=0, membership=None)

Learn standard tissue means from a reference image; see :func:fit_array.

Parameters:

Name Type Description Default
images Sequence[Image]

T1-w MR images (numpy arrays or nibabel images).

required
masks Sequence[Mask | None] | None

optional foreground (brain) mask per image.

None
norm_value float

intensity the reference CSF mean is mapped to.

1.0
seed int | None

RNG seed for the FCM tissue fit; None is nondeterministic.

0
membership IntensityArray | None

precomputed membership map of the reference image (shape image.shape + (3,)) for non-T1-w references; computed from the reference image itself when None.

None

Returns:

Type Description
LSQTransform

A fitted :class:LSQTransform. Its reference_membership attribute

LSQTransform

holds the reference image's CSF/GM/WM membership map.

fit_transform(images, masks=None, **kwargs)

Fit on the reference image and normalize all images.

RAVEL normalization (WhiteStripe, then CSF control-voxel correction).

RAVEL (Fortin et al., 2017) is a batch correction method: it removes technical variation by regressing out latent "unwanted factors" estimated from the across-image variation of CSF control voxels. There is no single-image transform — new images must be included in the batch. fit_transform is therefore the entire API; the returned :class:RavelResult holds the learned artifacts (factors, control mask) for diagnostics and reproducibility.

RavelResult dataclass

Artifacts learned by a RAVEL batch correction.

Attributes are exposed read-only for diagnostics: the unwanted factors, the CSF control-voxel mask, and the control-voxel matrix. These live in the working space — template space when register=True (the default), native space otherwise. Frozen and write-protected: the artifacts cannot change after construction, so a saved result always matches memory.

save(path)

Save the learned artifacts to path (.npz) for provenance.

load(path) classmethod

Load artifacts saved with :meth:save.

fit_transform(images, masks=None, *, register=True, membership_threshold=0.99, num_unwanted_factors=1, sparse_svd=False, quantile_to_label_csf=1.0, masks_are_csf=False, template=None, whitestripe=None, seed=0)

WhiteStripe-normalize then RAVEL-correct a set of co-registered images.

All images must have the same shape and be (at least rigidly) co-registered; good results require deformable co-registration. With register=True (default), images are deformably registered to a template (the first image unless template is given), the correction is computed in template space, and the corrected images are warped back to native space.

Parameters:

Name Type Description Default
images Sequence[Image]

MR images (numpy arrays or nibabel images), all one modality.

required
masks Sequence[Mask | None] | None

foreground (brain) mask per image (CSF masks if masks_are_csf).

None
register bool

deformably register to a template before finding control voxels (masks are warped along). Requires antspy. If False, images are assumed already deformably co-registered.

True
membership_threshold float

FCM CSF membership threshold for control voxels.

0.99
num_unwanted_factors int

b in the RAVEL paper.

1
sparse_svd bool

use a sparse SVD (lower memory) for the factor estimation.

False
quantile_to_label_csf float

fraction of images in which a voxel must be CSF to be a control voxel (1.0 = strict intersection).

1.0
masks_are_csf bool

masks are boolean CSF masks, not brain masks.

False
template Image | None

registration target; defaults to the first image.

None
whitestripe WhiteStripeSpec | None

WhiteStripe parameters for the normalization step (a :class:WhiteStripeSpec); defaults used when None.

None
seed int | None

RNG seed for the FCM tissue fits; None is nondeterministic.

0

Returns:

Type Description
RavelResult

(result, normalized): the learned :class:RavelResult artifacts

list[Image]

and the normalized images (same types as the inputs).

fit_transform_array(ws_images, masks=None, *, membership_threshold=0.99, num_unwanted_factors=1, sparse_svd=False, quantile_to_label_csf=1.0, masks_are_csf=False, seed=0)

RAVEL-correct a set of WhiteStripe-normalized, co-registered intensity arrays.

This is the registration-free core: every array must already be in one common (working) space with voxel-wise correspondence.

Parameters:

Name Type Description Default
ws_images Sequence[IntensityArray]

WhiteStripe-normalized intensity arrays, all the same shape.

required
masks Sequence[BinaryMask | None] | None

foreground (brain) mask array per array (CSF masks if masks_are_csf).

None
membership_threshold float

FCM CSF membership threshold for control voxels.

0.99
num_unwanted_factors int

b in the RAVEL paper.

1
sparse_svd bool

use a sparse SVD (lower memory) for the factor estimation.

False
quantile_to_label_csf float

fraction of arrays in which a voxel must be CSF to be a control voxel (1.0 = strict intersection).

1.0
masks_are_csf bool

masks are boolean CSF masks, not brain masks.

False
seed int | None

RNG seed for the FCM tissue fits; None is nondeterministic.

0

Returns:

Type Description
RavelResult

(result, corrected): the learned :class:RavelResult artifacts

list[IntensityArray]

and the corrected intensity arrays, all in the working space.

Array-level methods

Every wrapper above delegates to a pure-numpy core named after it plus _array. Cores take a required boolean foreground mask and resolved options — no nibabel, no mask estimation, no modality strings. Use them when your pipeline already holds arrays.

Z-score normalize an intensity array by its foreground intensities.

Subtracts the foreground mean and divides by the foreground standard deviation, then scales to norm_value. Works for any anatomy/modality (not brain-specific).

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask (see :func:intensity_normalization._image.resolve_foreground).

required
norm_value float

multiply the standardized array by this value.

1.0

Returns:

Type Description
IntensityArray

The normalized intensity array.

Normalize an intensity array to the fuzzy c-means mean of a tissue class.

For T1-w images, three-class fuzzy c-means segments the foreground into CSF/GM/WM memberships and the array is scaled so the tissue mean equals norm_value. This is the recommended starting point for T1-w brain images.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
modality str

"t1" computes memberships from data itself. For other modalities, pass membership (from a co-registered T1-w image, e.g. via :func:intensity_normalization.tissue_membership); otherwise foreground is used as hard tissue weights.

't1'
tissue str

"csf", "gm", or "wm".

'wm'
membership IntensityArray | None

precomputed tissue membership map (same shape as data).

None
norm_value float

intensity the tissue mean is mapped to.

1.0
seed int | None

RNG seed for the FCM fit; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

Normalize an intensity array by the tissue mode of its smoothed histogram.

Fits a kernel density estimate to the foreground intensities, finds the mode of the tissue of interest (white matter by default for T1-w), and scales the array so that mode equals norm_value.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
peak Peak

which histogram peak carries the tissue of interest ("last", "largest", "first"); resolve modality names with :func:intensity_normalization.histogram.resolve_peak.

required
norm_value float

intensity the tissue mode is mapped to.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

WhiteStripe normalization of an intensity array (Shinohara et al., 2014).

Finds the normal-appearing white matter (NAWM) as the intensities within width quantile around the white matter mode of the smoothed foreground histogram (the "white stripe"), then standardizes the array to the mean and standard deviation of that stripe, scaled by norm_value.

Parameters:

Name Type Description Default
data IntensityArray

intensity array.

required
foreground BinaryMask

boolean foreground (brain) mask.

required
peak Peak

which histogram peak anchors the stripe ("last", "largest", "first"); resolve modality names with :func:intensity_normalization.histogram.resolve_peak.

required
width float

quantile half-width of the stripe around the tissue mode.

0.05
width_l float | None

asymmetric override for the lower width.

None
width_u float | None

asymmetric override for the upper width.

None
norm_value float

multiply the standardized array by this value.

1.0
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
IntensityArray

The normalized intensity array.

Learn the standard histogram scale from a population of intensity arrays.

Streams one array at a time, keeping only per-array landmark percentiles — the dataset size never bounds memory.

Parameters:

Name Type Description Default
datas Sequence[IntensityArray]

intensity arrays, all one modality.

required
foregrounds Sequence[BinaryMask]

boolean foreground (brain) mask per array.

required
landmarks Sequence[float] | None

landmark percentiles, strictly increasing within (0, 100); defaults to the standard grid 1, 10, ..., 90, 99.

None
output_min_value float

intensity the first landmark maps to.

1.0
output_max_value float

intensity the last landmark maps to.

100.0

Returns:

Type Description
NyulTransform

A fitted :class:NyulTransform.

Learn standard tissue means from a reference intensity array.

The first array is the reference (per the original method): its tissue means, computed after scaling its CSF mean to norm_value, become the standard that other arrays are scaled toward.

Parameters:

Name Type Description Default
datas Sequence[IntensityArray]

T1-w intensity arrays.

required
foregrounds Sequence[BinaryMask]

boolean foreground (brain) mask per array (the reference's is used).

required
norm_value float

intensity the reference CSF mean is mapped to.

1.0
seed int | None

RNG seed for the FCM tissue fit; None is nondeterministic.

0
membership IntensityArray | None

precomputed membership map of the reference (shape data.shape + (3,)) for non-T1-w references; computed from the reference itself when None.

None

Returns:

Type Description
LSQTransform

A fitted :class:LSQTransform. Its reference_membership attribute

LSQTransform

holds the reference's CSF/GM/WM membership map.

RAVEL-correct a set of WhiteStripe-normalized, co-registered intensity arrays.

This is the registration-free core: every array must already be in one common (working) space with voxel-wise correspondence.

Parameters:

Name Type Description Default
ws_images Sequence[IntensityArray]

WhiteStripe-normalized intensity arrays, all the same shape.

required
masks Sequence[BinaryMask | None] | None

foreground (brain) mask array per array (CSF masks if masks_are_csf).

None
membership_threshold float

FCM CSF membership threshold for control voxels.

0.99
num_unwanted_factors int

b in the RAVEL paper.

1
sparse_svd bool

use a sparse SVD (lower memory) for the factor estimation.

False
quantile_to_label_csf float

fraction of arrays in which a voxel must be CSF to be a control voxel (1.0 = strict intersection).

1.0
masks_are_csf bool

masks are boolean CSF masks, not brain masks.

False
seed int | None

RNG seed for the FCM tissue fits; None is nondeterministic.

0

Returns:

Type Description
RavelResult

(result, corrected): the learned :class:RavelResult artifacts

list[IntensityArray]

and the corrected intensity arrays, all in the working space.

Tools

Fuzzy c-means tissue memberships of a T1-w MR image; see :func:tissue_membership_array.

Parameters:

Name Type Description Default
image Image

T1-w numpy array or nibabel image; the same type is returned.

required
mask Mask | None

foreground (brain) mask. If None, estimated as positive voxels.

None
hard_segmentation bool

return a hard 3D label map (0 background, 1 CSF, 2 GM, 3 WM) instead of per-class membership maps.

False
seed int | None

RNG seed for the FCM fit; None is nondeterministic.

0

Returns:

Type Description
Image

A 4D membership map, image.shape + (3,) in CSF/GM/WM order

Image

(see :data:intensity_normalization.methods.fcm.TISSUES), or a 3D

Image

label map with hard_segmentation=True.

Plot smoothed foreground-intensity histograms of a set of images.

The recommended way to validate normalization: run before and after and compare. Histograms are kernel density estimates (see :mod:intensity_normalization.histogram).

Parameters:

Name Type Description Default
images Sequence[Image]

images to plot (numpy arrays or nibabel images).

required
masks Sequence[Image | None] | None

optional foreground (brain) mask per image.

None
labels Sequence[str] | None

legend labels; defaults to image 0, image 1, ...

None
title str | None

plot title.

None
log_scale bool

plot the density on a log scale (default; makes tissue peaks of MR brain images easier to compare).

True
output str | PathLike[str] | None

save the figure to this path instead of showing it.

None
seed int | None

RNG seed for the KDE subsample; None is nondeterministic.

0

Returns:

Type Description
Any

The matplotlib Figure.

Preprocess an MR image: N4 bias correction, optional resample, reorientation.

Parameters:

Name Type Description Default
image Image

numpy array or nibabel image; the same types are returned.

required
mask Image | None

foreground (brain) mask; estimated from the image if None.

None
resolution tuple[float, float, float] | None

voxel size (mm) to resample to; None skips resampling.

None
orientation str

ANTs orientation code (e.g., "RAS").

'RAS'
n4_convergence_options dict[str, Any] | None

ANTs N4 convergence dict.

None
interp_type str

resampling interpolation ("linear", "nearest_neighbor", "gaussian", "windowed_sinc", "bspline").

'linear'
second_n4_with_smoothed_mask bool

run a second N4 weighted by a smoothed mask; usually improves the correction.

True

Returns:

Type Description
tuple[Image, Image]

(preprocessed_image, foreground_mask), same types as the inputs.

Register image to template with ANTs (MNI template if None).

Parameters:

Name Type Description Default
image Image | ANTsImage

moving image; the same type is returned.

required
template Image | ANTsImage | None

fixed image. If None, uses the MNI template bundled with ANTs.

None
type_of_transform str

ANTs transform type (e.g., "Rigid", "Affine", "SyN").

'Affine'
interpolator str

interpolation for the resampled output.

'bSpline'
metric str

registration metric (e.g., "mattes", "CC").

'mattes'
initial_rigid bool

do a rigid registration first to initialize.

True
template_mask Image | ANTsImage | None

mask restricting the metric on the fixed image.

None

Returns:

Type Description
Image | ANTsImage

The registered image, same type as image.

Histogram utilities

Histogram estimation and tissue modes of MR image intensities.

Shared by the KDE, WhiteStripe, and LSQ methods, and public so users can inspect histograms when validating normalization results.

The modality -> tissue-mode policy lives here: for T1-w images white matter is the highest-intensity tissue peak ("last"); for T2-w/FLAIR the interesting tissue is the global maximum ("largest"); for PD/MD it is the lowest peak ("first"). Non-standard data can override the policy with an explicit peak.

smooth_histogram(intensities, *, max_samples=_MAX_KDE_SAMPLES, seed=0)

Kernel density estimate of the intensity distribution.

Uses a seeded subsample of at most max_samples intensities: the KDE is O(n) in the sample count per grid point and the mode is statistically unchanged, so this keeps the estimate fast on multi-million-voxel images.

Parameters:

Name Type Description Default
intensities ForegroundIntensities

1D array of (foreground) intensities.

required
max_samples int

cap on the number of samples fed to the KDE.

_MAX_KDE_SAMPLES
seed int | None

subsample RNG seed; None is nondeterministic.

0

Returns:

Type Description
tuple[IntensityArray, IntensityArray]

(grid, pdf): the intensity grid and the estimated density on it.

largest_mode(intensities, **kwargs)

Mode of the largest tissue class (global maximum of the smoothed histogram).

last_mode(intensities, *, tail_percentage=96.0, **kwargs)

Mode of the highest-intensity tissue class (last local maximum of the histogram).

The histogram above tail_percentage is removed first, so bright tails (e.g., vessels, lesions, fat) do not count as the tissue mode.

first_mode(intensities, *, tail_percentage=99.0, **kwargs)

Mode of the lowest-intensity tissue class (first local maximum of the histogram).

resolve_peak(modality, peak)

The modality -> peak policy, resolved once at the boundary.

Parameters:

Name Type Description Default
modality str

one of "t1", "t2", "flair", "pd", "md", "other".

required
peak Peak | None

explicit peak override ("last", "largest", "first") for non-standard data; derived from modality when None.

required

tissue_mode(intensities, *, peak, **kwargs)

Mode of the tissue of interest at peak.

Parameters:

Name Type Description Default
intensities ForegroundIntensities

1D array of foreground intensities.

required
peak Peak

which histogram peak carries the tissue ("last", "largest", "first"); resolve modality names with :func:resolve_peak.

required

Types

Signatures across the package use one vocabulary, importable from the root:

Name Meaning
Image an intensity array or a nibabel spatial image
Mask a float or bool array, or a nibabel image
IntensityArray float image data (numpy)
MaskArray a mask as an array (float or bool)
BinaryMask a thresholded boolean mask
ForegroundIntensities 1-D samples inside a foreground mask

Errors

Exceptions for intensity-normalization.

Runtime failures raise :class:IntensityNormalizationError with a message that says what to do about it. Bad arguments (wrong types, out-of-range values) surface as ordinary TypeError/ValueError.

IntensityNormalizationError

Bases: Exception

A normalization operation could not be completed.