[Python] python从一组颜色中找出与给定颜色最接近的颜色 →→→→→进入此内容的聊天室

来自 , 2020-09-24, 写在 Python, 查看 113 次.
URL http://www.code666.cn/view/8909a6e3
  1. from colorsys import rgb_to_hsv
  2.  
  3. colors = dict((
  4. ((196, 2, 51), "RED"),
  5. ((255, 165, 0), "ORANGE"),
  6. ((255, 205, 0), "YELLOW"),
  7. ((0, 128, 0), "GREEN"),
  8. ((0, 0, 255), "BLUE"),
  9. ((127, 0, 255), "VIOLET"),
  10. ((0, 0, 0), "BLACK"),
  11. ((255, 255, 255), "WHITE"),))
  12.  
  13. def to_hsv( color ):
  14.     """ converts color tuples to floats and then to hsv """
  15.     return rgb_to_hsv(*[x/255.0 for x in color]) #rgb_to_hsv wants floats!
  16.  
  17. def color_dist( c1, c2):
  18.     """ returns the squared euklidian distance between two color vectors in hsv space """
  19.     return sum( (a-b)**2 for a,b in zip(to_hsv(c1),to_hsv(c2)) )
  20.  
  21. def min_color_diff( color_to_match, colors):
  22.     """ returns the `(distance, color_name)` with the minimal distance to `colors`"""
  23.     return min( # overal best is the best match to any color:
  24.         (color_dist(color_to_match, test), colors[test]) # (distance to `test` color, color name)
  25.         for test in colors)
  26.  
  27. color_to_match = (255,255,0)
  28. print min_color_diff( color_to_match, colors)
  29. #//python/8668

回复 "python从一组颜色中找出与给定颜色最接近的颜色"

这儿你可以回复上面这条便签

captcha