Finding nearest RGB colour

前端 未结 3 569
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 03:12

I was told to use distance formula to find if the color matches the other one so I have,

struct RGB_SPACE
{
    float R, G, B;
};

RGB_SPACE p = (255, 164, 3         


        
3条回答
  •  北海茫月
    2021-01-01 04:11

    "Matches by at least 25%" is not a well-defined problem. Matches by at least 25% of what, and according to what metric? There's tons of possible choices. If you compare RGB colors, the obvious ones are distance metrics derived from vector norms. The three most important ones are:

    • 1-norm or "Manhattan distance": distance = abs(r1-r2) + abs(g1-g2) + abs(b1-b2)
    • 2-norm or Euclidean distance: distance = sqrt(pow(r1-r2, 2) + pow(g1-g2, 2) + pow(b1-b2, 2)) (you compute the square of this, which is fine - you can avoid the sqrt if you're just checking against a threshold, by squaring the threshold too)
    • Infinity-norm: distance = max(abs(r1-r2), abs(g1-g2), abs(b1-b2))

    There's lots of other possibilities, of course. You can check if they're within some distance of each other: If you want to allow up to 25% difference (over the range of possible RGB values) in one color channel, the thresholds to use for the 3 methods are 3/4*255, sqrt(3)/4*255 and 255/4, respectively. This is a very coarse metric though.

    A better way to measure distances between colors is to convert your colors to a perceptually uniform color space like CIELAB and do the comparison there; there's a fairly good Wikipedia article on the subject, too. That might be overkill depending on your intended application, but those are the color spaces where measured distances have the best correlation with distances perceived by the human visual system.

提交回复
热议问题