Reputation: 2773
I have some 3D nifti files of dimension (50, 100, 50). I would like to flip the the y and z axes so that the dimension will be (50, 50, 100). What is the best way to go about doing this and how would I modify the associated affine with the file?
Currently, I am making the nifti file into a numpy array and swapping the axes like so
array = np.asanyarray(niiobj.dataobj)
img_after_resample_swapped_array = np.swapaxes(img_after_reample_array, 1, 2)
I'm confused as to the next step. I know I can use the function nib.Nifti1Image
to make the numpy array into a nifti object, but how would I have to modify the affine to account for the axis change?
Thank you for any help.
Upvotes: 1
Views: 1408
Reputation: 2085
If you use SimpleITK, there is a PermuteAxes function that can saw the Y and Z axes. And it will properly preserve the transformation of the image.
Here's an example of how to do it:
import SimpleITK as sitk
img = sitk.ReadImage("tetra.nii.gz")
print (img.GetDirection())
img2 = sitk.PermuteAxes(img, [0,2,1])
print (img2.GetDirection())
sitk.WriteImage(img2, "permuted.nii.gz")
And here's the 3x3 direction matrix output:
(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0)
The input image has the identity matrix for the direction, and for the permuted matrix the Y and Z rows are swapped.
Here is the documentation for the PermuteAxesImageFilter and the PermuteAxes function:
https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1PermuteAxesImageFilter.html https://simpleitk.org/doxygen/latest/html/namespaceitk_1_1simple.html#a892cc754413ba3b60c731aac05dddc65
Upvotes: 0