One way you could do this is just by finding the "closest" color. suppose we have a collection of colors, It doesn't have to cover all 16777216 possible rgb values, it doesn't even need to be in rgb, but for the sake of simplicity, it might look something like so:
colors = {'red': (255,0,0),
'green': (0,255,0),
'blue': (0,0,255),
'yellow': (255,255,0),
'orange': (255,127,0),
'white': (255,255,255),
'black': (0,0,0),
'gray': (127,127,127),
'pink': (255,127,127),
'purple': (127,0,255),}
Lets define a mechanism that tells us what we really mean by "closest" color. In this case, i'll use a simple cartesian distance, but anything that can compare two colors for how similar they are will do.
def distance(left, right):
return sum((l-r)**2 for l, r in zip(left, right))**0.5
class NearestColorKey(object):
def __init__(self, goal):
self.goal = goal
def __call__(self, item):
return distance(self.goal, item[1])
And that's actually all we need. We can use the builtin min()
(or max if your similarity function returns higher values for more similar colors)
>>> min(colors.items(), key=NearestColorKey((10,10,100)))
('black', (0, 0, 0))
>>> min(colors.items(), key=NearestColorKey((10,10,200)))
('blue', (0, 0, 255))
>>> min(colors.items(), key=NearestColorKey((100,10,200)))
('purple', (127, 0, 255))
>>>