Recently, I needed to compare a number of colors to get the 2 most identical colors. This problem at the facade looks like a cake walk, even for beginners, but is a bit involved.

A naive implementation is to calculate to Euclidean distance (as shown below) between the RGB values of the 2 colors.

The 2 colors that have the lowest Euclidean Distance are then selected. But, there is a serous flaw in this assumption. Although RGB values are a convenient way to represent colors in computers, we humans perceive colors in a different way from how colors are represented in the RGB color space. What looks like identical colors to us, might give us a Euclidean distance that is greater than the Euclidean distance of colors that look different to us when comparing in RGB color space.

## So, what to do now?

Delta-E distance metric comes to our rescue. It uses the CIE Lab color space which approximates how we perceive colors, although its also not fully accurate. Once we represent the color in the CIE color space, we can calculate the Delta-E distance metric using Euclidean Distance. Ever since its release in 1976, it has been modified 2 times to cope with shortcomings of the previous versions. The diagram below shows that by shifting along the x and y axis we get different shades of the same color.

CIE76 -> CIE94 -> CIE2000

For, this tutorial we will use CIE2000. If you are interested in the actual mathematics, refer to the wikipedia page. It’s is pretty easy to write your own code to compare the 2 colors, but we’ll not try reinvent the wheel. Python provides a high utility package colormath  to convert between different colorspaces, delta E comparison, density to spectral operation etc.

Using colormath, we just don’t need to put in much effort to find the Delta-E metric.

The module colormath can be installed using pip -

Now, let’s write the actual code to find the difference between 2 colors.

I hope you liked the post, THANK YOU.