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

2024-10-01 13:28:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想转换一种颜色或在RGB/十六进制格式的最接近的网络安全颜色。在

有关websafe颜色的详细信息可在此处找到:http://en.wikipedia.org/wiki/Web_safe_color

这个网站(http://www.colortools.net/color_make_web-safe.html)可以按照我想要的方式来做,但是我不确定如何用Python实现它。有人能帮我吗?在


Tags: orgwebhttp网站颜色www格式wiki
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]

或为多个input_color添加循环

关于k-dimensional tree

尽管用词不当,web安全调色板确实对颜色量化非常有用。它简单、快速、灵活且无处不在。它还允许RGB十六进制速记,例如#369,而不是{}。以下是演练:

  1. Web安全颜色是RGB三元组,每个值是以下六个值之一:00, 33, 66, 99, CC, FF。因此,我们可以将最大RGB值255除以5(比总可能值小1)得到一个倍数值51。在
  2. 通过除以255来规范化通道值(这使其成为来自0-1的值,而不是{})。在
  3. 乘以5,并对结果进行四舍五入以确保它保持精确。在
  4. 乘以51得到最终的web安全值。总而言之,这看起来像:

    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)
    

没有必要像其他人建议的那样疯狂地比较颜色或创建巨大的查找表。:-)

相关问题 更多 >