Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating image through input pixel values with the Python Imaging Library (PIL)

I'm wanting to work on an idea using images but I can't get it to write pixel values properly, it always just ends up grey with some pattern like artefacts, and no matter what I try, the artefacts change but the image remains grey.

Here's the basic code I have:

from PIL import Image
data = ""
for i in range( 128**2 ):
    data += "(255,0,0),"
im = Image.fromstring("RGB", (128,128), data)
im.save("test.png", "PNG")

There is no information in http://effbot.org/imagingbook/pil-index.htm on how to format data, so I've tried using 0-1, 0-255, 00000000-111111111 (binary), brackets, square bracks, no brackets, extra value for alpha and changing RGB to RGBA (which turns it light grey but that's it), comma after, and no comma after, but absolutely nothing has worked.

For the record, I'm not wanting to just store a single colour, I'm just doing this to initially get it working.

like image 615
Peter Avatar asked Dec 12 '14 14:12

Peter


1 Answers

The format string should be arranged like:

"RGBRGBRGBRGB..."

Where R is a single character indicating the red value of a particular pixel, and the same for G and B.

"But 255 is three characters long, how can I turn that into a single character?" you ask. Use chr to convert your numbers into byte values.

from PIL import Image
data = ""
for i in range( 128**2 ):
    data += chr(255) + chr(0) + chr(0)
im = Image.fromstring("RGB", (128,128), data)
im.save("test.png", "PNG")

Result:

enter image description here


Alternative solution:

Using fromstring is a rather roundabout way to generate an image if your data isn't already in that format. Instead, consider using Image.load to directly manipulate pixel values. Then you won't have to do any string conversion stuff.

from PIL import Image

im = Image.new("RGB", (128, 128))
pix = im.load()
for x in range(128):
    for y in range(128):
        pix[x,y] = (255,0,0)

im.save("test.png", "PNG")
like image 111
Kevin Avatar answered Sep 30 '22 16:09

Kevin