How about converting them into RGB and find the dominatant color?
For example
RED FF0000 rgb(255,0,0)
BLUE 0000FF rgb(0,0,255)
steelblue 4A7DAC rgb(74,125,172)
You can most likely achieve this target with the RGB rather than the HEX
The rest you can see this algo: https://stackoverflow.com/a/9018100/6198978
EDIT
The thing is RGB and HEX calculation will not be able to work with Grey color as every color just has closest distance to the grey. For that purpose you can use the HSV values of the color, I am editing the code with the HSV implemented as well :D
Learned alot :D
I was having fun with it here you go:
import math
colors= {
"red":"#FF0000",
"yellow":"#FFFF00",
"green":"#008000",
"blue":"#0000FF",
"black":"#000000",
"white":"#FFFFFF",
"grey": "#808080"
}
# function for HSV TAKEN FROM HERE: https://gist.github.com/mathebox/e0805f72e7db3269ec22
def rgb_to_hsv(r, g, b):
r = float(r)
g = float(g)
b = float(b)
high = max(r, g, b)
low = min(r, g, b)
h, s, v = high, high, high
d = high - low
s = 0 if high == 0 else d/high
if high == low:
h = 0.0
else:
h = {
r: (g - b) / d + (6 if g < b else 0),
g: (b - r) / d + 2,
b: (r - g) / d + 4,
}[high]
h /= 6
return h, s, v
# COLOR YOU WANT TO TEST TESTED
check = "#808000".lstrip('#')
checkRGB = tuple(int(check[i:i+2], 16) for i in (0, 2 ,4))
checkHSV = rgb_to_hsv(checkRGB[0], checkRGB[1], checkRGB[2])
colorsRGB = {}
colorsHSV = {}
for c, v in colors.items():
h = v.lstrip('#')
colorsRGB[c] = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
for c, v in colorsRGB.items():
colorsHSV[c] = tuple(rgb_to_hsv(v[0], v[1], v[2]))
def colourdistanceRGB(color1, color2):
r = float(color2[0] - color1[0])
g = float(color2[1] - color1[1])
b = float(color2[2] - color1[2])
return math.sqrt( ((abs(r))**2) + ((abs(g))**2) + ((abs(b))**2) )
def colourdistanceHSV(color1, color2):
dh = min(abs(color2[0]-color1[0]), 360-abs(color2[0]-color1[0])) / 180.0
ds = abs(color2[1]-color1[1])
dv = abs(color2[2]-color1[2]) / 255.0
return math.sqrt(dh*dh+ds*ds+dv*dv)
resultRGB = {}
resultHSV = {}
for k, v in colorsRGB.items():
resultRGB[k]=colourdistanceRGB(v, checkRGB)
for k,v in colorsHSV.items():
resultHSV[k]=colourdistanceHSV(v, checkHSV)
#THIS WILL NOT WORK FOR GREY
print("RESULT WITH RGB FORMULA")
print(resultRGB)
print(min(resultRGB, key=resultRGB.get))
#THIS WILL WORK FOR EVEN GREY
print(resultHSV)
print(min(resultHSV, key=resultHSV.get))
#OUTPUT FOR RGB
#check = "#808000" output=GREY
#check = "#4A7DAC" output=GREY :D
#OUTPUT FOR RGB
#check = "#808000" output=GREEN
#check = "#4A7DAC" output=BLUE:D