Convert RGB color to English color name, like 'green' with Python

后端 未结 4 638
再見小時候
再見小時候 2020-11-30 19:39

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

>>> im = Image.open(\"test.jpg\")
>>> n, color = max(im.getcol         


        
4条回答
  •  独厮守ぢ
    2020-11-30 20:33

    For those who, like me, want a more familiar colour name, you can use the CSS 2.1 colour names, also provided by webcolors:

    • aqua: #00ffff
    • black: #000000
    • blue: #0000ff
    • fuchsia: #ff00ff
    • green: #008000
    • grey: #808080
    • lime: #00ff00
    • maroon: #800000
    • navy: #000080
    • olive: #808000
    • purple: #800080
    • red: #ff0000
    • silver: #c0c0c0
    • teal: #008080
    • white: #ffffff
    • yellow: #ffff00
    • orange: #ffa500

    Just use fraxel's excellent answer and code for getting the closest colour, adapted to CSS 2.1:

    def get_colour_name(rgb_triplet):
        min_colours = {}
        for key, name in webcolors.css21_hex_to_names.items():
            r_c, g_c, b_c = webcolors.hex_to_rgb(key)
            rd = (r_c - rgb_triplet[0]) ** 2
            gd = (g_c - rgb_triplet[1]) ** 2
            bd = (b_c - rgb_triplet[2]) ** 2
            min_colours[(rd + gd + bd)] = name
        return min_colours[min(min_colours.keys())]
    

提交回复
热议问题