npy 到 nii.gz 转换的问题

Problems with npy to nii.gz conversion

我正在尝试将 .npy 图像转换为 nii.gz 图像,但我遇到了各种问题,即使我正确地遵循了说明。

这是我正在使用的代码:

import numpy as np
import nibabel as nib

file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
print(img_array1.shape)
print(img_array1.dtype)

normal_array = "D:/teste volumes slicer/teste01.npy"
print ("done")
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))

关于图像:(332, 360, 360) float64(这是我们打印shape和dtype时得到的) https://ibb.co/mRyTrw7 - 显示错误和图像信息的图像

The error message: 
Traceback (most recent call last):
  File "d:\teste volumes slicer\conversor.py", line 16, in <module>
    nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
  File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1756, in __init__
    super(Nifti1Pair, self).__init__(dataobj,
  File "C:\Python39\lib\site-packages\nibabel\analyze.py", line 918, in __init__
    super(AnalyzeImage, self).__init__(
  File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 469, in __init__
    self.update_header()
  File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 2032, in update_header
    super(Nifti1Image, self).update_header()
  File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1795, in update_header
    super(Nifti1Pair, self).update_header()
  File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 491, in update_header
    shape = self._dataobj.shape
AttributeError: 'str' object has no attribute 'shape'

您的代码的问题不是传递您的 Numpy 数组(您的图像),而是将图像的路径传递给 Nifti1Image 函数。

正确的转换方式是:

import numpy as np
import nibabel as nib

file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1) 
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))