开发者

Color classification library [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It 开发者_如何学JAVAis not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 8 years ago.

Improve this question

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))
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜