This example describes a Python implementation that finds the closest color to a given color from a set of colors. Share to everyone for your reference. The specific analysis is as follows:
This code is very useful, you can find a color similar to the specified color, such as a set of 8 colors, now given an RGB format of the demo, find out which is the closest to the 8 colors, if you need to do a search image color according to the image of the program, this is very useful.
Copy the Code code as follows:
From Colorsys import RGB_TO_HSV
colors = Dict ((
(196, 2, Wuyi), "RED"),
(255, 165, 0), "ORANGE"),
(255, 205, 0), "YELLOW"),
(0, 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 the color vectors in HSV space" "
return sum ((a) **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 ' colors '" ""
return min (# overal best are 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)
Hopefully this article will help you with Python programming.