Creating an Image Using Input Pixel Values ​​Using the Python Image Library (PIL)

I want to work on an idea using images, but I cannot get it to write pixel values ​​correctly, it always ends in gray with some pattern similar to artifacts, and no matter what I try, the artifacts change, but the image remains gray.

Here is 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 tried using 0-1, 0- 255, 00000000-111111111 (binary), brackets, square brackets, without brackets, an extra value for alpha and changing RGB to RGBA (which makes it light gray, but it is), a comma after and without a comma, but absolutely nothing worked.

For the record, I don’t want to just store one color, I just do it to initially make it work.

+5
source share
1 answer

The format string should be organized as follows:

"RGBRGBRGBRGB ..."

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

"But 255 three characters long, how can I turn this into one character?" you ask. Use chr to convert numbers to 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 pretty roundabout way to generate an image if your data is not in this format yet. Instead, consider using Image.load to directly control pixel values. Then you do not have to do any string conversions.

 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") 
+8
source

Source: https://habr.com/ru/post/1208891/


All Articles