[Neuroimaging] How to write a color 3D NIfTI

Matthew Brett matthew.brett at gmail.com
Thu Nov 10 14:01:06 EST 2016


Hi,

On Thu, Nov 10, 2016 at 10:38 AM, sullivan, ken
<ken.sullivan at kohyoung.com> wrote:
> 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:

Yes, it's a bit difficult to set the datatype post-hoc to the data
array.  In practice, you'll have to cast the array correctly before
passing it to the image constructor.  Something like:

In [21]: shape_3d = (5, 6, 7)
In [22]: rgb_arr = np.random.randint(0, 256, size=shape_3d + (3,)).astype('u1')
In [23]: rgb_dtype = np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')])
In [24]: rgb_typed = rgb_arr.view(rgb_dtype).reshape(shape_3d)
In [25]: import nibabel as nib
In [26]: img = nib.Nifti1Image(rgb_typed, np.eye(4))
In [27]: img.header['datatype']
Out[27]: array(128, dtype=int16)

Cheers,

Matthew


More information about the Neuroimaging mailing list