Hi,
I posted a problem on the list earlier that didn't seem to make it to the
list. Anyway, It gave me time to solve my problem and the result is this
function that takes as input a .cpt file (a palette file format) and return=
s
a colormap dictionnary.
It can return a continuous or discrete colormap (provided the input palette
is itself discrete) and symetric/asymetric colormap.
Have fun !
David
# cpt_reader
# Read cpt palette and returns a segmented color dictionary for use in
matplotlib
# David Huard, February 2006
# dav...@gm...
from scipy.io import read_array
from scipy import zeros, linspace, shape, Float, concatenate
def cpt2seg(file_name, sym=3DFalse, discrete=3DFalse):
"""Reads a .cpt palette and returns a segmented colormap.
sym : If True, the returned colormap contains the palette and a mirrore=
d
copy.
For example, a blue-red-green palette would return a
blue-red-green-green-red-blue colormap.
discrete : If true, the returned colormap has a fixed number of uniform
colors.
That is, colors are not interpolated to form a continuous range.
Example :
>>> _palette_data =3D cpt2seg('palette.cpt')
>>> palette =3D matplotlib.colors.LinearSegmentedColormap('palette',
_palette_data, 100)
>>> imshow(X, cmap=3Dpalette)
"""
dic =3D {}
f =3D open(file_name, 'r')
rgb =3D read_array(f)
rgb =3D rgb/255.
s =3D shape(rgb)
colors =3D ['red', 'green', 'blue']
for c in colors:
i =3D colors.index(c)
x =3D rgb[:, i+1]
if discrete:
if sym:
dic[c] =3D zeros((2*s[0]+1, 3), dtype=3DFloat)
dic[c][:,0] =3D linspace(0,1,2*s[0]+1)
vec =3D concatenate((x ,x[::-1]))
else:
dic[c] =3D zeros((s[0]+1, 3), dtype=3DFloat)
dic[c][:,0] =3D linspace(0,1,s[0]+1)
vec =3D x
dic[c][1:, 1] =3D vec
dic[c][:-1,2] =3D vec
else:
if sym:
dic[c] =3D zeros((2*s[0], 3), dtype=3DFloat)
dic[c][:,0] =3D linspace(0,1,2*s[0])
vec =3D concatenate((x ,x[::-1]))
else:
dic[c] =3D zeros((s[0], 3), dtype=3DFloat)
dic[c][:,0] =3D linspace(0,1,s[0])
vec =3D x
dic[c][:, 1] =3D vec
dic[c][:, 2] =3D vec
return dic
|