Python finds the nearest color from a set of colors.

Source: Internet
Author: User

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.

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.