Note

This page is a reference documentation. It only explains the function signature, and not how to use it. Please refer to the user guide for the big picture.

nilearn.masking.compute_background_mask

nilearn.masking.compute_background_mask(data_imgs, border_size=2, connected=False, opening=False, target_affine=None, target_shape=None, memory=None, verbose=0)[source]

Compute a brain mask for the images by guessing the value of the background from the border of the image.

Parameters:
data_imgsNiimg-like object

See Input and output: neuroimaging data representation. Images used to compute the mask. 3D and 4D images are accepted.

Note

If a 3D image is given, we suggest to use the mean image.

border_sizeint, optional

The size, in voxel of the border used on the side of the image to determine the value of the background. default=2.

connectedbool, optional

If connected is True, only the largest connect component is kept. default=False.

openingbool or int, optional

This parameter determines whether a morphological opening is performed, to keep only large structures. This step is useful to remove parts of the skull that might have been included. opening can be:

Note

Turning off opening (opening=False) will also prevent any smoothing applied to the image during the mask computation.

default=False.

target_affine3x3 or a 4x4 array-like, or None, default=None

If specified, the image is resampled corresponding to this new affine.

Note

This parameter is passed to nilearn.image.resample_img.

target_shapetuple or list or None, default=None

If specified, the image will be resized to match this new shape. len(target_shape) must be equal to 3.

Note

If target_shape is specified, a target_affine of shape (4, 4) must also be given.

Note

This parameter is passed to nilearn.image.resample_img.

memoryNone, instance of joblib.Memory, str, or pathlib.Path, default=None

Used to cache the masking process. By default, no caching is done. If a str is given, it is the path to the caching directory.

verbosebool or int, default=0

Verbosity level (0 or False means no message).

Returns:
masknibabel.nifti1.Nifti1Image

The brain mask (3D image).

Examples

>>> import numpy as np
>>> from nibabel import Nifti1Image
>>> from nilearn.masking import compute_background_mask
>>>
>>> data = np.random.default_rng(42).random((2,3,4))
>>>
>>> # Set background to zero.
>>> data[0:3,0:2,0:3] = 0
>>> data.round(decimals=3)
array([[[0.   , 0.   , 0.   , 0.697],
        [0.   , 0.   , 0.   , 0.786],
        [0.128, 0.45 , 0.371, 0.927]],
       [[0.   , 0.   , 0.   , 0.227],
        [0.   , 0.   , 0.   , 0.632],
        [0.758, 0.355, 0.971, 0.893]]])
>>>
>>> img = Nifti1Image(data, affine=np.eye(4))
>>>
>>> background_mask = compute_background_mask(img)
>>>
>>> background_mask.get_fdata()
array([[[0., 0., 0., 1.],
        [0., 0., 0., 1.],
        [1., 1., 1., 1.]],
       [[0., 0., 0., 1.],
        [0., 0., 0., 1.],
        [1., 1., 1., 1.]]])