I'm trying to save a numpy
volume to an NRRD
file format using itk
, to use it later with Matlab
, and I want export the file in a Boolean
or logical
datatype if that's possible.
The operation works great with int16
datatype (but the resultant file is large):
itkVol = itk.GetImageFromArray(npVol.astype(np.int16))
imageType = itk.Image[itk.SS, 3]
writerType = itk.ImageFileWriter[imageType]
writer = writerType.New()
writer.SetFileName('/home/user/Desktop/test.nrrd')
writer.SetInput(itkVol)
writer.Update()
The original type of npVol
(the numpy
3D array) is float64
, my problem is that I didn't know how save it is logical
or bool
datatype to save memory (I have to export many of them and they are large files).
I tried casting the type to a bool
type and pass it to the ImageFileWriter()
in itk
but I got an error:
here is the code:
itkVol = itk.GetImageFromArray(npVol.astype(np.bool))
imageType = itk.Image[itk.B, 3]
and here is the error:
TemplateTypeError: itk.ImageFileWriter is not wrapped for input type `itk.Image[itk.B,3]`.
The error messages are pretty straightforward about ImageFileWriter()
not supporting such a type, and it gave me the list of supported input types (and non of them is logical
or of type bool
):
Supported input types:
itk.Image[itk.UC,2]
itk.Image[itk.UC,3]
itk.Image[itk.RGBPixel[itk.UC],2]
itk.Image[itk.RGBPixel[itk.UC],3]
itk.Image[itk.RGBAPixel[itk.UC],2]
itk.Image[itk.RGBAPixel[itk.UC],3]
itk.Image[itk.Vector[itk.F,2],2]
itk.Image[itk.Vector[itk.F,2],3]
itk.Image[itk.Vector[itk.F,3],2]
itk.Image[itk.Vector[itk.F,3],3]
itk.Image[itk.Vector[itk.F,4],2]
itk.Image[itk.Vector[itk.F,4],3]
itk.Image[itk.CovariantVector[itk.F,2],2]
itk.Image[itk.CovariantVector[itk.F,2],3]
itk.Image[itk.CovariantVector[itk.F,3],2]
itk.Image[itk.CovariantVector[itk.F,3],3]
itk.Image[itk.CovariantVector[itk.F,4],2]
itk.Image[itk.CovariantVector[itk.F,4],3]
itk.Image[itk.SS,2]
itk.Image[itk.SS,3]
itk.Image[itk.US,2]
itk.Image[itk.US,3]
itk.Image[itk.F,2]
itk.Image[itk.F,3]
itk.Image[itk.complex[itk.F],2]
itk.Image[itk.complex[itk.F],3]
itk.VectorImage[itk.SS,2]
itk.VectorImage[itk.UC,2]
itk.VectorImage[itk.US,2]
itk.VectorImage[itk.F,2]
itk.VectorImage[itk.SS,3]
itk.VectorImage[itk.UC,3]
itk.VectorImage[itk.US,3]
itk.VectorImage[itk.F,3]
How can I do it?
PS: I'm new to both python and itk
Image of bool
s is frequently needed for binary masks, but all real-world solutions I have seen is using an integral type. 0=false, nonzero=true, usually in 8-bit unsigned int. NumPy's name for it might be uint8, and ITK's name for it is UC (unsigned char). Getting around this is hard.
But what could be easily accomplished is to compress the output file by writer.SetUseCompression(True)
or writer.UseCompressionOn()
. And if your "true" value is consistent (e.g. always 1 or always 255), these files should compress well. If your image is a binary label map, you can expect compression down to about 1%-2% of their original size.