简体   繁体   中英

How can I determine the primary, secondary or tertiary color of a hex code?

I want to write some code which can take a hex color and accurately guess its primary, secondary or tertiary color.

For example, if I input #0000FF , or #002FA7 , or #004950 it would return blue . (I don't want it to return things like AquaBlue or Cobolt or Navy , but rather the simple color blue ).

You can use simple python function to classify that. The colors like black and white ( #000000 and #FFFFFF ) you have to modify the function according to your requirements. Because it's hold the same values for rgb .

The function convert hex to rgb values and take the maximum value and classify according to that.

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))]

Results

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'

Here is a start -

Say the string c = '#004950' is a hex RGB color.

Define some slices to separate the rgb values

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

You need to find the magnitudes - I'll use a function and map it to the rgb values

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

Now we need to know which has the highest magnitude:

>>> # 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')
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM