Forgive me for any naivety, but I am new to working with images. Say I have a list of binary values [1,0,0,0,1,0,1,0,0,0,0,1,1,0....] which represent pixels in a black and white image. How would I go about making a .png file from this list?
-
Is this just a 1-D list?Chris Eberle– Chris Eberle2011-04-15 05:40:21 +00:00Commented Apr 15, 2011 at 5:40
-
Yes, it's just a 1-D list, but I want to make a 5x5 image and do want to map 0 to pure black and 1 to pure white. I can't figure out how to work with BasicWolf's suggestion, it creates an image, but the image is all black.Nacre– Nacre2011-04-15 16:26:43 +00:00Commented Apr 15, 2011 at 16:26
-
1Actually it's mostly black. If you take his suggestion, you'll be writing 0 and 1, which out of 255 will look pretty darn black.Chris Eberle– Chris Eberle2011-04-15 16:37:33 +00:00Commented Apr 15, 2011 at 16:37
Add a comment
|
2 Answers
Use Python Imaging Library for this purpose.
There is a img = Image.frombuffer(mode, size, data) method which creates an image from "raw" data (a string). You can then save it as PNG file via img.save('image.png', transparency=transparency)
1 Comment
Chris Eberle
Yes but he wants to map 0 to pure black (0,0,0) and 1 to pure white (255,255,255)
Expanding on BasicWolf's example:
from PIL import Image
import struct
size = 5, 5
arr = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0]
data = struct.pack('B'*len(arr), *[pixel*255 for pixel in arr])
img = Image.frombuffer('L', size, data)
img.save('image.png')
I think this is what you're after...