Imagine we how some basic colors:
RED = Color ((196, 2, 51), "RED")
ORANGE = Color ((255, 165, 0), "ORANGE")
YELLOW = Color ((255, 205, 0), "YELLOW")
GREEN = Color ((0, 128, 0), "GREEN")
BLUE = Color ((0, 0, 255), "BLUE")
VIOLET = Color ((127, 0, 255), "VIOLET")
BLACK = Color ((0, 0, 0), "BLACK")
WHITE = Color ((255, 255, 255), "WHITE")
I want to have a function, which gets a 3-tuple as a parameter (like (206, 17, 38)), and it should return the color which it is. For instance, (206, 17, 38) is red, and (2, 2, 0) is black, and (0, 255, 0) is green.
Which is most accurate way to choose one of 8 colors?
Short answer: use the Euclidean distance in a device independent color space (source: Color difference article in Wikipedia). Since RGB is device-dependent, you should first map your colors to one of the device-independent color spaces.
I suggest to convert RGB to Lab*. To quote Wikipedia again:
Unlike the RGB and CMYK color models,Lab color is designed to approximatehuman vision.
Here's a recipe to do the conversion. Once you have the L
, a
, b
values, calculate the Euclidean distance between your color and all the reference colors and choose the closest one.
Actually, the python-colormath Python module on Google Code (under GPL v3) is capable of converting between many different color spaces and calculates color differences as well.