【问题标题】:How to convert 3D numpy array to nifti image in nibabel?如何将 3D numpy 数组转换为 nibabel 中的 nifti 图像?
【发布时间】:2019-03-10 17:35:15
【问题描述】:

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

【问题讨论】:

    标签: python numpy nifti nibabel neuro-image


    【解决方案1】:

    假设你是一个 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.gz 覆盖到task-rest_bold.nii.gz

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-10-26
    • 2014-06-02
    • 2021-12-29
    • 2018-07-21
    • 2017-03-10
    相关资源
    最近更新 更多