Color difference algorithm – part 2

Emanuele Feronato Php, Tutorials

It’s time to see how to calculate difference between two colors.

I am using the CIE1994 formula because it’s quite accurate and not that complex to calculate.

Here it is, assuming I have two colors in Lab format


(thanx to Bruce Lindbloom)

First, I am turning the scripts explained at Color difference algorithm into functions, this way:


Now, it’s time to determine color difference, using the above formula:

And you’ll find the difference between colors.

Next time, a real application using all this boring theory… (you will be surprised…)

Want to learn more? Learn by example!

Get the full commented source code of an actual commercial cross platform HTML5 game!!

Comments 12

  1. dim

    great snippet … i will love to see a function that can generate lighter or darker color by a given color value through parameter

    this will be very handy when we want to auto generate color themes bye given color value by user

  2. Pingback: How to Choose Colours Procedurally (Algorithms) ยป

  3. Eduardo

    I trying to transfer this code to pascal. I don’t understan the following operation:
    $_red *= 100;
    $_green *= 100;
    $_blue *= 100;
    Could you explain to me?

  4. kpodenphant

    This is frickin’ awesome.I ported it to Actionscript.
    I tried the RGB distance method which worked ok, but had some errors. Then i tried converting to HSB which worked well for the RGB errors but has some other error.
    This algorithm is sweet!

  5. anonyMouse

    Eduardo it means that the variable is set to its current value times 100;

    i.e. red=2;
    red*=100; (red is now 200, all further code that uses the variable “red” will now use 200 rather than 2);

  6. Igor

    Thanks for explaining this stuff, and for your snippets of code )

    I’d like to use those snippets in our project, but in your post you don’t mention it anywhere, so can I ask you if it’s okay to reuse them? And if so, can you please put a license note on them, so they will be legally accessible?

    1. Post
  7. Dylan

    Thanks for this, it saved me A LOT of time.

    I had to change Line 8 of de_1994 to $dh = sqrt(abs(($da*$da)+($db*$db)-($dc*$dc)));

  8. Dylan

    You are going to kill me!!! Ignore the nonsense I posted earlier…

    Change line 8 of de_1994 to:
    $dh = ($da * $da) + ($db * $db) – ($dc * $dc);
    if ($dh < 0) { $dh = 0; } else { $dh = sqrt($dh); }

    I guess the problem is an excessively large delta C resulting in a sqrt of a negative number. This was causing NaN on many comparisons.

Leave a Reply

Your email address will not be published. Required fields are marked *