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(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.

data_imgsNiimg-like object

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


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:


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


target_affinenumpy.ndarray, default=None

If specified, the image is resampled corresponding to this new affine. target_affine can be a 3x3 or a 4x4 matrix.


This parameter is passed to nilearn.image.resample_img.

target_shapetuple or list, default=None

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


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


This parameter is passed to nilearn.image.resample_img.

memoryinstance of joblib.Memory, str, or pathlib.Path

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.

verboseint, default=0

Verbosity level (0 means no message).


The brain mask (3D image).