Let’s convert RGB values to CSS3 Color Names in Python. We are using Python 3.8.10. Let’s go! ✨✨
First let’s install the webcolors library, which allows us to work with HTML/CSS colors. We also import the AST (Abstract Syntax Tree) library which gives us access to the literal_eval method:
pip install webcolors
pip install AST
The RGB (red, green, blue) color triplet in Python is represented as a 3-integer tuple, each with a value between 0 and 255 inclusive. The first number is the value forred, the second forgreenand the third forbluebecause in the RGB system all visible colors can be reproduced using different combinations of these colors.
For example, the RGB value for color black will be (0,0,0), for white it will be (255,255,255) and gold will be (255,195,3).
Our program will accept an RGB tuple value and return the corresponding color name or its nearest match. The color name is a readable english word that corresponds to the RGB tuple value. Find a full list of color names HERE.
Now, let’s write our code:
import webcolors
from ast import literal_eval
def est_color(requested_color):
min_colors = {}
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_color[0]) ** 2
gd = (g_c - requested_color[1]) ** 2
bd = (b_c - requested_color[2]) ** 2
min_colors[(rd + gd + bd)] = name
return min_colors[min(min_colors.keys())]
def get_color_name(rgb_color):
try:
closest_color_name = actual_color_name = webcolors.rgb_to_name(rgb_color)
except ValueError:
closest_color_name = est_color(rgb_color)
actual_color_name = None
return actual_color_name, closest_color_name
print("Enter RGB triplet e.g (255,128,55): ")
rgb_color = input()
rgb_color = literal_eval(rgb_color)
actual_color_name, closest_color_name = get_color_name(rgb_color)
print ("Actual color name:", actual_color_name, ", closest color name:", closest_color_name)
#output
#Enter RGB triplet e.g (255,128,55):
#(25,255,40)
#Actual color name: None , closest color name: lime
Let’s explain what is happening here:
- We import the webcolors library which we installed earlier as well as the literal_eval method.
- We define the est_color() function that will accept one parameter called requested_color and return an estimated value for the color name. We prepare this function for situations when the RGB value doesn’t have an exact corresponding color name, which would be the case for many RGB values.
- method webcolors.CSS3_HEX_TO_NAME is a dictionary containing the hex value and color names of the 147 named CSS3 colors which you can find HERE.
- method webcolors.hex_to_rgb converts a hex value to an RGB triplet
- our loop will find and return the CSS3 color name that most closely matches requested_color
- We define get_color_name() which accepts an RGB tuple and returns two values: actual_color_name and closest_color_name.
- The webcolors.rgb_to_name() method accepts our RGB tuple and returns the corresponding color name if it exists.
- We enclose the logic in a try…except structure because the RGB value may not have an exact match, in which case we invoke the function est_color() previously defined
- If a match is found, both return values will be the same, if not, they will be different
- In the main body, we prompt the user for an RGB value, which must be input in the correct format.
- We use literal_eval() to convert the string literal to a proper tuple data type.
- We pass the proper tuple inputted by the user as rgb_color to the previously defined get_color_name() function which returns the values we are looking for
When the above code executes you will be prompted for an RGB value, which should be input in the correct format. The program will then return the actual corresponding color name (if it exists, else None) and its nearest match.
See how easy that was? Thanks for reading! 👌👌👌