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