更改Numpy和Nibabel中的数据类型

更改Numpy和Nibabel中的数据类型,numpy,Numpy,我正在尝试使用Nibabel将numpy数组转换为Nifti文件格式。我的一些Numpy数组具有dtype('标题问题与文本中的问题略有不同。因此 如果要将numpy数组的数据类型arr更改为np.int8,则需要查找arr.astype(np.int8) 请注意,由于数据转换,您可能会失去精度(请参阅文档) 要在以后保存它,您可能需要查看?np.save和?np.savetxt(或者检查库pickle,以保存比numpy数组更通用的对象) 如果要更改保存在my_image.nii.gz 你

我正在尝试使用Nibabel将numpy数组转换为Nifti文件格式。我的一些Numpy数组具有
dtype('标题问题与文本中的问题略有不同。因此


如果要将numpy数组的数据类型
arr
更改为
np.int8
,则需要查找
arr.astype(np.int8)

请注意,由于数据转换,您可能会失去精度(请参阅文档)

要在以后保存它,您可能需要查看
?np.save
?np.savetxt
(或者检查库
pickle
,以保存比numpy数组更通用的对象)


如果要更改保存在
my_image.nii.gz
你必须选择:

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')

最后,如果您有一个numpy数组
my\u arr
,并且希望将其保存到具有给定数据类型
np.my\u dtype
的nifti映像中,您可以执行以下操作:

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')
希望有帮助



注意:如果您正在使用ITKsnap,您可能需要使用
np.float32
np.float64
np.uint16
np.uint8
np.int16
np.int8
。其他选项可能无法生成可使用此软件打开的图像。

似乎您也可以这样做

import nibabel

img = nibabel.load(filename)
img.set_data_dtype(dtype)
img.to_filename(new_filename)

您可以使用nilearn获得一个整洁的解决方案。如果您想将nifti图像的数据类型更改为int16,请参见以下示例:

from nilearn import image
import numpy as np

vol = image.load_img(input_file)
vol = image.new_img_like(vol, np.int16(vol.get_fdata()))
vol.to_filename(output_file)

'原始数组的数据类型为int64,但更改为'
np.ones'(3),@hpaulj谢谢!这似乎在nib调用中也起作用。这现在在函数
set_new_data
中编码,作为pip可安装库nilabels的一部分。利益冲突声明:我做的!这不起作用。这将创建一个乱码文件,因为用户还必须更改img中的数据。
from nilearn import image
import numpy as np

vol = image.load_img(input_file)
vol = image.new_img_like(vol, np.int16(vol.get_fdata()))
vol.to_filename(output_file)