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.

clean_img

nilearn.image.clean_img(imgs, runs=None, detrend=True, standardize='zscore_sample', confounds=None, low_pass=None, high_pass=None, t_r=None, ensure_finite=False, mask_img=None, **kwargs)[source]

Improve SNR on masked fMRI signals.

This function can do several things on the input signals, in the following order:

  • detrend

  • low- and high-pass filter

  • remove confounds

  • standardize

Low-pass filtering improves specificity.

High-pass filtering should be kept small, to keep some sensitivity.

Filtering is only meaningful on evenly-sampled signals.

According to Lindquist et al. (2018), removal of confounds will be done orthogonally to temporal filters (low- and/or high-pass filters), if both are specified.

Added in Nilearn 0.2.5.

Parameters:
imgs4D image Niimg-like object or 2D SurfaceImage

The signals in the last dimension are filtered (see Input and output: neuroimaging data representation for a detailed description of the valid input types).

runsnumpy.ndarray, default=``None``

Add a run level to the cleaning process. Each run will be cleaned independently. Must be a 1D array of n_samples elements.

Warning

‘runs’ replaces ‘sessions’ after release 0.10.0. Using ‘session’ will result in an error after release 0.10.0.

detrendbool, default=True

If detrending should be applied on timeseries (before confound removal).

standardizeany of: ‘zscore_sample’, ‘psc’ or None; default=zscore_sample

Strategy to standardize the signal:

  • 'zscore_sample': The signal is z-scored. Timeseries are shifted to zero mean and scaled to unit variance. Uses sample std.

  • 'psc': Timeseries are shifted to zero mean value and scaled to percent signal change (as compared to original mean signal).

confoundsnumpy.ndarray, str, pathlib.Path, pandas.DataFrame, None, or list or tuple of numpy.ndarray, str, pathlib.Path, pandas.DataFrame, default=None

This parameter is passed to nilearn.signal.clean. Please see the related documentation for details.

Array must have shape must be (instant number, confound number), or just (instant number,).

If a or pathlib.Path str is provided, it is assumed to be the name of a csv file containing signals as columns, with an optional one-line header.

If a list is provided, all confounds are removed from the input signal, as if all were in the same array.

For dataframes, each column corresponds to a confound variable to be included in the regression model of the respective image. The number of rows must match the number of volumes in the respective image.

low_passfloat or int or None, default=None

Low cutoff frequency in Hertz. If specified, signals above this frequency will be filtered out. If None, no low-pass filtering will be performed.

high_passfloat or int or None, default=None

High cutoff frequency in Hertz. If specified, signals below this frequency will be filtered out.

t_rfloat, int or None, default=None

Repetition time, in second (sampling period). Set to None if not specified. Mandatory if used together with low_pass or high_pass.

ensure_finitebool, default=False

If True, the non-finite values (NaNs and infs) found in the images will be replaced by zeros.

mask_imgNiimg-like object or SurfaceImage, default=None

If provided, signal is only cleaned from voxels inside the mask. If mask is provided, it should have same shape and affine as imgs. If not provided, all voxels / verrices are used. See Input and output: neuroimaging data representation.

kwargsdict

Keyword arguments to be passed to functions called within this function. Kwargs prefixed with 'clean__' will be passed to clean. Within clean, kwargs prefixed with 'butterworth__' will be passed to the Butterworth filter (i.e., clean__butterworth__).

Returns:
Niimg-like object or SurfaceImage

Input images, cleaned. Same shape as imgs.

Notes

Confounds removal is based on a projection on the orthogonal of the signal space from Friston et al.[1].

Orthogonalization between temporal filters and confound removal is based on suggestions in Lindquist et al.[2].

References

Examples

>>> import numpy as np
>>> from nibabel import Nifti1Image
>>>
>>> from nilearn.image import clean_img
>>>
>>> # Create a nifti image where each voxel
>>> # contains a noisy sine wave with an extra linear trend.
>>> t = np.linspace(1, 30, 100)
>>> signal = np.sin(t) * 2 + t - 10
>>> signal += np.random.default_rng(42).normal(size=t.shape)
>>> raw_data = np.broadcast_to(signal, (2, 2, 2, 100))
>>> raw_img = Nifti1Image(raw_data, affine=np.eye(4))
>>>
>>> # Clean the image with a low pass filter.
>>> cleaned_img = clean_img(raw_img,
...                         low_pass=0.2,
...                         t_r = 1,
...                         standardize=None)
>>>
>>> # Plot the results
>>> from matplotlib import pyplot as plt
>>>
>>> cleaned_data = cleaned_img.get_fdata()
>>> fig = plt.plot(t, raw_data[1, 1, 1], color="red")
>>> fig = plt.plot(t, cleaned_data[1, 1, 1], color="green")
>>> leg = plt.legend(["raw", "cleaned"])
>>> plt.show()
../../_images/nilearn-image-clean_img-1.png

Examples using nilearn.image.clean_img

Predicted time series and residuals

Predicted time series and residuals