[Neuroimaging] [Nibabel] up/downsample image in Python

Matthew Brett matthew.brett at gmail.com
Sat Aug 19 06:21:25 EDT 2017

Hi Michael,

On Fri, Aug 18, 2017 at 9:52 PM, Michael Waskom <mwaskom at nyu.edu> wrote:
> Hi Matthew/Chris/others,
> Building on my previous question, I would also like to implement a
> pure-python downsampling of my images. I have done:
> import nibabel as nib
> from scipy import ndimage
> img = nib.load("brain.nii")
> data = img.get_data()
> lowres_data = ndimage.zoom(data, .5)
> zoom_xfm = np.eye(4)
> zoom_xfm[:3, :3] /= .5
> lowres_affine = img.affine.dot(zoom_xfm)
> lowres_img = nib.Nifti1Image(lowres_data, lowres_affine, img.header)
> lowres_img.to_fileame("lowres_brain.nii")
> This is very close, but when I view the resulting image in Freeview (my
> downsampled image is also slightly stretched relative to the anatomical).
> I can also compare to the result from mri_convert, i.e. mri_convert
> brain.nii -vs 2 2 2 lowres_brain.nii. The resulting image is not stretched
> relative to the hires brain, so it's not an artifact on Freeview's side. The
> images also don't have an identical affine (it is off by 0.5 in the third
> row of the final column.
> What am I missing about how to alter to affine of a downsampled image?
> Alternative, is ndimage.zoom not the right Python function to use here?

Did you find nibabel.processing.resample_from_to ?   Not surprising if
you didn't - it's not well documented yet.

The nipy method is very nice, we really should port it across to
nibabel.  It just adapts the affine to the numpy slicing you've done:




More information about the Neuroimaging mailing list