How to Convert RGB Color to English Color Name in Python?

Patricia Arquette
Release: 2024-10-30 15:08:02
Original
1026 people have browsed it

How to Convert RGB Color to English Color Name in Python?

Convert RGB Color to English Color Name in Python

Given a tuple of RGB values, you may want to convert it to a human-readable English color name. How can this be accomplished using Python?

Solution

To convert an RGB color to its corresponding English color name, consider using the webcolors library. It offers the rgb_to_name() function, which takes an RGB triplet as input and returns the normalized color name if a match exists.

Example

<code class="python">import webcolors

# Get RGB color from an image
im = Image.open("test.jpg")
n, color = max(im.getcolors(im.size[0]*im.size[1]))

# Convert to English color name
color_name = webcolors.rgb_to_name(color, spec='css3')
print(color_name)  # Output: 'cadetblue'</code>
Copy after login

Closest Color Name

If a perfect match is not found, you can find the closest color name using the following code:

<code class="python">def closest_colour(requested_colour):
    # Iterate through RGB space and calculate Euclidian distance
    min_distances = {}
    for hex_code, name in webcolors.CSS3_HEX_TO_NAMES.items():
        r, g, b = webcolors.hex_to_rgb(hex_code)
        dist = sum((n - c for n, c in zip(requested_colour, (r, g, b))))**2
        min_distances[dist] = name

    # Return the closest color name
    return min_distances[min(min_distances.keys())]</code>
Copy after login

Complete Function

To handle both cases, you can define a function that returns the actual and closest color names:

<code class="python">def get_colour_name(requested_colour):
    try:
        closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
    except ValueError:
        closest_name = closest_colour(requested_colour)
        actual_name = None

    return actual_name, closest_name</code>
Copy after login

Sample Usage

<code class="python">color = (119, 172, 152)
actual_name, closest_name = get_colour_name(color)
print("Actual:", actual_name, ", Closest:", closest_name)</code>
Copy after login

Output

Actual: None, Closest: cadetblue

The above is the detailed content of How to Convert RGB Color to English Color Name in 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!