views:

80

answers:

3

Hi all,

I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a integer from 0 to 255. To save this to a PNG I can create a 3 item tuple of each element (x) like so:

t = (x, x, x)

add apply it across the array using the map(), then save the image using putdata(). However, the conversion to the array of tuples takes a long time (few minutes). Is there a way to specify the rgb value using only one integer (not a tuple). I guessing an alternative would be to use NumPy, but I don't know where to start, so any help in this regard would also be appreciated.

Thanks in advance for the help.

+2  A: 

There are several ways to do this, but if you already have the data in memory, look into using Image.frombuffer or Image.fromstring using the 'L' mode (for 8-bit greyscale data).

tkerwin
A: 

Would im.putpixel(xy, colour) be what you are looking for?

David Sowsy
putpixel is significantly slower than putdata
Nadia Alramli
I agree. I was using putpixel() in a previous version. Worked but is ~10x slower. (1m30s vs 0m15s for putdata())
Vince
+2  A: 

When you create the new image, give it the mode L:

im = Image.new('L', size)
im.putdata([x1, x2, x3, ...])

Where data is a list of values not tuples.

Nadia Alramli
Exactly what I was looking for. Thank you!
Vince