0

Unable to set image voxel dimensions in NiftiHeader in nibabel. How to set particular voxel dimensions for a given image?

I need to save the image with some particular voxel dimensions in nibabel.

image = nib.load('some_image')
c = np.array(image.get_fdata())
x = nib.Nifti1Image(c, image.affine)
nib.save(x, 'something.nii.gz')

How do i save the imager with some new voxel dimensions ?

BlackSpecter
  • 61
  • 2
  • 12

1 Answers1

3

You need to change the header information before saving:

image = nib.load('some_image')
header_info = image.header
print(header_info)

# change the voxel dimensions to [2,2,2]
header_info['pixdim'][1:4]  = [2,2,2]

c = np.array(image.get_fdata())

# Use the new `header_info` before writing
x = nib.Nifti1Image(c, image.affine, header_info)
nib.save(x, 'something.nii.gz')
seralouk
  • 30,938
  • 9
  • 118
  • 133
  • Can you please help me with this post? https://stackoverflow.com/questions/56698087/how-to-remove-a-modality-from-mri-image-python-nibabel – The Great Jun 21 '19 at 07:11
  • 1
    This does not actually save the file with the modified pixdim as they are overridden by the values in affine matrix. To change it independently of the affine matrix, use `x.header['pixdim'][1:4]=[2,2,2]` after x is created. – Oldrich Jan 15 '21 at 17:35
  • this is not true. the header is indeed changed. see also: https://ibb.co/5Ghfds7 – seralouk Jan 15 '21 at 21:17