6

从这个问题How to convert Nifti file to Numpy array? ,我创建了一个 nifti 图像的 3D numpy 数组。我对这个数组做了一些修改,比如我通过添加零填充来改变数组的深度。现在我想将此数组转换回 nifti 图像,我该怎么做?

我试过:

imga = Image.fromarray(img, 'RGB')
imga.save("modified/volume-20.nii")

但它不能识别nii扩展名。我也试过:

nib.save(img,'modified/volume-20.nii')

这也行不通,因为如果我想使用功能img就必须这样做。在上面的两个例子中都是一个 3D numpy 数组。nibabel.nifti1.Nifti1Imagenib.saveimg

4

1 回答 1

6

假设你是一个 numpy 数组并且你想使用nib.save函数,你需要先得到affine转换。

例子:

# define the path to the data
func_filename = os.path.join(data_path, 'task-rest_bold.nii.gz')

# load the data
func = nib.load(func_filename)

# do computations that lead to a 3D numpy array called "output"
# bla bla bla
# output = np.array(....)

# to save this 3D (ndarry) numpy use this
ni_img = nib.Nifti1Image(output, func.affine)

nib.save(ni_img, 'output.nii.gz')

现在您将能够覆盖output.nii.gztask-rest_bold.nii.gz

于 2019-06-17T17:10:10.410 回答