简体   繁体   English

如何将某个 RGB 值分配给 Python 中一些其他 RGB 值的“最近”值

[英]how to assign a certain RGB Value to the 'nearest' of some other RGB-Values in Python

I wrote a code which pixelates an incoming picture to a chosen pixel size.我编写了一个代码,它将传入的图片像素化为选定的像素大小。 I have a list of some RGB_color codes (tuples) and I want to check each pixel, which color the pixels color comes closest to.我有一些 RGB_color 代码(元组)的列表,我想检查每个像素,像素颜色最接近哪种颜色。

The 'nearest' color I defined to be the one, where the distance of their R G and B values is the lowest.我定义的“最近”颜色是其 R G 和 B 值的距离最低的颜色。 for example if I have only black ad white, the color (128,0,0) would be converted to black because 0-128 + 0-0 + 0-0 = distance to black and 255-128 + 255-0 + 255-0 = distance to white.例如,如果我只有黑色广告白色,颜色 (128,0,0) 将转换为黑色,因为 0-128 + 0-0 + 0-0 = 到黑色的距离和 255-128 + 255-0 + 255 -0 = 到白色的距离。

It works quite well for black, white and grey.它适用于黑色、白色和灰色。 But when I include for example red, most of the pixels that don't have any red in them are outputted as red.但是当我包括例如红色时,大多数没有任何红色的像素都会输出为红色。 Do you know any better method to declare what is the closest color?你知道有什么更好的方法来声明最接近的颜色吗?

Your current distance metric is r1-r2 + g1-g2 + b1-b2 which can be rearranged to r1+g1+b1 - (r2+g2+b2) , or if brightness=r+g+b , then the distance is brightness1 - brightness2 .您当前的距离度量是r1-r2 + g1-g2 + b1-b2可以重新排列为r1+g1+b1 - (r2+g2+b2) ,或者如果brightness=r+g+b ,那么距离是brightness1 - brightness2 Thus, you current solution will always say that a color is closest to whichever of the colors has the lowest brightness .因此,您当前的解决方案总是说颜色最接近 colors 中具有最低brightness的那个。

A simple solution to this would be to instead use Euclidean distance: sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) .一个简单的解决方案是使用欧几里得距离: sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) (Note that if all you need to do is compare distances then the square root can be omitted.) (请注意,如果您只需要比较距离,则可以省略平方根。)

However, the RGB color space is not perceptually uniform, so using Euclidean distance may give some strange-looking results.但是,RGB 颜色空间在感知上并不均匀,因此使用欧几里得距离可能会产生一些看起来很奇怪的结果。 Multiple attempts have been made to solve this problem, such as the CAM02-UCS color space - the following is an example using the colorspacious module (install using pip ) for color conversion and numpy for the Euclidean distance computation.已经进行了多次尝试来解决这个问题,例如 CAM02-UCS 颜色空间 - 以下是使用colorspacious模块(使用pip安装)进行颜色转换和 numpy 进行欧几里德距离计算的示例。

from colorspacious import cspace_convert
from numpy.linalg import norm as distance


a = cspace_convert([64, 128, 255], "sRGB255", "CAM02-UCS")
b = cspace_convert([64, 138, 255], "sRGB255", "CAM02-UCS")
c = cspace_convert([64, 148, 255], "sRGB255", "CAM02-UCS")
print('distance between a and b', distance(a-b))
print('distance between a and c', distance(a-c))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM