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

5

2
你知道“网页安全”颜色现在并不重要了,对吧?而且它们一开始也没有那么重要。我敢打赌,你放在这里的维基百科链接也解释了这一点。 - Andrew Barber
1
我认为这个一般任务很有趣(谁在乎颜色是否来自“Web安全”调色板?)-第一步是找出:“如何计算两个RGB值之间的差异(以及使用什么度量标准)?” 一旦定义了这样的差异函数,这个任务就可以轻松地通过映射和排序来解决(这非常无聊)。 - user2864740
1
color difference开始,就可以看出设计这样一个差异函数有多么复杂!(而且这也与设备和颜色空间有关。)无论如何,有了这些新的搜索词,应该能够更好地探索。祝你好运! - user2864740
例如,参见https://dev59.com/y2445IYBdhLWcg3wpb8P - user2864740
1
与其他调色板不同,Web 安全颜色不需要任何复杂的比较算法,因为每个通道只是 51 的倍数。因此,您可以取自己颜色的通道,然后执行 R = Round( ( R / 255 ) * 5 ) * 51。快速简单的跨平台颜色量化。这就是所谓的“不再重要”的全部内容!;-) - Beejor
3个回答

9

尽管有点名称不准确,但Web安全调色板确实非常有用于颜色量化。它简单、快速、灵活且普及广泛。它还允许使用RGB十六进制简写,例如#369而不是#336699。以下是步骤:

  1. Web safe colors are RGB triplets, with each value being one of the following six: 00, 33, 66, 99, CC, FF. So we can divide the max RGB value 255 by five (one less than the total possible values) to get a multiple value, 51.
  2. Normalize the channel value by dividing by 255 (this makes it a value from 0-1 instead of 0-255).
  3. Multiply by 5, and round the result to make sure it stays exact.
  4. Multiply by 51 to get the final web safe value. All together, this looks something like:

    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)
    

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


非常感谢您提供如此有用且有效的方法!我已将您的通用代码描述翻译成了Python函数。然而,标记似乎无法正常工作。 - Simon Steinberger
@SimonSteinberger:Markdown 的问题在于,如果要在有序列表中插入代码块,我们需要输入 8 个空格而不是 4 个。:-/ - 0x2b3bfa0

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维树


2
任意调色板的绝佳解决方案。 - Simon Steinberger

0

您可以使用colorir来实现:

>>> from colorir import Palette
>>> css = Palette.load("css")
>>> web_safe = css.most_similar("fe0000") # input can be in any format
>>> web_safe
HexColor(#ff0000)

如果您需要它的名称:
>>> css.get_names(web_safe)
['red']

如果您需要RGB格式:

>>> web_safe.rgb()
sRGB(255, 0, 0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接