How to get the list of colors in an image in Python

Overview

The Python Imaging Library, known as “PIL” or “pillow,” is a library for image processing in Python. This library has powerful image processing capabilities, supports a large number of file types, and is built for an effective internal representation of picture data.

There are many modules in the PIL library for different purposes. One such module is the Image module. The Image module offers a variety of factory operations, including tools for generating new pictures and loading images from files.

The getcolors() function

The getcolors() function is used to get a list of colors present in the image. The function takes the maxcolors parameter that indicates the maximum number of colors in the given image. But if the number of colors in the given image exceed the maxcolors parameter, the limitation None is returned. The workaround for this limitation is to set the maxcolors parameter to a very high value.

Syntax

Image.getcolors(maxcolors=256)

Code example

Let’s take a look at the example below.

from PIL import Image

img = Image.open("test.png")

max_colors = 10000

print(img.getcolors(max_colors))

Code explanation

  • Line 1: The Image module is imported from PIL.
  • Line 3: The image is loaded to memory.
  • Line 5: The maximum color value is defined and set to a high value so that all colors of the image can be retrieved.
  • Line 7: The colors in the image are obtained and printed.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved