Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change data type in Numpy and Nibabel

Tags:

numpy

I'm trying to convert numpy arrays into Nifti file format using Nibabel. Some of my Numpy arrays have dtype('<i8') when it should be dtype('uint8') when Nibabel calls for the data type.

arr.get_data_dtype()

Does anyone know how to convert and save Numpy arrays' data type?

like image 573
Char Avatar asked Sep 01 '25 05:09

Char


1 Answers

The question of the title is slightly different than the question in the text. So...


If you want to change the data-type of a numpy array arr to np.int8, you are looking for arr.astype(np.int8).

Mind that you may lose precision due to data casting (see astype documentation)

To save it afterwards you may want to see ?np.save and ?np.savetxt (or to check the library pickle, to save more general objects than numpy array).


If you want to change the data-type of a nifti image saved in my_image.nii.gz you have to go for:

import nibabel as nib
import numpy as np

image = nib.load('my_image.nii.gz')

# to be extra sure of not overwriting data:
new_data = np.copy(image.get_data())
hd = image.header

# in case you want to remove nan:
new_data = np.nan_to_num(new_data)

# update data type:
new_dtype = np.int8  # for example to cast to int8.
new_data = new_data.astype(new_dtype)
image.set_data_dtype(new_dtype)

# if nifty1
if hd['sizeof_hdr'] == 348:
    new_image = nib.Nifti1Image(new_data, image.affine, header=hd)
# if nifty2
elif hd['sizeof_hdr'] == 540:
    new_image = nib.Nifti2Image(new_data, image.affine, header=hd)
else:
    raise IOError('Input image header problem')

nib.save(new_image, 'my_image_new_datatype.nii.gz')

Finally if you have a numpy array my_arr and you want to save it into a nifti image with a given data-type np.my_dtype, you can do:

import nibabel as nib
import numpy as np

new_image = nib.Nifti1Image(my_arr, np.eye(4))
new_image.set_data_dtype(np.my_dtype)

nib.save(new_image, 'my_arr.nii.gz')

Hope it helps!


NOTE: If you are using ITKsnap you may want to use np.float32, np.float64, np.uint16, np.uint8, np.int16, np.int8. Other choices may not produce images that can be open with this software.

like image 71
SeF Avatar answered Sep 03 '25 03:09

SeF