[Neuroimaging] How to write a color 3D NIfTI

sullivan, ken ken.sullivan at kohyoung.com
Thu Nov 10 13:38:42 EST 2016


I've had no problem writing out 3D grayscale .nii files with nibabel and
opening them in NIfTI viewers (Mango, MCIcron). However I haven't been able
to write out 3D color, as each RGB plane is being interpreted as a
different volume.  Looking around a bit it seems there is a "dataset" field
in the header that needs to be set to 128 for 24-bit RGB planar images. One
nice thing about nibabel is how it automatically sets up the header based
on the numpy array fed to it. However this is an ambiguous case and if I
print the header information I can see it setting the datatype to 2
(uint8), which presumably is why viewers are interpreting it as separate
volumes, not RGB24. I don't see any official support in the API for setting
the datatype, but the documentation does mention access to the raw fields
for those with "great courage". I tried this:

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

Which, if I print the header, does now show "datatype : RGB", but when I
call nib.save() I get:

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

Which looks like it is caused by an inconsistency of internal types (arr_dtype
!= out_dtype) , which I presume is because just changing the header like I
did isn't enough. Is there a proper way to do this?

Code giving 3 separate 20 x 201 x 202 volumes:
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)

-- 

------------------------------

The information contained in this message and any attachments may be 
confidential and legally privileged. If you are not the intended recipient, 
please notify the sender immediately by return e-mail, delete this e-mail 
and destroy any copies. Any dissemination or use of this information by a 
person other than the intended recipient is unauthorized and may be illegal.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/neuroimaging/attachments/20161110/0c26eb6d/attachment.html>


More information about the Neuroimaging mailing list