Home  >  Article  >  Web Front-end  >  How to Convert RGB Color to English Color Name in Python?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 15:08:021000browse

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>

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>

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>

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>

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!

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