Category Archives: rstats

Building a colour palette from an image.

In a fit of constructive procrastination I have programmed a function to extract colour information from a JPEG image and make a colour palette. This was inspired partly by Karthik Ram’s Wes Anderson R package.

This is how it works. First find yourself a nice image, then use the function, palettebuildr(), to extract the dominant colours. The function extracts the red/green/blue (rgb) colour values for each pixel in the image. It then calculates a distance matrix for the similarity of the colour values of each pixel. i.e. different shades of red will show up as being similar, likewise for shades of green etc. The function feeds this distance matrix into a clustering algorithm which hierarchically clusters the n pixels into n groups, based on similarity, to produce a tree object. It then cuts this tree into groups based on the desired number of groups. I used a similar algorithm to divide individual sheep into sub-groups based on their geographical location in one of the papers from my PhD (Jones et al. 2006 J. Anim. Ecol.). Once the pixels have been assigned to groups the function simply takes an arithmetic mean of the r/g/b colour values across the members of the group.

The arguments to the function are (1) the path to the JPEG file, (2) the number of colours desired, (3) the distance algorithm, (4) the clustering algorithm. The defaults for the latter two arguments are “euclidian” and “complete” – see the respective functions dist() and hclust() for details. It is worth exploring combinations of the available algorithms in some cases, depending on what you’re looking for, but the defaults seem to work well in most cases.

You run the function like this:

colorPalette <- palettebuildr("starrynight.jpg", ncols = 5)

Here’s a couple of examples.

Van Gogh’s “The Starry Night”

starrynight

A still from Princess Mononoke

mononoke

A bag of Skittles (hat tip Alyssa Frazee)

skittles

These palettes are naturally divergent, and might make a fun alternative to the excellent RColorBrewer colour schemes.

Here is the function, saved as a gist on github

Edit 25/2/2015 – Here’s another great example by Russell Dinnage (@ecologician) of colour palette extraction from images. This time using phylogenetic methods to generate a palette which takes into account human perception/colour luminosity.

Advertisements