RGB to Color Names in Python — The Robust Way

A simple function to convert RGB values into color names for a variety of combinations.

Mir AbdulHaseeb
CodeX
2 min readJan 3, 2021

--

Photo by Rohit Raj on Unsplash

It’s a fairly simple problem and there is a library for Python called webcolors to solve it. We can use the rgb_to_name function which takes RGB values as a parameter and returns the name of the color they represent. Let’s see it in action:

from webcolors import rgb_to_name
named_color = rgb_to_name((255,0,0), spec='css3')
print(named_color)

Output:

red

This works fine. But let’s see if it can handle some random combination of RGB values. Let’s try for (190,53,25).

named_color = rgb_to_name((190,53,25), spec='css3')print(named_color)

The above code throws an error:

ValueError: '#960000' has no defined color name in css3.

It’s telling us that the combination of RGB values we gave doesn’t map to any Hex code available in css3. In other words, when the function converts the decimal values into CSS hex code, it doesn’t find an exact match for the color name associated with it. Let’s take a look at some RGB values with their hex code and color names to make it clear:

  • RGB →(0.255.0), Hex Code →#00FF00, Color Name →lime
  • RGB →(178,34,34), Hex Code →#B22222, Color Name →firebrick

This actually makes sense if you are working on a project which relies on the accuracy of the colors. However, if you can make do with the nearest possible color name for the given RGB values, we can use something that finds the closest match.

Solution:

We will use a data structure called KDTree. It will look for the closest matched hex code for our given RGBs that has a color name associated to it. You can read more about KDTree here.

Code:

from scipy.spatial import KDTree
from webcolors import (
css3_hex_to_names,
hex_to_rgb,
)
def convert_rgb_to_names(rgb_tuple):

# a dictionary of all the hex and their respective names in css3
css3_db = css3_hex_to_names
names = []
rgb_values = []
for color_hex, color_name in css3_db.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))

kdt_db = KDTree(rgb_values)
distance, index = kdt_db.query(rgb_tuple)
return f'closest match: {names[index]}'

Let’s use this function to get the name of RGB (190,53,25).

print(convert_rgb_to_names((190,53,25)))

Output:

closest match: firebrick

Conclusion

We can see that the RGBs for firebrick in css3 are not far off from the ones we used. This code can be used if you need a color name for every possible RGB combination. I hope this article was helpful.

--

--