Predictive Hacks

Most Dominant Color of an Image

dominant colors python

When we build machine learning models on Images, apart from the image labels, we want also to get the color of them, usually as categorical variable. For that reason, we need to convert the RGB pixels into color labels.

How to get the name of the most dominant colors

The logic is to iterate over all image pixels and to get their labels. Then, based on the frequency, we will get the n most frequent color names.

import PIL
from PIL import Image
import requests
from io import BytesIO
import webcolors
import pandas as pd


# read images from URL
url = "https://www.fantasy-milos.com/slider/69/slider_image.jpg"
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img
Most Dominant Color of an Image 1

This is the function which converts an RGB pixel to a color name

import webcolors
 
def closest_colour(requested_colour):
    min_colours = {}
    for key, name in webcolors.css3_hex_to_names.items():
        r_c, g_c, b_c = webcolors.hex_to_rgb(key)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]

Now let’s write a function which takes as an input the image and returns the top n colors plus their corresponding weights/proportions in the image.

def top_colos(image, n):
    # convert the image to rgb
    image = image.convert('RGB')
    
    # resize the image to 300 x 300
    image = image.resize((300,300))
    
    detected_colors =[]
    for x in range(image.width):
        for y in range(image.height):
            detected_colors.append(closest_colour(image.getpixel((x,y))))
    Series_Colors = pd.Series(detected_colors)
    output=Series_Colors.value_counts()/len(Series_Colors)
    return(output.head(n))


top_colos(img,10)
steelblue         0.107411
lightseagreen     0.103100
cornflowerblue    0.089833
royalblue         0.077656
darkcyan          0.067311
dimgrey           0.060656
darkslategrey     0.046433
lightslategrey    0.042911
gray              0.042200
darkgrey          0.040644

As we can see the top 3 dominant colors are the “steelblue” (10.74%), “lightseagreen” (10.3%) and “cornflowerblue” (8.98%)!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

1 thought on “Most Dominant Color of an Image”

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore