Averaging Colours
I’m currently working on a project which needs me to get the mean average of different colours. I tried different ways of getting the average from rgb/hex and hsl.
My initial reaction was to add up each of the rgb values and divide by number of colours. However this is not strictly correct: the value of each pixel of color is stored as the square root of the value, and our monitors display it as the square of that value. See this post, and reddit discussion.
So the average value would more accurately be the sum of the square of each of the r,g,b values divided by the number of colours.
But what if I used hsl values instead of hex or rgb? Simply adding the two hue values together to get the average gives an incorrect value as hue is, in short, a point in a colour wheel. Each hue needs to be converted to cartesian coordinates, take the mean, and get the arctangent. The saturation and lightness/luminosity are percentages, so their average can be simply obtained.
I found that taking the average of the hue gives a colour that’s different to taking the average of the rgb.
Adding these two colours:
+
Gives you:
with RGB/hex, without squaring:
with RGB/hex, with squaring:
with HSL:
As you can see the HSL average (taken by calculating the mean of circular quantities), is closer to the ‘incorrect’ mean of RGB/hex, without taking the square of each r,g,b component. For this reason I decided against using HSL (also it’s less common for web).
Another issue I had is that the more colours were added together, the more it averaged out to a sort of brownish shade. It made more visual sense to choose two colours (eg. red and yellow) so each result can be represented on a red-yellow gradient, rather than as a shade of brown.
For reference, see this page with colours and formulas used.