如何在nibabel中将3D numpy数组转换为nifti图像?

8
从这个问题如何将Nifti文件转换为Numpy数组?,我创建了一个nifti图像的3D numpy数组。我对这个数组进行了一些修改,比如通过添加零填充来改变数组的深度。现在我想将这个数组转换回nifti图像,怎么做?
我尝试过:
imga = Image.fromarray(img, 'RGB')
imga.save("modified/volume-20.nii")

但是它无法识别nii扩展名。我也尝试过:

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

这也无法运行,因为如果我想使用nib.save功能,img必须是nibabel.nifti1.Nifti1Image格式。在上述两个示例中,img都是一个三维numpy数组。

1个回答

8
假设您有一个NumPy数组,想要使用nib.save函数,您需要先获取仿射变换。
示例:
# 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.gz叠加到 task-rest_bold.nii.gz 上。

你好,能帮我看一下这篇文章吗?https://stackoverflow.com/questions/56698087/how-to-remove-a-modality-from-mri-image-python-nibabel。 这个问题也和这个主题有关。 - The Great

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接