4

我用 nibabel 写出 3D 灰度 .nii 文件并在 NIfTI 查看器(Mango、MCIcron)中打开它们没有问题。但是我无法写出 3D 颜色,因为每个 RGB 平面都被解释为不同的体积。例如,由此产生的输出:

import nibabel as nib
import numpy as np
nifti_path = "/my/local/path"
test_stack = (255.0 * np.random.rand(20, 201, 202, 3)).astype(np.uint8)
ni_img = nib.Nifti1Image(test_stack, np.eye(4))
nib.save(ni_img, nifti_path)

被视为 3 个独立的 20x201x202 卷。我还尝试将颜色平面放在第一个轴上(即 np.random.rand(3, 20, 201, 202)),但遇到了同样的问题。环顾四周,对于 24 位 RGB 平面图像,似乎有一个“数据集”字段需要设置为 128。关于 nibabel 的一件好事是它如何根据提供给它的 numpy 数组自动设置标题。然而,这是一个模棱两可的情况,如果我打印标题信息,我可以看到它将数据类型设置为 2(uint8),这可能是观众将其解释为单独卷而不是 RGB24 的原因。我在API中没有看到任何官方支持设置数据类型,但 文档确实提到了对具有“很大勇气”的人的原始字段的访问权限。这样做,即

hdr = ni_img.header
raw = hdr.structarr
raw['datatype'] = 128

用于更改标题值

print(hdr)

给出“数据类型:RGB”但在写入时

nib.save(ni_img, nifti_path)

我收到一个错误:

File "<python path>\lib\site-packages\nibabel\arraywriters.py", line 126, in scaling_needed
raise WriterError('Cannot cast to or from non-numeric types')
nibabel.arraywriters.WriterError: Cannot cast to or from non-numeric types

如果某些 arr_dtype != out_dtype 会引发异常,所以大概我对原始标头的黑客攻击导致了一些不一致。

那么,有没有合适的方法来做到这一点?

4

2 回答 2

4

感谢神经影像分析邮件列表上的 matthew.brett,我能够像这样写出 3-d 彩色 NIfTI:

# ras_pos is a 4-d numpy array, with the last dim holding RGB
shape_3d = ras_pos.shape[0:3]
rgb_dtype = np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')])
ras_pos = ras_pos.copy().view(dtype=rgb_dtype).reshape(shape_3d)  # copy used to force fresh internal structure
ni_img = nib.Nifti1Image(ras_pos, np.eye(4))
nib.save(ni_img, output_path)
于 2017-08-01T23:04:21.223 回答
2

使用建议的方法有效,查看 RGB 音量,例如 ITK-SNAP 没有问题,

# ras_pos is a 4-d numpy array, with the last dim holding RGB
shape_3d = ras_pos.shape[0:3]
rgb_dtype = np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')])
ras_pos = ras_pos.copy().view(dtype=rgb_dtype).reshape(shape_3d)  # copy used 
#to force fresh internal structure
ni_img = nib.Nifti1Image(ras_pos, np.eye(4))
nib.save(ni_img, output_path)

但是,重新加载图像仅适用于 get_data()

ni_img = nib.load(output_path)

# this will result in error
data = img.get_fdata()

# this will work fine, but get_data() is going to be removed.
data = img.get_data()

这很关键,因为 get_data() 将在未来的版本中删除。推荐只使用 get_fdata()。get_fdata() 方法当前存在错误,该方法无法将 RGB 数据转换为有效的 numpy 数组。

于 2019-05-12T15:44:34.370 回答