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.image.crop_img¶
- nilearn.image.crop_img(img, rtol=1e-08, copy=True, pad=True, return_offset=False, copy_header=True)[source]¶
Crops an image as much as possible.
Will crop img, removing as many zero entries as possible without touching non-zero entries. Will leave one voxel of zero padding around the obtained non-zero area in order to avoid sampling issues later on.
- Parameters:
- imgNiimg-like object
Image to be cropped (see Input and output: neuroimaging data representation for a detailed description of the valid input types).
- rtol
float, default=1e-08 relative tolerance (with respect to maximal absolute value of the image), under which values are considered negligible and thus croppable.
- copy
bool, default=True Specifies whether cropped data is copied or not.
- pad
bool, default=True Toggles adding 1-voxel of 0s around the border.
- return_offset
bool, default=False Specifies whether to return the voxels from the original image that are kept in the output.
- copy_header
bool, default=True Indicated if the header of the reference image should be used to create the new image. Ignored for
SurfaceImage.Added in Nilearn 0.11.0.
- Returns:
- cropped_imNiimg-like object
Cropped version of the input image If the specified image is empty, the original image will be returned.
- offsettuple of
slice Returned if
return_offset=True. Represents the voxels from the original image kept in the cropped volume. For example:[ slice(dim1_first_voxel, dim1_last_voxel - 1, None), slice(dim2_first_voxel, dim2_last_voxel - 1, None), ..., slice(dimN_first_voxel, dimN_last_voxel - 1, None), ]
Examples
>>> import numpy as np >>> from nibabel import Nifti1Image >>> >>> affine = np.diag((4, 3, 2, 1)) >>> data = np.zeros((5, 6, 7)) >>> data[2:4, 1:5, 3:6] = 1 >>> data[1, 1:5, 3:6] = 0.49 >>> >>> img = Nifti1Image(data, affine=affine) >>> img.shape (5, 6, 7) >>> >>> cropped_img, offset = crop_img(img, return_offset=True) >>> >>> cropped_img.shape (5, 6, 5) >>> offset (slice(0, 5, None), slice(0, 6, None), slice(2, 7, None))