UnknownColormap="UnknownColormap" import os.path import Image, ImagePalette import numpy class ColorTable: def __init__(self, colormap = None): self.colormap = colormap if colormap != None: self.load(colormap) def get_palette(self,colormap=""): """ Returns a string representation of the colormap, as used with a PIL image @param colormap the name of the colormap to use. If not defined, throws an "UnknownColormap" exception """ if(self.colormap != colormap): self.load(colormap) return self.palette def get_length(self,colormap=""): if(self.colormap != colormap): self.load(colormap) return self.length def load(self, colormap): """Load the palette with colormap""" lutfile = os.path.join ( os.path.dirname ( __file__ ), "color_LUT", colormap+".pal" ) if not os.path.exists(lutfile) : lutfile = os.path.join ( os.path.dirname ( __file__ ), "color_LUT", colormap ) if not os.path.exists(lutfile) : lutfile = colormap if not os.path.exists(lutfile) : if not os.path.exists(lutfile) : raise UnknownColormap, colormap self.length = 0 fh = open(lutfile, "r") self.palette=[] for line in fh.xreadlines(): RGB = line.split() self.palette.extend((int(RGB[0]), int(RGB[1]), int(RGB[2]))) self.length += 1 fh.close() def save(self, colormap): """Saves the palette under name colormap""" lutfile = os.path.join ( ".","color_LUT",colormap+".pal" ) print 'saving palette '+lutfile print self.palette fh = open(lutfile, "w") for r, g, b in self.palette: line = str(r)+" "+str(g)+" "+str(b)+'\n' fh.write(line) fh.close() def get_Palette_from_image(self,colormap,filename): """ """ image = Image.open(filename, 'r') pal = image.palette assert image.mode == "P" lut = image.resize((256, 1)) lut.putdata(range(256)) lut = list(lut.convert("RGB").getdata()) pal = lut self.palette = pal self.save(colormap) def main(): ct = ColorTable(None) ct.get_Palette_from_image(sys.argv[1],sys.argv[2]) if __name__ == '__main__': main()