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
closest_colour([102, 153, 255])
'cornflowerblue'
closest_colour([255, 0, 102])
'deeppink'
Sources :
wikipedia
Stackoverflow
2 thoughts on “How to use RGB color codes as features in Machine Learning Models with Python”
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