Skip to content

nltools.mask

Building masks and moving values between masks and brain images.

Utilities for creating and manipulating brain masks.

Functions:

Name Description
create_sphere

Generate binary spheres in the space of a brain mask.

expand_mask

Expand an integer-labeled mask into separate binary masks.

collapse_mask

Collapse separate masks into one integer-labeled mask.

roi_to_brain

Populate an expanded binary ROI mask with a vector or matrix of per-ROI values.

roi_to_brain_from_atlas

Paint per-parcel values onto voxel space using a labeled atlas.

Functions:

create_sphere

create_sphere(coordinates, radius=5, mask=None)

Generate binary spheres in the space of a brain mask.

Spheres are drawn with nilearn.maskers.NiftiSpheresMasker, so centers are world (MNI) millimeter coordinates and the radius is in millimeters — the same convention as nilearn's SearchLight and NiftiSpheresMasker. The result is resolution-independent: the same request covers the same physical volume on a 1 mm, 2 mm, or 3 mm grid, up to voxel quantization.

Parameters:

Name Type Description Default
coordinates list

Sphere center [x, y, z] in world (MNI) millimeters, or one center per sphere [[x1, y1, z1], ...].

required
radius int | float | list

Radius of the sphere(s) in millimeters. A scalar applies to every center; a list gives one radius per center.

5
mask Nifti1Image | str

Image (or path) defining the brain space. Defaults to the package brain-space mask.

None

Returns:

Type Description
Nifti1Image

A binary image with the requested spheres in mask space.

Raises:

Type Description
ValueError

If mask is neither a nibabel image nor a readable file path, if the radius list length does not match the coordinate list length, or if a requested sphere contains no in-mask voxel.

Examples:

from nltools.mask import create_sphere

# A 10 mm sphere centered on an MNI coordinate
roi = create_sphere([12, 10, -8], radius=10)

# Two spheres with different radii
rois = create_sphere([[12, 10, -8], [-12, 10, -8]], radius=[10, 6])

expand_mask

expand_mask(mask, custom_mask=None)

Expand an integer-labeled mask into separate binary masks.

Parameters:

Name Type Description Default
mask Nifti1Image | BrainData

Integer-labeled mask.

required
custom_mask Nifti1Image | str

Brain mask (or path) used when converting a nibabel mask to BrainData.

None

Returns:

Type Description
BrainData

One binary mask per unique non-zero label.

collapse_mask

collapse_mask(mask, auto_label=True, custom_mask=None)

Collapse separate masks into one integer-labeled mask.

Overlapping areas are ignored.

Parameters:

Name Type Description Default
mask Nifti1Image | BrainData

Two or more separate masks stacked along the first axis.

required
auto_label bool

If True (default), label the collapsed regions with sequential integers (1, 2, 3, …) in mask order. If False, keep each mask's own values as its label.

True
custom_mask Nifti1Image | str

Brain mask (or path) used when converting a nibabel mask to BrainData.

None

Returns:

Type Description
BrainData

A single mask whose integer values identify the source masks.

Raises:

Type Description
ValueError

If mask is neither a nibabel nor BrainData instance, or if it holds fewer than 2 masks (nothing to collapse).

roi_to_brain

roi_to_brain(data, mask_x)

Populate an expanded binary ROI mask with a vector or matrix of per-ROI values.

Accepts lists, numpy arrays, polars DataFrame/Series, or pandas DataFrame/Series. Internally coerces to a numpy array and operates on it — 1-D input produces a single BrainData image; 2-D input (ROIs by observations) produces a stack of BrainData images, one per observation.

Parameters:

Name Type Description Default
data list | ndarray | DataFrame | Series | DataFrame | Series

ROI values. 1-D length must equal len(mask_x); 2-D shape must be (n_rois, n_obs) or (n_obs, n_rois).

required
mask_x BrainData

An expanded binary mask with one row per ROI.

required

Returns:

Type Description
BrainData

A BrainData instance with each ROI populated by the provided value(s).

roi_to_brain_from_atlas

roi_to_brain_from_atlas(
    values,
    atlas,
    source_mask,
    *,
    roi_labels=None,
    fill: float = nan,
)

Paint per-parcel values onto voxel space using a labeled atlas.

Sibling of roi_to_brain, but accepts a labeled atlas (one integer label per voxel), not an expanded mask with one binary row per ROI. Voxels whose atlas label is not in roi_labels (or whose label is 0) receive fill.

Parameters:

Name Type Description Default
values ndarray

Per-parcel scalars, either 1-D (n_parcels,) for a single image or 2-D (n_images, n_parcels) for a stack of images. The trailing (parcel) axis must match len(roi_labels) (or the number of unique non-zero atlas labels when roi_labels is None).

required
atlas BrainData | Nifti1Image | str | Path

Labeled image. Resampled to source_mask (nearest-neighbor) if shapes/affines differ.

required
source_mask Nifti1Image | str | Path

Image (or path) defining the output voxel grid. The returned BrainData is masked to this image.

required
roi_labels array - like

Integer atlas IDs in the same order as values. Must not contain 0. If None, defaults to np.unique of the atlas with 0 stripped (sorted ascending).

None
fill float

Value for voxels not in any provided ROI. Default np.nan.

nan

Returns:

Type Description
BrainData

Masked to source_mask, with each in-atlas voxel set to its parcel's scalar from values. Holds a single image when values is 1-D, or n_images images when values is 2-D (n_images, n_parcels).

Raises:

Type Description
ValueError

If values is neither 1-D nor 2-D, if roi_labels contains 0 (background), or if its length does not match the parcel axis of values.

Examples:

from nltools.mask import roi_to_brain_from_atlas

brain_map = roi_to_brain_from_atlas(
    values=accuracies,
    atlas=atlas_img,
    source_mask=brain_mask,
    roi_labels=[1, 2, 3],
)