Hate UML?

Draw sequence diagrams in seconds.

Fun with Colour Difference
Posted on: 2011-02-04 10:46:55

Are you looking for a nifty way to choose colours that stand out? Are you the type of person who is not satisfied until you have mathematically proven that your choice is optimal?

One way to do it is to treat red, green, and blue colour values as coordinates in a cube. Two colours are different if the distance between their coordinates is large. But the RGB colour space is not perceptually uniform. Because of the way the human eye works, lots of greens look the same, but we can easily see the difference between subtle shades of yellow. That's why George Takei is hawking TVs. It's also why perceptually uniform colour spaces, such as LAB or LUV warp the cube, as if it were made of play-dough, and left out in the sun for a while. The result is that the differences between the coordinates almost correspond to the perceived difference between two colours for most people.

The colour-space calculations are all on wikipedia, and they are dead simple to implement. For fun, I put them into a simple force system using Javascript (You'll need an HTML5 browser to view. If you're using an RSS reader, you'll have to go to my blog to see it.)


Below are all of the CSS colours which have names commonly recognized by most browsers. Every colour name from "AliceBlue" to "Gainsboro" to "YellowGreen" is there. The circles float freely, and are repelled by each other and the four sides of their container.

When you click on a colour, the background changes to that colour. All of the circles are then attracted to a vertical position based on how different they are from the background. Those near the top are close to the background colour. Those near the bottom are further away from the background. You can change the colour space in which the distance is calculated by clicking on band at the top of the container.

For HSV, the H parameter is divided by 360 before the distance is calculated, to make its influence fair, since the S and V values range from 0 to 1.

Sorry, you have to use a browser that supports HTML5 and go to my blog to see it.


In RGB, black is the most different from white. But in LAB, black is in the middle somewhere, and other dark colours are more distant.

To my eye, both RGB and LAB perform well for finding differences, but HSV results in some odd choices. To choose a contrasting colour, use RGB or LAB and avoid picking anything less than a third of the way down.

Source code

The source code is released to the public domain.

You might be interested in a previous article about exploiting colour difference for edge detection.

Other articles from my blog

Want more programming tech talk?
Add to Circles on Google Plus
Subscribe to posts

Post comment

Real Name:
Your Email (Not displayed):

Text only. No HTML. If you write "http:" your message will be ignored.
Choose an edit password if you want to be able to edit or delete your comment later.
Editing Password (Optional):


2011-02-05 06:13:38
Good demonstration, thanks.

Only seems to use quite much CPU power (irrelevant, I just wondered why my laptop fan was speeding up).

Andy Brice

2011-02-22 04:18:07
Interesting. I might get to use some of these ideas in PerfectTablePlan for choosing default vizualization colours.

Stefan Monov

2011-02-23 16:43:01
I looked at your code, you calculate HSV distance incorrectly.

The distance between hues 0.1 and 0.9 is 0.2 because hue wraps around, but your code calculates it to be 0.8.

Steve Hanov

2011-03-10 20:42:45
Stefan: Thanks for pointing out the calculation error in HSV. I have corrected it.

Yann Achard

2011-03-12 23:20:32
I wonder if using a particular set of weights for the HSV distance function would make the HSV results less surprising.

Our eyes are much more sensitive to V than to H or S so it would make sense wouldn't it?


2011-03-21 14:51:38
It would be interesting to come up with a perceptual color map for typical red-green color blindness. Many colors that I consider perceptually similar end up near the bottom with the above color spaces. People with good color vision would probably be amused by the results.

In fact, since I can't identify many of these colors, it would be nice to show the RGB/HSV/LAB values when you mouseover.

Jan Odvarko

2011-06-26 05:20:54
Thank you for your article, it has been so much helpful!


2011-07-01 00:56:37
Shouldn't distance be commutative, or am I misunderstanding something? In, for example, the LAB color space, if you click on black, and then choose one of the furthest colors, black ends up somewhere in the middle, as if yellow is twice as far from black as black is from yellow.


2011-10-01 14:21:47
In Colours.js, convert_XYZA_RGBA refers to xyz.X, .Y, and .Z when it should be .values[0], [1], and [2] and convert_LABA_XYZA has WHITE.z (lowercase) when it should be WHITE.Z (uppercase).

Jason Davies

2011-12-03 00:11:36
The two files are returning 404 (Colours.js and driver.js) so the example no longer works. :(


2012-01-02 06:17:25
I think the formula for distanceTo isn't ideal in LAB, CIE has adjusted the formula throughout the years to account for peculiarities of human perception of color, en.wikipedia.org/wiki/Color_difference


2012-07-09 05:38:50
i want to see coding java for make the differences between two color !!!

Steve Moseley

2012-07-26 19:55:14

I found the same bug as Josh, where in "convert_XYZA_RGBA" function you are referencing fields X, Y and Z where you should be using array elements. Please fix!

Other than that, nice work :-)

Steve Hanov

2012-07-27 10:42:23
I updated Colours.js for you all with new bugfixes. It is now the same version I use on zwibber.com, and includes changes so that it builds with the Google Closure compiler without errors.


2012-08-02 05:38:07
Just one note in defence of HSV: i had to implement a colour difference function some time ago, and learned pretty soon that for example hue difference is much more noticeable if luminosity (v for you) is around the middle; it's common sense if you think about it a bit, if the colour is (nearly) black or white, it makes no or little difference. Same, or similar, with saturation. So converting the 3 dimensions of your colour space, whichever it is, into a scalar is not as trivial as a 3D vector length. I ended up with quite an expression but it works much closer to human judgement. Although if you just want to demonstrate the differences between colour spaces instead of looking for a good colour difference function, you're fine.

Oh, and thanks by the way, nice little toy.


Other posts by Steve

Yes, You Absolutely Might Possibly Need an EIN to Sell Software to the US How Asana Breaks the Rules About Per-Seat Pricing 5 Ways PowToon Made Me Want to Buy Their Software How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets UMA and free long distance UMA's dirty secrets Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets