0

I am trying to find out if a hex color is "blue". This might be a very subjective thing when comparing different (lighter/ darker) shades of blue or close to blue colors but in my case it does not have to be very precise. I just want to determine if a color is blue or not.

The more generalized question would be, is there a way to calculate which of the "basic colors" is closest to a given hex value? Basic colors being red, blue ,green, yellow, purple, etc. without being too specific.

I am looking for an implementation or library in python but a general solution would also suffice.

Steve Melons
  • 83
  • 1
  • 7
  • You may take a look at my [following answer](https://stackoverflow.com/a/59549285/4926757). The concept is converting to LAB color space, compute euclidean distance from LAB tripletes, and finding the color with minimum distance (you may ignore the color names, and reduce the list to few basic colors). – Rotem Nov 15 '22 at 21:34

2 Answers2

1

This is a somewhat complicated question, see more discussion here: https://graphicdesign.stackexchange.com/questions/92984/how-can-i-tell-basic-color-a-hex-code-is-closest-to

I don't know of any library or implementation that already exists for this. If you really need this functionality though and don't need it to be insanely precise, what you can do is use a color table with the colors you want to classify, e.g.

    Black   #000000     (0,0,0)
    White   #FFFFFF     (255,255,255)
    Red     #FF0000     (255,0,0)
    Lime    #00FF00     (0,255,0)
    Blue    #0000FF     (0,0,255)
    Yellow  #FFFF00     (255,255,0)
    Cyan / Aqua     #00FFFF     (0,255,255)
    Magenta / Fuchsia   #FF00FF     (255,0,255)
    Silver  #C0C0C0     (192,192,192)
    Gray    #808080     (128,128,128)
    Maroon  #800000     (128,0,0)
    Olive   #808000     (128,128,0)
    Green   #008000     (0,128,0)
    Purple  #800080     (128,0,128)
    Teal    #008080     (0,128,128)
    Navy    #000080     (0,0,128)

(from https://www.rapidtables.com/web/color/RGB_Color.html)

And calculate which of these the given hex color is closest to. This isn't going to be completely accurate because of the way we perceive specific colors on the spectrum, but I don't think this problem has a general solution anyways so approximation may be the only path forward.

Tyler Aldrich
  • 386
  • 2
  • 10
-1

I mean you could do:

hex = input()    

if hex == '#0000FF':
    print('Blue')

else:
    print('Not blue') 

If that is what you are looking for.

Code Freak
  • 13
  • 6