Given an RGB value what would be the best way to find the closest match in the database?

前端 未结 8 1581
别跟我提以往
别跟我提以往 2020-12-04 17:02

I have a rgb value and if it doesn\'t exist in the color table in my database I need to find the closest color. I was thinking of comparing all values and finding the diffe

相关标签:
8条回答
  • 2020-12-04 17:33

    The following does exactly what you describe:

    select (abs(my_R - t.r) + abs(my_G - t.g) + abs(my_B - t.b)) / 3 as difference, t.*
    from RGBtable t
    order by difference desc;
    

    However, you might get better results with something that was non-linear. In the "take the averages" approach, if you goal color is (25, 25, 25) the color (45, 25, 25) would be closer than (35, 35, 35). However, I bet the second would actually look closer, since it would also be gray.

    A few ideas come to mind: you could try squaring the differences before you average them. Or you could do something complicated with finding the color with the closest ratio between the different values. Finding the closest ratios would get you closest to the right hue, but won't account for saturation (if I'm remembering the terms right...)

    0 讨论(0)
  • 2020-12-04 17:35

    The Euclidean distance difference = sqrt(sqr(red1 - red2) + sqr(green1 - green2) + sqr(blue1 - blue2)) is the standard way to determine the similarity of two colours.

    However, if you have your colours in a simple list, then to find the nearest colour requires computing the distance from the new colour with every colour in the list. This is an O(n) operation.

    The sqrt() is an expensive operation, and if you're just comparing two distances then you can simply omit the sqrt().

    If you have a very large palette of colours, it is potentially quicker to organise the colours into a kd tree (or one of the alternatives) so as to reduce the number of diffreences that require computing.

    0 讨论(0)
提交回复
热议问题