vtkImageData to png

Dear everyone,
I would like to export a vtkImageData of 500x500 cells to a png picture of exactly 500x500 pixel resolution. In this way, every pixel should be approximately corresponding to a cell.

This means fitting my vtkImageData (grey box) to the render view (black box) and exporting a screenshot if we would be in paraview

Is there a way for vtk to export directly the 500x500 vtkImageData to a 500x500 px png image?

Here are further details on my object:
image

You can use vtkJPEGWriter or vtkPNGWriter and pass your vtkImageData as input.

Does the vtkPNGWriter then write only the vtkImageData or does it export the render with the background as well?

I tried it since it’s called when you use “Save Data” on paraview, but it always gives out an error like this one:

PNGWriter only supports unsigned char and unsigned short inputs

Saw a possible fix in one gitlab issue but I didn’t understand how to implement the fix in my code as well
Here is my code for reference:

The vtkPNGWriter will only write the image data, it won’t write the rendered background or any rendered annotations.

If the data type is “float” or any type other than “unsigned char” or “unsigned short”, then a good way to convert it before saving as PNG is vtkImageMapToColors.

Python example:

table = vtkScalarsToColors()
table.SetRange(0.0, 1.0) # set the range of your data values

convert = vtkImageMapToColors()
convert.SetLookupTable(table)
convert.SetOutputFormatToRGB()
convert.SetInputData(image_data)
convert.Update()

writer = vtkPNGWriter()
writer.SetInputData(convert.GetOutput())
...