>> n, color = max(im.getcolors(im.size[0-6ren">
gpt4 book ai didi

python - 将RGB颜色转换为英文颜色名称,如Python 'green'

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:48 25 4
gpt4 key购买 nike

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

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

在 python 中有没有简单的方法来做到这一点?

最佳答案

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

rgb_to_name(rgb_triplet, spec='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.

Example:

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

反之亦然:

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

#找到最接近的颜色名称:

但是 webcolors 会在找不到与请求的颜色匹配的情况下引发异常。我编写了一个小修复程序,为请求的 RGB 颜色提供最接近的匹配名称。它在 RGB 空间中按欧氏距离匹配。

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

关于python - 将RGB颜色转换为英文颜色名称,如Python 'green',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com