如何确定十六进制代码的主要,二级或三级颜色?

时间:2016-11-30 06:03:17

标签: python colors

我想写一些代码,这些代码可以采用十六进制颜色并准确猜出它的主要,二级或三级颜色。

例如,如果我输入#0000FF#002FA7#004950,则会返回blue。 (我不希望它返回AquaBlueCoboltNavy之类的内容,而是简单的颜色blue)。

2 个答案:

答案 0 :(得分:0)

您可以使用简单的python函数对其进行分类。黑色和白色(#000000#FFFFFF)等颜色必须根据您的要求修改功能。因为它为rgb保留了相同的值。

该函数将hex转换为rgb值并取最大值并根据该值进行分类。

def hex_to_rgb(value):
        value = value.lstrip('#')
        lv = len(value)
        colors = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
        pri_colrs = ['Red','Green','Blue']
        return pri_colrs[colors.index(max(colors))]

<强>结果

In [33]: hex_to_rgb('#002FA7')
Out[33]: 'Blue'
In [34]: hex_to_rgb('#0000FF')
Out[34]: 'Blue'
In [35]: hex_to_rgb('#004950')
Out[35]: 'Blue'

答案 1 :(得分:0)

这是一个开始 -

假设字符串c = '#004950'是十六进制RGB颜色。

定义一些切片以分隔rgb值

>>> red = slice(1,3)
>>> blue = slice(3,5)
>>> green = slice(5, 7)

你需要找到幅度 - 我将使用一个函数并将其映射到rgb值

>>> def f(s):
    return int(n, base = 16)
>>> rgb = map(f, (c[red], c[green], c[blue]))

现在我们需要知道哪个具有最高的幅度:

>>> # a couple more helpers
>>> from operator import itemgetter
>>> color = itemgetter(0)
>>> value = itemgetter(1)
>>> 
>>> colors = zip(['red', 'green', 'blue'], rgb)
>>> colors = sorted(colors, key = value)
>>> tertiary, secondary, primary = map(color, colors)
>>> primary, secondary, tertiary
('blue', 'green', 'red')
>>>