python - How to write a color 3D NIfTI with NiBabel? -
i've had no problem writing out 3d grayscale .nii files nibabel , opening them in nifti viewers (mango, mcicron). haven't been able write out 3d color, each rgb plane being interpreted different volume. e.g. output this:
import nibabel nib import numpy 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)
is seen 3 separate 20x201x202 volumes. tried putting color planes in first axis (i.e. np.random.rand(3, 20, 201, 202)), same issue. looking around bit seems there "dataset" field needs set 128 24-bit rgb planar images. 1 nice thing nibabel how automatically sets header based on numpy array fed it. ambiguous case , if print header information can see setting datatype 2 (uint8), presumably why viewers interpreting separate volumes, not rgb24. don't see official support in api setting datatype, the documentation mention access raw fields "great courage". doing this, i.e.
hdr = ni_img.header raw = hdr.structarr raw['datatype'] = 128
works in changing header value
print(hdr)
gives "datatype : rgb" when writing
nib.save(ni_img, nifti_path)
i error:
file "<python path>\lib\site-packages\nibabel\arraywriters.py", line 126, in scaling_needed raise writererror('cannot cast or non-numeric types') nibabel.arraywriters.writererror: cannot cast or non-numeric types
the exception raised if arr_dtype != out_dtype, presumably hacking of raw header causing inconsistency down line.
so, there proper way this?
thanks matthew.brett on neuroimaging analysis mailing list, i'm able write out 3-d color nifti so:
# ras_pos 4-d numpy array, 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 force fresh internal structure ni_img = nib.nifti1image(ras_pos, np.eye(4)) nib.save(ni_img, output_path)
Comments
Post a Comment