How to apply brain mask and save file to disk?

I would like to apply a brain mask to input Nifti file and save the result to disk.
Here is my code
mask_file = ‘brain_mask.nii.gz’
func_file = ‘patient1.nii.gz’

masker = NiftiMasker(mask_img=mask_file)

func_data = masker.fit_transform(func_file)

new_img_like(func_file, func_data).to_filename('masked_file.nii.gz')

but it throw exception HeaderDataError: shape (1, 844248) does not fit in dim datatype

the output of the masker is a numpy array of all the in-mask voxels. to save that, use for example numpy.save. you can transform the masked data to a nifti image containing this data inside the mask and 0 outside by using the masker’s inverse_transform method

1 Like