将RGB颜色转换为调色板中最接近的颜色(Web安全颜色)?

mee*_*mee 3 python colors python-imaging-library

我想将RGB/Hex格式的颜色转换为最接近的Web安全颜色.

有关网页安全颜色的详细信息,请访问:http://en.wikipedia.org/wiki/Web_safe_color

这个网站(http://www.colortools.net/color_make_web-safe.html)能够以我想要的方式进行,但我不确定如何在Python中实现它.有人可以帮我从这里出去吗?

Bee*_*jor 5

尽管有点用词不当,但网页安全调色板对于颜色量化确实非常有用.它简单,快速,灵活,无处不在.它还允许使用RGB十六进制速记#369代替#336699.这是一个演练:

  1. Web安全颜色是RGB三元组,每个值都是以下六个中的一个:00, 33, 66, 99, CC, FF.因此,我们可以将最大RGB值255除以5(比可能的总值少一个)来得到一个多值,51.
  2. 通过除以255(这使得它成为一个值0-1而不是0-255)来规范化通道值.
  3. 乘以5并舍入结果以确保其保持精确.
  4. 乘以51得到最终的网络安全值.总之,这看起来像:

    def getNearestWebSafeColor(r, g, b):
        r = int(round( ( r / 255.0 ) * 5 ) * 51)
        g = int(round( ( g / 255.0 ) * 5 ) * 51)
        b = int(round( ( b / 255.0 ) * 5 ) * 51)
        return (r, g, b)
    
    print getNearestWebSafeColor(65, 135, 211)
    
    Run Code Online (Sandbox Code Playgroud)

正如其他人所建议的那样,无需疯狂地比较颜色或创建巨大的查找表.:-)


Pyl*_*lyp 2

import scipy.spatial as sp

input_color = (100, 50, 25)
websafe_colors = [(200, 100, 50), ...] # list of web-save colors
tree = sp.KDTree(websafe_colors) # creating k-d tree from web-save colors
ditsance, result = tree.query(input_color) # get Euclidean distance and index of web-save color in tree/list
nearest_color = websafe_colors[result]
Run Code Online (Sandbox Code Playgroud)

或者添加几个input_colors的循环

关于k维树

  • 任意调色板的绝佳解决方案。 (2认同)