Search code examples
c++opencvcolorsmetric

Simple metric for difference of color in OpenCV?


I have two cv::Scalar objects and I want to calculate the color difference.

I came up with this code:

cv::Scalar a(255, 128, 255); // color 1
cv::Scalar b(100, 100, 100); // color 2

cv::Scalar d = b - a;
double distance = sqrtl(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);

This looks rather clumsy. Is there a simpler way to express this or another metric, e.g. a way to express the dot product d*d, or a way to say directly distance of two cv::Scalar, or cv::Vec4i, to which it can be casted afaik?


Solution

  • As suggested by @IwillnotexistIdonotexist, you can use the Vec class and according norm():

    cv::Vec4d d = a-b;
    double distance = cv::norm(d);