2016-11-10 91 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)