我生成一个4D复数numpy数组 例如:
numpy_array = np.tile(np.array([3, 4, 0], dtype=np.complex64), (100,100,100,1))
我想将numpy数组另存为nifti文件
我尝试使用vtk和SimpleITK,但是它们都不支持复数(仅支持实数向量) 看来只有nibabel支持复杂的向量,并且我设法保存了文件,但是当我尝试使用ITK-SNAP或Slicer加载它时,我只能用nibabel加载它,但无法打开。我知道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输出:
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的文档,它不支持copmlex数组, 也许有人知道解决方法。
答案 0 :(得分:1)
SimpleITK 1.2版本支持编写4D复杂图像。缺少的功能是支持stk.GetImageFromArray
中的复数,但是它已经添加到开发分支中,并且如果您是当前SimpleITK master分支的编译版本或等待排定在2019年10月发布的1.3版本,您的代码将起作用。 / p>
同时,您可以像这样将复数分量分别转换为SimpleITK:
image = sitk.RealAndImaginaryToComplexImageFilter(sitk.GetImageFromArray(numpy_array.real),
sitk.GetImageFromArray(numpy_array.imag))
sitk.WriteImage(image, r'file_name.nii')