The example in this article describes how the Python implementation finds the closest color to a given color in a set of colors. Share to everyone for your reference. The specific analysis is as follows:
This piece of 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 demo, find out which one of the 8 colors in the closest, if you need to do a picture of the color to search the program, this is very useful.
Copy 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, 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 to x in color]) #rgb_to_hsv wants floats!
def color_dist (C1, C2):
"" "Returns the squared Euklidian distance between two color vectors in HSV spaces" "
return sum ((a-b) **2 to 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 be 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 your Python programming.