How to export ParaView colormap into a format that could be read by matplotlib

A beautiful little python function that Cory Quammen created:

Sure, here is a little function that can export the color map in a table:

def ExportPreset(lutName):
  from paraview import servermanager
  presets = paraview.servermanager.vtkSMTransferFunctionPresets()

  lut = GetColorTransferFunction('dummy')
  lut.ApplyPreset(lutName)

  import vtk
  helper = vtk.vtkUnsignedCharArray()

  dctf = lut.GetClientSideObject()
  dataRange = dctf.GetRange()

  for i in range(0, 256):
    x = (i/255.0) * (dataRange[1]-dataRange[0]) + dataRange[0]
    helper.SetVoidArray(dctf.MapValue(x), 3, 1)
    r = helper.GetValue(0)
    g = helper.GetValue(1)
    b = helper.GetValue(2)
    print("%d %d %d" % (r, g, b))

lutName is a string with the name of the colormap you’d like to export.

Evaluate and call this function in the Python Shell (View -> Python Shell). You can adapt the script to produce the type of array needed for the matplotlib function.

If you want to go the other way around and have a color map in matplotlib or python you want to import into paraview…

cmap = lut
#where lut is a colormap of X length by Y as [r,g,b,a]
scheme = 'test'

with open('test.xml', 'w') as fid:
    fid.write('<ColorMaps>\n')
    fid.write('<ColorMap name="{}" space="HSV">\n'.format(scheme))
    N = cmap.shape[0]
    for i in range(N):
        x = [(i-1)/(N-1)] + cmap[i,:].tolist()
        fid.write('<Point x="{:2f}" o="{:2f}" r="{:2f}" g="{:2f}" b="{:2f}" />\n'.format(x[0],x[4],x[1],x[2],x[3]))

    fid.write('</ColorMap>\n')
    fid.write('</ColorMaps>')