Predictive Hacks

How to use RGB color codes as features in Machine Learning Models with Python

RGB code to names

The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. These codes are a combination of three values from 0-255 and that’s why this makes it difficult to use them as features.

One way to deal with it is to transform the RGB codes to “labels” therefore, to find the closest color name exists. The biggest color space with names we know is the webcolors which it’s containing 140 different colors. These are enough to make sure that the color name will describe the RGB value with high precision.


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())]

Examples

RGB CODE: 102, 153, 255
closest_colour([102, 153, 255])
'cornflowerblue'

RGB CODE: 255, 0, 102
closest_colour([255, 0, 102])
'deeppink'


Sources :
wikipedia
Stackoverflow

Share This Post

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

2 thoughts on “How to use RGB color codes as features in Machine Learning Models with Python”

  1. That is very fascinating, You’re an excessively professional blogger.
    I have joined your rss feed and stay up for looking for more of your excellent
    post. Also, I’ve shared your web site in my social networks

    Reply

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s