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

How to use RGB color codes as features in Machine Learning Models with Python 1
RGB CODE: 102, 153, 255
closest_colour([102, 153, 255])
'cornflowerblue'

How to use RGB color codes as features in Machine Learning Models with Python 2
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

connect with sql
R

How to Connect R with SQL

Need to Connect R with SQL It is common for Data Analysts/Scientists to connect R with SQL. For that reason,

letter frequency
Python

Document Letter Frequency in Python

Letter Frequency We will provide you a walk-through example of how you can easily get the letter frequency in documents

[the_ad_group id="232"]
[the_ad id="2133"]