DEV Community

Tejesh Reddy
Tejesh Reddy

Posted on

Difference Between 2 Colours Using Python

Recently, I needed to compare a number of colours to get the 2 most identical colours. This problem at the facade looks like a cakewalk, 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 colours.

d=sqrt((x1−x2)^2 + (y1−y2)^2 + (z1−z2)^2)

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

So, what to do now?

Delta-E distance metric comes to our rescue. It uses the CIE Lab colour space which approximates how we perceive colours, although it's also not fully accurate. Once we represent the colour in the CIE colour 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 colour.
CIE76 -> CIE94 -> CIE2000



alt text

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 colours, but we’ll not try to 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 -



sudo apt-get install python-pip
sudo pip install colormath


Enter fullscreen mode Exit fullscreen mode

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



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

Enter fullscreen mode Exit fullscreen mode




References

  1. Stack Overflow Thread
  2. PyPi colormath Package

Top comments (0)