Retrieve the mapped colors from vtkOpenGLPolyDataMapper

Hi Guys

I am in a situation where I am using a LUT for displaying vtkPolyData. I would like to transfer the colors that the mapper uses to the ‘Color’ PointArray of the vtkPolyData instance, such that I can save the color information to the mesh. Is there a simple way to do that?

Thanks in advance

I figured it out. Perhaps a nasty workaround. I ended up rendering once to an offscreen buffer to initialize the LUT and simply use the mapper for converting scalar data into colors and overwrite the colors for the vtkPolyData. Would have been nice to use MapScalarsThroughTable, but I will need to figure out how to do this from Python…

There is a method called MapScalars() that works like MapScalarsThroughTable(), but it returns a vtkUnsignedCharArray.

colorArray = lut.MapScalars(dataArray, 0, 0, 3)

The 3 is for RGB, or use 4 for RGBA.

1 Like

That is clever, the 3 if for RGB similarly to what is used in MapScalarsThroughTable. It works like a charm. I can live with the hack of rendering once to get the LUT to work. But MapScalars is much better than my for loop :smiley:

The MapScalars() method is how vtkMapper (the base class of vtkPolyDataMapper) applies the colors :slight_smile:

The 3 and 4 are defined constants (defined in vtkCommonCore):

>>> from vtkmodules.vtkCommonCore import VTK_RGB, VTK_RGBA
>>> VTK_RGB
3
>>> VTK_RGBA
4

It works out-of-the-box, but the wrapped function MapScalars leaks memory. Is there a clever back-door for calling explicitly the destructor?

Ah, good that you caught the leak! We can easily patch it for VTK 9.3.1.

But until we fix it, here is how to directly manipulate the reference count of VTK objects in Python:

colorArray = lut.MapScalars(dataArray, 0, 0, 3)
# remove extra reference count due to VTK leak
if colorArray.GetReferenceCount() == 2:
    colorArray.SetReferenceCount(1)

Use SetReferenceCount() with caution. Here, it is being used only to fix a bug in VTK. Never use it just to force VTK to delete something, or else you will end up with dangling references and probably corrupted data.

1 Like