Orphevs
Orphevs

Reputation: 125

Pillow: image.getcolors(maxcolors) returns None unless maxcolors ≥ 148279

I'm using Pillow to read an image, and get all its colours with Image.getcolors(). From the getcolors() reference page:

Image.getcolors(maxcolors=256)

Returns a list of colors used in this image.
Parameters: maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors.
Returns: An unsorted list of (count, pixel) values.

I am using the following code snippet to load an image, lena.png.

from PIL import Image

def main(filename):
    with Image.open(filename) as image:
        colors = image.getcolors(maxcolors) #where maxcolors is some value, as explained below
        print(colors)

if __name__ == "__main__":
    main("lena.png")

This will print None if image.getcolors() recieves no argument or maxcolors < 148279. If maxcolors >= 148279, the values are printed as expected. The output is along the lines of [(1, (233, 130, 132)), (1, (243, 205, 168)),...(1, (223, 140, 118))], a list of tuples containing the occurence of the colour first, and a tuple of the RGB values second. I checked the output, and there is not one single value greater than 255.

When using another image, test.jpg, the same occurs. There seems to be no correlation to filetype or dimension. Adding image.load() above colors = ... does not change this either. 148279 is a prime, which makes this seem even weirder to me.

Why does getcolors() not work as intended with the default value, and why does it work with 148279?

Upvotes: 1

Views: 1649

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

I think it works correctly, but is maybe not described very well.

If you use ImageMagick on your Lena image, as follows, you will find that your image has exactly 148,279 unique colours in it - see explanatory link here:

identify -format %k lena.png
148279

So, I think the Pillow description probably means that you want a list of the unique colours, so long as there are fewer than the number you specify. You can change the number of colours, also with ImageMagick, to say 32:

convert lena.png -colors 32 lena.png

Then run your Python again, and you will have to make maxcolors 32 or more to get a list of the colours. If you set it to 31 or less, it outputs None.

Upvotes: 2

Related Questions