How to convert vtkImageData to binary images?

I have a vtkImageData mask data, and each point is of the Unsigned Char type. In order to save memory, I want to convert it to VTK_BIT type vtkImageData data. Is there any good way, or is there any way to save vtkImageData data in the form of sparse matrix to save memory?


Hi @Jawanz,

Thanks for your question. It is an interesting problem.

Passing over to a vtkBitArray will definitely cut down on your memory cost but might slow down your processing significantly depending on what you are doing. Due to a known issue (, the vtkBitArray is not safe to use in multi-threaded processing.

I would suggest using a more experimental feature that was developped not to long ago: vtkImplicitArrays. Indeed, if you look into vtkToImplicitArrayFilter ( and use the vtkToImplicitRamerDouglasPeuckerStrategy ( You should be able to treat your array as if it was a unsigned char array and have it take much less space in memory effectively begin somewhat compressed into a concatenation of constant arrays over unvarying indexes and affine arrays over jumps.

Hope that helps!

Best regards,

The vtkImageStencilData data type in VTK provides run-length compression of binary images. It is meant to be used for masking operations, and several filters can use it for masking, for example: vtkImageHistogram, vtkImageAccumulate, vtkImageReslice, vtkImageBlend, vtkImageStencil, vtkImageConnectivityFilter, vtkImageToPoints.

The vtkImageToImageStencil filter can create a vtkImageStencilData from vtkImageData, and vtkPolyDataToImageStencil can create vtkImageStencilData from a polydata mesh.