Simple metric for difference of color in OpenCV?
Asked Answered
I

1

6

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?

Iatrogenic answered 1/10, 2014 at 0:15 Comment(5)
The difference between two colours is in fact a complicated topic. Are you sure you're looking for the Euclidean distance between two (RGB) colours? If you're actually looking for the perceptual difference (the difference in colour as perceived by a human), a better solution for you would be to convert your colours to the CIE Lab colour space, which is designed s.t. the Euclidean distance between two colours is better correlated to the actual perceptual distance.Kalpa
@IwillnotexistIdonotexist thank you for the hint. I will consider CIE Lab if I do not get good results with RGB. Meanwhile, it's more about writing the formula. Once I've converted to Lab space, will I have to calculate an euclidean distance in the Lab space or is there another formula?Iatrogenic
I believe it is indeed the Euclidean distance. Wikipedia claims that a Euclidean distance of approximately 2.3 constitutes a JND (Just-Noticeable Difference).Kalpa
The documentation for OpenCV alleges the existence of a norm() function for Vec's.... docs.opencv.org/modules/core/doc/basic_structures.html#vecKalpa
For the benefit of other people - those looking for a complicated metric for color difference, the following Wikipedia articles will be useful: (1) Color difference (2) MacAdam ellipse.Inalienable
P
8

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

cv::Vec4d d = a-b;
double distance = cv::norm(d);
Plea answered 1/10, 2014 at 4:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.