I’m wondering is it possible to export ParaView colormap in RGB format to be able to read it in matplotlib? I know that ParaView could export colormaps in .json format but I don’t know how to convert it in a suitable format to be able to read it by using matplotlib.colors.ListedColormap function. Any idea or help is appreciated.
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.
Thanks Cory, it worked smoothly!
I’m trying to export the opacities but have some trouble, they always return as fully opaque for me. Came across this old response. Should this also return the opacities in the MapValue() function? Or do I need to call the GetOpacityTransferFunction() and do similar operations in a second loop? Thx
This might be an old post but can be useful to someone. The following python script can export any paraview colormap to be exported and independently used as a colormap in matplotlib python.
import json
import vtk
from paraview import servermanager
from paraview.simple import GetColorTransferFunction
def ExportToJSON(lutName):
filename=f"{lutName.lower()}.json"
lut = GetColorTransferFunction(lutName)
if not lut.ApplyPreset(lutName, True):
print(f"Preset {lutName} not found!")
return
dctf = lut.GetClientSideObject()
dataRange = dctf.GetRange()
rgb_data = []
helper = vtk.vtkUnsignedCharArray()
for i in range(256):
x = (i / 255.0) * (dataRange[1] - dataRange[0]) + dataRange[0]
helper.SetVoidArray(dctf.MapValue(x), 3, 1)
# Normalize to [0, 1] for Matplotlib compatibility
r = helper.GetValue(0) / 255.0
g = helper.GetValue(1) / 255.0
b = helper.GetValue(2) / 255.0
rgb_data.append([r, g, b])
with open(filename, 'w') as f:
json.dump(rgb_data, f)
print(f"Colormap exported successfully to {filename}")
if __name__ == "__main__":
ExportToJSON('Spectral_lowBlue')
import json
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
def load_pv_colormap(json_file):
with open(json_file, 'r') as f:
rgb_list = json.load(f)
return ListedColormap(rgb_list)
# Usage
my_cmap = load_pv_colormap('spectral_lowblue.json')
# Quick test visualization
data = np.random.rand(10, 10)
plt.imshow(data, cmap=my_cmap)
plt.colorbar()
plt.savefig("test-colormap.png")