Is it possible to change the dimentations of 3D MRI?

Hi neurosStars :slight_smile:

I have MRIs with shapes (170,256,256) and I need to change the shape of the MRIs to (256,256 ,256) Is this possible with python?
I need to do this step to use a patchify package to break the volumes into smaller patches. We will break it into patches of 64x64x64 for training.

You can use nibabel.processing.conform:

This also has a command-line interface nib-conform that is accessible if you pip install nibabel.

I got this error while trying to reshape the image.

import nibabel
from nibabel import processing

img = img.get_fdata()
img =img.squeeze()
out = processing.conform(img, out_shape=(256, 256, 256))

AttributeError Traceback (most recent call last)
Input In [9], in <cell line: 3>()
1 import nibabel
2 from nibabel import processing
----> 3 out = processing.conform(img, out_shape=(256, 256, 256))

File ~\anaconda3\lib\site-packages\nibabel\processing.py:376, in conform(from_img, out_shape, voxel_size, order, cval, orientation, out_class)
373 elif len(voxel_size) != required_ndim:
374 raise ValueError(f"voxel_size must have {required_ndim} values")
→ 376 start_ornt = io_orientation(from_img.affine)
377 end_ornt = axcodes2ornt(orientation)
378 transform = ornt_transform(start_ornt, end_ornt)

AttributeError: 'numpy.ndarray' object has no attribute 'affine'

In the documentation, it says that from_img is an

Object having attributes dataobj, affine, header and shape. If out_class is not None, img.__class__ should be able to construct an image from data, affine and header.

Typically, this will be a SpatialImage. Calling img.get_fdata() gets you a numpy array. Instead, just pass img and you will get a new image out.

i need to call img.get_fdata() so I can squeeze the image.
the image in shape (170,256,256,1). I need to squeeze it to (170,256,256).
when i tried to pass it directly without squeezing,it produce this error.

ValueError: Only 3D images are supported.

You could use nibabel.funcs.squeeze_image.

1 Like

Thanks so much, effigies
all clear now