Python implements a method that finds the closest color to a given color from a set of colors

Source: Internet
Author: User
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.

  • Related Article

    Contact Us

    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.