image python

Florian Schmidt schmidt_florian at
Mon Oct 1 21:30:22 CEST 2007

On Mon, Oct 01, 2007 at 11:21:09AM -0700, oruccim at wrote:
> hi
> I want understanding pictures colorfull
> for examle colorfull or black-white
> there are understand it.

i'm not sure if i understand your question. assuming you want to decide if
an image has only grayscale or multi-channel color data you could use
the python image library

>>> from PIL import Image
>>> im ="gray.png")
>>> im.mode
>>> im ="color.jpeg")
>>> im.mode
>>> im ="another_gray.jpeg")
>>> im.mode

but this doesn't tell you if color.jpeg really uses non-gray colors...

if you really want to do an expensive search, if an RGB image contains
only gray colors, you could do something like that:
>>> im ="color.jpeg")
>>> im.mode

im.getcolors() returns a list like [(color_count, (red, green, blue)),

to only select the channel values one could do:
>>> colors = set(lambda cv: cv[1], im.getcolors())

lets define a gray color as a color with all three color channels having the
same value like (30, 30, 30). to detect if a sequence has only equal items
one could create a set of this sequence and see how many items the set
contains afterwards:
>>> set((30, 30, 30))
>> len(set((30, 30, 30)))

to check if an rgb image uses only grayscale colors we can do
>>> map(lambda cv: len(set(cv[1])), im.getcolors())
[1, 1, 1, 1, ....
the returned list contain only 1's if there are only gray values in the

to easyly show this we can again create a set from this list:
>>> set(map(lambda cv: len(set(cv[1])), im.getcolors()))

so "im" is an grayscale image even though it has three channels.

this method does not always work:
- with indexed image data,
- with another definition/understanding of "gray" pixels

but maybe PIL can help you anyway!


Florian Schmidt	//

More information about the Python-list mailing list