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

Linda Hamilton
Release: 2024-11-01 18:01:02
Original
321 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

Actual colour name: None , closest colour name: cadetblue
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!