Yotam
Yotam

Reputation: 10685

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

Upvotes: 4

Views: 3968

Answers (2)

allcaps
allcaps

Reputation: 11248

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)

Upvotes: 2

Drop
Drop

Reputation: 450

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.

Upvotes: 6

Related Questions