简体   繁体   中英

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.

The 'nearest' color I defined to be the one, where the distance of their R G and B values is the lowest. 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.

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 . Thus, you current solution will always say that a color is closest to whichever of the colors has the lowest brightness .

A simple solution to this would be to instead use Euclidean distance: 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. 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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