Downsample a deforamtion vector field in infti format using nibabel

I have a deformation vector field with dimension (512, 512, 105, 1, 3) in nifti format.

I want to downsample this to something like (128, 128, 105, 1, 3). How can I achive that using nibabel ? If possible can someone please elaborate this with an example code.

Have you had a chance to look at the documentation for the nibabel.processing module? Specifically, the function conform seems to get at your needs

import numpy as np
import nibabel as nb
from nibabel import processing
from nibabel import funcs

# make sample image
src_data = np.random.normal(size = (512, 512, 105, 1, 3))
src = nb.Nifti1Image(src_data, affine=np.eye(4))
src.shape
# (512, 512, 105, 1, 3)

# processing.conform only works on 3D images, so using this tool
# requires operating on individual slices of the data
resampled = []
for slice in range(src.shape[-1]):
    sliced = src.slicer[:, :, :, 0, slice]
    resampled.append(processing.conform(sliced, out_shape=(128, 128, 105)))

concatenated = funcs.concat_images(resampled)
final = nb.Nifti1Image(np.expand_dims(np.asarray(concatenated.dataobj), axis=3), affine=concatenated.affine)
final.shape
# (128, 128, 105, 1, 3)

Iā€™d recommend viewing these the result in something like fsleyes to check that it matches your expectations

1 Like