Adding a pseudocolor palette to a PIL Image object

June 16, 2002 | Fredrik Lundh

I’d like to show a greylevel image as miscolored image, anyone has an idea how i can do it and maybe adjust the color scale?

Do you mean pseudocoloring? Something like this should work:

from PIL import Image

im ="some grayscale image")
im.load() # make sure it's loaded into memory

assert im.mode == "L"

# create a lookup table (r, g, b, r, g, b, r, g, b, ...)
lut = []
for i in range(256):
    lut.extend([255-i, i/2, i])

assert im.mode == "P" # now has a palette"out.gif")

The load call is a workaround for a bug in PIL 1.1.3 and earlier. Without it, you will sometimes get a ValueError exception when attempting to save (or further process) the image.


A Django site. rendered by a django application. hosted by webfaction.