Home  >  Article  >  Web Front-end  >  How to Convert RGB Colors to English Color Names with Python?

How to Convert RGB Colors to English Color Names with Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 18:01:02306browse

How to Convert RGB Colors to English Color Names with Python?

Convert RGB Colors to English Color Names with Python

With the task of transforming RGB color tuples into comprehensive English color names, there's a Python module that holds the solution: webcolors.

webcolors' rgb_to_name() function provides a direct conversion path, as seen in its example:

<code class="python">>>> rgb_to_name((0, 0, 0))
'black'</code>

However, when an exact match is not found, webcolors raises an exception. To handle this, we've crafted a workaround that retrieves the nearest matching color name. This solution employs the following steps:

  1. Convert RGB color to hex value (using the dechex() function)
  2. Calculate Euclidean distance between the requested color and all web colors
  3. Return the closest matching color

For example:

<code class="python">requested_colour = (119, 172, 152)
actual_name, closest_name = get_colour_name(requested_colour)
print("Actual colour name:", actual_name, ", closest colour name:", closest_name)</code>

Output:

Actual colour name: None , closest colour name: cadetblue

This approach ensures that even when an exact match isn't available, you receive the closest possible English color name.

The above is the detailed content of How to Convert RGB Colors to English Color Names with Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn