将RGB颜色转换为调色板中最接近的颜色

将RGB颜色转换为调色板中最接近的颜色

本文介绍了将RGB颜色转换为调色板中最接近的颜色(网络安全色)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将RGB/十六进制格式的颜色转换为最接近的网络安全颜色.

I want to convert a color either in RGB/Hex format to its nearest web-safe color.

有关网络安全色的详细信息可以在这里找到: http://en.wikipedia.org/wiki/Web_safe_color

Details about a websafe color can be found here: http://en.wikipedia.org/wiki/Web_safe_color

此网站( http://www.colortools.net/color_make_web-safe.html)可以按照我想要的方式进行操作,但是我不确定如何在Python中进行操作.有人可以帮我吗?

This website(http://www.colortools.net/color_make_web-safe.html) is able to do the way I want to, but I am not sure how to go about it in Python. Can anyone help me out here?

推荐答案

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

Despite being somewhat of a misnomer, the web safe color palette is indeed quite useful for color quantization. It's simple, fast, flexible, and ubiquitous. It also allows for RGB hex shorthand such as #369 instead of #336699. Here's a walkthrough:

  1. 网络安全色是RGB三胞胎,每个值是以下六个值之一:00, 33, 66, 99, CC, FF.因此,我们可以将最大RGB值255除以五(比可能的总值小一),以得到多个值51.
  2. 通过除以255标准化通道值(这使它成为0-1而不是0-255的值).
  3. 乘以5,然后对结果取整以确保其精确.
  4. 乘以51以获得最终的Web安全值.总之,这看起来像:

  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)

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

No need to go crazy comparing colors or creating huge lookup tables, as others have suggested. :-)

这篇关于将RGB颜色转换为调色板中最接近的颜色(网络安全色)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:41