Swap axes of a 3D image in nilearn/numpy

1.8k views Asked by At

I am working with some neuroimaging data and my dimensions for a scan is (100, 150, 100). I am currently working with the nibabel formatted file.

Is there a nice way to swap the axes? For example, I want my image to be (100, 100, 150). I would preferable want this in the nibabel format, but if need be, I can get the image to a numpy ndarray and then do the work there as well. In this case, is there a nice way of doing this in numpy?

Thank you for the help!

2

There are 2 answers

0
Ehsan On BEST ANSWER

If you are using numpy use:

import numpy as np

arr = np.swapaxes(arr, 1, 2)

This will swap axis 1 and 2 (which are 2nd and 3rd dimension with 150 and 100 size respectively).

Example code:

arr = np.zeros((100,150,100))
arr = np.swapaxes(arr, 1, 2)
print(arr.shape)

output:

(100, 100, 150)
0
tiago On

You can use numpy.swapaxes as mentioned in Ehsan's answer, which swaps two axes. You can also use numpy.transpose, which allows you to change two or more axes, in any desired order. E.g.:

>>> import numpy as np
>>> data = np.empty((4, 5, 6))
>>> data.shape
(4, 5, 6)
>>> np.transpose(data, axes=(1, 2, 0)).shape
(5, 6, 4)