我生成一个 4D 复杂的 numpy 数组,例如:
numpy_array = np.tile(np.array([3, 4, 0], dtype=np.complex64), (100,100,100,1))
我想将 numpy 数组保存为 nifti 文件
我尝试使用 vtk 和 SimpleITK,但它们都不支持复数(只有实数向量)似乎只有 nibabel 支持复数向量,我设法保存文件,但我只能用 nibabel 加载它,当我尝试使用 ITK-SNAP 或 Slicer 加载它时,它不会打开。我知道 ITK-SNAP 可以打开 nifti 文件的复杂向量,因为我已经使用 matlab 将这些文件与另一个脚本一起保存
import numpy as np
import nibabel as nib
import SimpleITK as sitk
import vtk
from vtk.util.numpy_support import numpy_to_vtk
numpy_array = np.tile(np.array([3, 4, 0], dtype=np.complex64), (100,100,100,1))
nibabel 保存尝试:
image = nib.Nifti2Image(numpy_array, affine=np.eye(4))
nib.save(image , r'file_name.nii')
SimpleITK 保存尝试:
image = sitk.GetImageFromArray(numpy_array)
sitk.writeimage(image, r'file_name.nii')
vtk 保存尝试:
array = np.concatenate((np.real(numpy_array), np.imag(numpy_array)), axis=3)
stacked_array = array.reshape(-1, array.shape[-1])
vtk_array = numpy_to_vtk(stacked_array, deep=True,
array_type=vtk.VTK_FLOAT)
vtk_image = vtk.vtkImageData()
vtk_image.SetDimensions(numpy_array.shape[0], numpy_array.shape[1],
numpy_array.shape[2])
vtk_image.GetPointData().SetScalars(vtk_array)
writer = vtk.vtkNIFTIImageWriter()
writer.SetFileName(file_name)
writer.SetInputData(vtk_image)
writer.Write()
尼巴贝尔输出:
nibabel 创建一个带有矢量的 nifti 文件,但使用其他程序(如 ITK-SNAP)它不会打开
ITK-SNAP 错误:
Error: Unsupported or missing image file format. ITK-SNAP failed to create an
ImageIO object for the image 'file_name.nii' using format ''.
SimpleITK 错误:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\SimpleITK\SimpleITK.py", line 3366, in _get_sitk_vector_pixelid
return _np_sitk[numpy_array_type.dtype]
KeyError: dtype('complex64')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\ProgramData\Anaconda3\lib\site-packages\SimpleITK\SimpleITK.py", line 3431, in GetImageFromArray
id = _get_sitk_vector_pixelid( z )
File "C:\ProgramData\Anaconda3\lib\site-packages\SimpleITK\SimpleITK.py", line 3371, in _get_sitk_vector_pixelid
raise TypeError('dtype: {0} is not supported.'.format(numpy_array_type.dtype))
TypeError: dtype: complex64 is not supported.
vtk 输出:
vtk 创建了一个矢量 nifti 文件,但有 6 个组件而不是 3 个(也将虚部视为组件),我在 numpy_to_vtk 的文档中看到它不支持 coplex 数组,也许有人知道解决方法。