Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL import png pixels as single value instead of 3 values vector

I have a bunch of map files I've downloaded from Google maps in png formats that I want to convert to a single larger image. When I import one and I look at the pixels, I see that the pixels are a single number in the range of 0..256 instead of three values list. What's going on here?

I'm using

from PIL import Image

print open('b1.png').load()[0,0]

and I get 153 instead of [r,g,b]

my image file is enter image description here

like image 430
Yotam Avatar asked Nov 05 '25 17:11

Yotam


2 Answers

The reason of such result (value 153 in [0,0]) is that image mode is set to P (8-bit pixels, mapped to any other mode using a colour palette). If You want to set different mode (e.g. RGB) You can do it before invoking method load().

Here is an example of how to do this:

from PIL import Image
file_data = Image.open('b1.png')
file_data = file_data.convert('RGB') # conversion to RGB
data = file_data.load()
print data[0,0]

and the result of print is

(240, 237, 229)

For more information about Image Modes please visit the documentation.

like image 74
Drop Avatar answered Nov 08 '25 08:11

Drop


Your image is in mode=P. It has it's colors defined in a color palette.

>>> Image.open('b1.png')
<PIL.PngImagePlugin.PngImageFile image mode=P size=640x640 at 0x101856B48>

You want a RGB value. First convert to RGB:

>>> im = Image.open('b1.png')
>>> im = im.convert('RGB')
>>> im.getpixel((1,1))
(240, 237, 229)

From the docs: http://pillow.readthedocs.org/en/latest/handbook/concepts.html?highlight=mode

P (8-bit pixels, mapped to any other mode using a color palette)
...
RGB (3x8-bit pixels, true color)

like image 23
allcaps Avatar answered Nov 08 '25 06:11

allcaps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!