将RGB颜色转换为英文颜色名称,如Python中的“green” [英] Convert RGB color to English color name, like 'green' with Python

查看:2138
本文介绍了将RGB颜色转换为英文颜色名称,如Python中的“green”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将颜色元组转换为颜色名称,例如黄色或蓝色

I want to convert a color tuple to a color name, like 'yellow' or 'blue'

>>> im = Image.open("test.jpg")
>>> n, color = max(im.getcolors(im.size[0]*im.size[1]))
>>> print color
(119, 172, 152)

在python中是否有一种简单的方法这样做?

Is there a simple way in python to do this?

推荐答案

它看起来像是 webcolors 将允许您这样做:

It looks like webcolors will allow you to do this:


rgb_to_name(rgb_triplet,spec ='css3')

rgb_to_name(rgb_triplet, spec='css3')

如果存在任何此类名称,则将适合在rgb()颜色三元组中使用的3元组整数转换为其对应的标准化颜色名称;有效值为html4,css2,css21和css3,默认值为css3。

Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to its corresponding normalized color name, if any such name exists; valid values are html4, css2, css21 and css3, and the default is css3.

示例:



>>> rgb_to_name((0, 0, 0))
'black'

它是副 - 能够:

>>> name_to_rgb('navy')
(0, 0, 128)



找到最近的颜色名称:



然而 webcolors 如果无法找到所请求颜色的匹配项,则会引发异常。我写了一个小修补程序,为请求的RGB颜色提供最接近的匹配名称。它与RGB空间中的欧几里德距离相匹配。

To find the closest colour name:

However webcolors raises an exception if it can't find a match for the requested colour. I've written a little fix that delivers the closest matching name for the requested RGB colour. It matches by Euclidian distance in the RGB space.

import webcolors

def closest_colour(requested_colour):
    min_colours = {}
    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_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]

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

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

输出:

Actual colour name: None , closest colour name: cadetblue

这篇关于将RGB颜色转换为英文颜色名称,如Python中的“green”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆