pythonarraysimagereshape

How can I reshape a 3D nii gz image array to a 2D?


I have a lot of nii.gz images that I need to reshape from 3D to 2D, I'm trying to use the following code but it's not working due to the nii.gz extension:

import nibabel as nib
img = nib.load('teste01converted.nii.gz')
img.shape
newimg = img.reshape(332,360*360)

Can anyone help me?

Here's an exemple of the kind of images I'm working with: https://drive.google.com/drive/folders/1681T99hp6qZRUgx1Ej_h1hwFv1g_LJo4?usp=sharing


Solution

  • According to the NiBabel Getting Started guide, you can convert a NiBabel object to a numpy array, which then lets you use reshape:

    This information is available without the need to load anything of the main image data into the memory. Of course there is also access to the image data as a NumPy array

    >>> data = img.get_fdata()
    >>> data.shape
    (128, 96, 24, 2)
    >>> type(data)
    <... 'numpy.ndarray'>
    

    So you can adapt your code like so:

    import nibabel as nib
    img = nib.load('teste01converted.nii.gz')
    newimg = img.get_fdata().reshape(332,360*360)
    

    When I do this, I get a numpy array with this shape:

    (332, 129600)
    

    By the way, I don't know anything about neuroimaging, so I don't know if the transformation you're requesting is meaningful.