2016-11-10 54 views
1

我用nibabel写出3D灰度.nii文件并在NIfTI观众(Mango,MCIcron)中打开它们没有任何问题。但是我无法写出3D颜色,因为每个RGB平面都被解释为不同的体积。例如。来自此的输出:如何用NiBabel编写3D NIfTI颜色?

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)),但是得到同样的问题。回顾一下,似乎有一个“数据集”字段需要设置为128位的24位RGB平面图像。关于nibabel的一个好处是它如何自动设置基于numpy数组的头部。然而,这是一个模棱两可的情况,如果我打印标题信息,我可以看到它将数据类型设置为2(uint8),这可能是为什么观众将它解释为单独的卷,而不是RGB24。我在API中没有看到任何设置数据类型的官方支持,但 the documentation确实提到了那些“非常有勇气”的原始字段的访问权限。在不断变化的标头值

print(hdr) 

这样做,即

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

作品给人 “数据类型: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,所以大概是我对黑头的黑客攻击造成了一些不一致。

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

回答

0

由于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)