Python finds the nearest color from a set of colors.
This example describes how to find the nearest color from a set of colors in python. Share it with you for your reference. The specific analysis is as follows:
This code is very useful. You can find a color similar to the specified color. For example, there is a group of eight colors. Now, given an rgb format demonstration, you can find out which one of the eight colors is the closest, if you need to create a program to search for images by image color, this is very useful.
Copy codeThe Code is as follows: from colorsys import rgb_to_hsv
Colors = dict ((
(196, 2, 51), "RED "),
(255,165, 0), "ORANGE "),
(255,205, 0), "YELLOW "),
(0,128, 0), "GREEN "),
(0, 0,255), "BLUE "),
(127, 0,255), "VIOLET "),
(0, 0, 0), "BLACK "),
(255,255,255), "WHITE "),))
Def to_hsv (color ):
"Converts color tuples to floats and then to hsv """
Return rgb_to_hsv (* [x/255.0 for x in color]) # rgb_to_hsv wants floats!
Def color_dist (c1, c2 ):
"Returns the squared euklidian distance between two color vectors in hsv space """
Return sum (a-B) ** 2 for a, B in zip (to_hsv (c1), to_hsv (c2 )))
Def min_color_diff (color_to_match, colors ):
"Returns the '(distance, color_name)' with the minimal distance to 'color '"""
Return min (# overal best is the best match to any color:
(Color_dist (color_to_match, test), colors [test]) # (distance to 'test' color, color name)
For test in colors)
Color_to_match = (255,255, 0)
Print min_color_diff (color_to_match, colors)
I hope this article will help you with Python programming.