# Python implements the method of finding the closest color to a given color from a set of colors _python

Source: Internet
Author: User

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)

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.