[Image-SIG] show a matrix as image
efotinis at yahoo.com
Tue Aug 11 18:06:34 CEST 2009
From: Milton Cezar Ribeiro
> I have an object that is a matrix (i.e. a list of lists)
> and I neet do plot it on screen as an image.
> My image have values 1 and 2, and I would
> like set different colors for each level.
> I tryed figure it out without success. In fact
> my images are 512x512, but I include a 10x10 sample below.
It's best to use a palettized image, since your data points are integers.
First, create one of the right size:
from PIL import Image
im = Image.new('P', (512,512)) # 'P' for palettized
Then, set the image data. You must use a flat list, so you need to flatten
data = sum(matrix, ) # flatten data
You also have to set the palette colors for the used indices (1 and 2). The
palette is a list of 768 ints (256*3), but it's somewhat easier to start
with a list of 3-tuples:
pal = [(0,0,0) for i in range(256)] # all black
pal = (255,0,0) # juicy red
pal = (0,255,0) # crazy green
pal = sum(pal, ()) # flatten it
That's it. You should be able to test the result with this:
More information about the Image-SIG