No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Convert RGB Values to CSS3 Color Names in Python

by Khaleel O.
June 4, 2022
in Python
Reading Time: 4 mins read
A A
python convert rgb color name
python convert rgb color name

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:

  1. We import the webcolors library which we installed earlier as well as the literal_eval method.
  2. 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
  3. 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
  4. 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! 👌👌👌

Tags: colorrbg
Previous Post

Coca-Cola Logo Pixel Art in Python

Next Post

Extract Pixel RGB Color Values In Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy