Which is most accurate way to distinguish one of 8 colors?

后端 未结 6 767
星月不相逢
星月不相逢 2021-02-09 06:00

Imagine we how some basic colors:

RED = Color ((196, 2, 51), \"RED\")
ORANGE = Color ((255, 165, 0), \"ORANGE\")
YELLOW = Color ((255, 205, 0), \"YELLOW\")
GREEN         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 06:24

    Use rgb_to_hsv to convert. Then match the color with the closet hue

    For your example it would be RED because the hue matches exactly

    >>> from colorsys import rgb_to_hsv
    >>> rgb_to_hsv(192,2,51)
    (0.83333333333333337, 0, 192)
    >>> rgb_to_hsv(206, 17, 38)
    (0.83333333333333337, 0, 206)
    >>> 
    

    Here's an example of how to find the closest match

    >>> from colorsys import rgb_to_hsv
    >>> 
    >>> colors = dict((
    ...     ((196, 2, 51), "RED"),
    ...     ((255, 165, 0), "ORANGE"),
    ...     ((255, 205, 0), "YELLOW"),
    ...     ((0, 128, 0), "GREEN"),
    ...     ((0, 0, 255), "BLUE"),
    ...     ((127, 0, 255), "VIOLET"),
    ...     ((0, 0, 0), "BLACK"),
    ...     ((255, 255, 255), "WHITE"),))
    >>> 
    >>> color_to_match = (206,17,38)
    >>> 
    >>> print min((abs(rgb_to_hsv(*k)[0]-rgb_to_hsv(*color_to_match)[0]),v) for k,v in colors.items())
    (0.0, 'RED')
    

提交回复
热议问题