Color classification library

Status: I am developing my own library


Question:

Is there a library that can do color classification?

I imagine the workflow as follows:

>>> import colorclassification >>> classifier = colorclassification.Classifier >>> color = classifier.classify_rgb([255, 255, 0]) ['yellow'] >>> color = classifier.classify_rgb([255, 170, 0]) ['orange'] 

The library does not have to be for python. Any language in which I can view the source code of the module / library will be fine.

+3
python colors
source share
1 answer

One way to do this is simply to find the “closest” color. Suppose we have a set of colors. It should not cover all 16777216 possible rgb values, it should not even be in rgb, but for simplicity it might look something like this:

 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 you define a mechanism that tells us what we really mean by the “closest” color. In this case, I will use a simple Cartesian distance, but everything that can compare the two colors for how similar they are will do.

 def distance(left, right): return sum((lr)**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 built-in 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)) >>> 
+9
source share

All Articles