Extracting Color Palette From Image in Python

In this article, we will learn how to extract color palette from an image using python. We will use python colorgram.py to extract.

Step 1: install colorgram.py

We can use pip to install

pip install colorgram.py

Step 2: extract color palette from an image

We can use colorgram.extract(image, number_of_colors) to extract.

Here is an example:

import colorgram

# Extract 6 colors from an image.
colors = colorgram.extract('test.jpg', 6)

# colorgram.extract returns Color objects, which let you access
# RGB, HSL, and what proportion of the image was that color.
first_color = colors[0]
rgb = first_color.rgb # e.g. (255, 151, 210)
hsl = first_color.hsl # e.g. (230, 255, 203)
proportion  = first_color.proportion # e.g. 0.34

# RGB and HSL are named tuples, so values can be accessed as properties.
# These all work just as well:
red = rgb[0]
red = rgb.r
saturation = hsl[1]
saturation = hsl.s

In this example, we will extract 6 colors from image test.jpg.

Run this code, you will see:

 Extracting Color Palette From Image in Python

To know more on how to use colorgram.py, you can see here.