Status: I am developing my own library
Question:
Is there any library that can do color classification?
I imagine the workflow like this:
>>> import colorclassification
>>> classifier = colorclassification.Classifier
>>> color = classifier.classify_rgb([255, 255, 0])
['yellow']
>>> color = classifier.classify_rgb([255, 170, 0])
['orange']
The library must not necessarily be for python. Any language where I can view the source code of the module/library will do fine.
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))
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With