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.
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.
colormath, we just don’t need to put in much effort to find the Delta-E metric.
colormath can be installed using pip -
Now, let’s write the actual code to find the difference between 2 colors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from colormath.color_objects import sRGBColor, LabColor from colormath.color_conversions import convert_color from colormath.color_diff import delta_e_cie2000 # Red Color color1_rgb = sRGBColor(1.0, 0.0, 0.0); # Blue Color color2_rgb = sRGBColor(0.0, 0.0, 1.0); # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor); # Convert from RGB to Lab Color Space color2_lab = convert_color(color2_rgb, LabColor); # Find the color difference delta_e = delta_e_cie2000(color1_lab, color2_lab); print "The difference between the 2 color = ", delta_e
I hope you liked the post, THANK YOU.