[Neuroimaging] How to fix the rotation change caused by resample_to_output()?

Christopher Markiewicz markiewicz at stanford.edu
Wed Jul 13 10:26:04 EDT 2022

I think the problem here is that you have a source image with a bad affine. Simply plotting the middle slice shows a head with the nose pointing directly at one of the edges of the image. However, your affine shows a 2.4 radian rotation around the z axis. When nibabel attempts to reslice to a [[1, 0, 0, tx], [0, 1, 0, ty], [0, 0, 1, tz], [0, 0, 0, 1]] affine, it assumes the source affine correct and creates a data array large enough to contain the bounding box of the original image. The two images are still in alignment and can be viewed on top of each other.

That said, you can write something that will keep the original rotations and only update the zooms like so:

# Need to calculate a shape. Since we're going to isotropic 1mm, it's just the FoV.
new_shape = np.uint8(np.array(img_nii.shape) * np.array(img_nii.header.get_zooms()))
new_affine = nib.affines.rescale_affine(img_nii.affine, img_nii.shape, zooms=(1, 1, 1), new_shape=new_shape)
img_resampled_nii = nib.processing.resample_from_to(img, (tuple(new_shape), new_aff))


From: Neuroimaging <neuroimaging-bounces+markiewicz=stanford.edu at python.org> on behalf of Melike Ilteralp <milteralp at gmail.com>
Sent: Wednesday, July 13, 2022 00:14
To: neuroimaging at python.org <neuroimaging at python.org>
Subject: [Neuroimaging] How to fix the rotation change caused by resample_to_output()?

Hi all, I am working on a dataset with different voxel sizes, so I need to resample the voxel sizes to (1, 1, 1). I found nibabel.processing.resample_to_output() which accomplishes this job. However, I realized that resampling changes the rotation of some images. Here<https://drive.google.com/file/d/1TPC7Go3f9TzTWNZxm8j7qi72_u-rWxGx/view?usp=sharing> is a slice from an image that rotates when resampled and its resampled version<https://drive.google.com/file/d/1Jwiv_W1pz1SLP5dmrumjGeF3tVG8xkam/view?usp=sharing>. Is there any way to make the rotation of the resampled image the same as the original image?

Here is what I tried,

import nibabel as nib
from nibabel.processing import resample_to_output

img_nii = nib.load('original.nii.gz')
img_resampled_nii = resample_to_output(img_nii, voxel_sizes=(1, 1, 1))
nib.save(img_resampled_nii, 'resampled.nii.gz')

You can download `original.nii.gz` from here<https://drive.google.com/drive/folders/1-5phtVGQy5fq1W76MtMPlw0SDGa3AABc?usp=sharing>,

Thank you for your support,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/neuroimaging/attachments/20220713/50fe82db/attachment.html>

More information about the Neuroimaging mailing list