A Simple Guide to Extract Image Main Colors and Their Proportions Using Python – Python Tutorial

By | August 30, 2020

In this tutorial, we will use python colorgram.py library to extract main colors and calculate their proportions from an image, this is very helpful for us to analysis images by their colors.

main color and their proportion

Install colorgram.py

pip install colorgram.py

Set an image

import colorgram
image_file = 'e:\\webp image tutorials and examples.png'

Set main color number

main_color_num = 20

This number is determined by your need.

Extract color information from image

colors = colorgram.extract(image_file, main_color_num)

Get main color rgb and there proportions

color_list = [(color.rgb, color.proportion) for color in colors]

The output is:

[(Rgb(r=51, g=51, b=49), 0.19666978936871052), (Rgb(r=193, g=223, b=227), 0.15503711986139232), (Rgb(r=131, g=175, b=187), 0.13220110201162452), (Rgb(r=62, g=111, b=123), 0.10343195027852488), (Rgb(r=38, g=50, b=42), 0.07139907124797276), (Rgb(r=17, g=46, b=57), 0.06395495250470924), (Rgb(r=73, g=92, b=83), 0.05699434891662385), (Rgb(r=210, g=226, b=224), 0.03742205836430852), (Rgb(r=86, g=84, b=76), 0.031912000241757575), (Rgb(r=223, g=220, b=215), 0.029413838606670493), (Rgb(r=164, g=203, b=210), 0.016923030431235078), (Rgb(r=10, g=86, b=107), 0.016479808205655113), (Rgb(r=142, g=164, b=155), 0.01587541426168243), (Rgb(r=79, g=147, b=163), 0.014908383951326142), (Rgb(r=166, g=164, b=155), 0.013770108690177592), (Rgb(r=64, g=68, b=52), 0.013165714746204909), (Rgb(r=52, g=49, b=51), 0.009700522800761537), (Rgb(r=100, g=168, b=44), 0.009227080877982937), (Rgb(r=52, g=71, b=60), 0.008048512687236208), (Rgb(r=109, g=183, b=25), 0.003465191945443373)]

About Color Object:

Color.rgb – The color represented as a namedtuple of RGB from 0 to 255, e.g. (r=255, g=151, b=210).
Color.hsl – The color represented as a namedtuple of HSL from 0 to 255, e.g. (h=230, s=255, l=203).
Color.proportion – The proportion of the image that is in the extracted color from 0 to 1, e.g. 0.34.

Leave a Reply