Wednesday, 9 December 2009

Colour matching feature in R

I love R. It is an open-source statistical programming language that I found reasonably easy to learn, and find it incredibly versatile and useful. Because it's open-source anyone can contribute to it, and there are a huge number of packages that extend its capabilities to do pretty much anything.

I've been using it to do Principal Components Analysis on some colour data that I measured from photos of some Carpophilus specimens, and was trying to figure out how to relate the RGB values I got from the photos to actual names. R has in its core packages a colors() function with a lot of names assigned to particular RGB values. Thankfully, Barry Rowlingson has come up with a very nice little function that figures out which colour names the RGB value is closest to:

nearColour <- function(r,g,b){
ctable = col2rgb(colors())
cdiff = ctable - c(r,g,b)
cdist = cdiff[1,]*cdiff[1,]+cdiff[2,]*cdiff[2,]+cdiff[3,]*cdiff[3,]
return(colors()[cdist == min(cdist)])
}
Pretty useful for standardising colour names!

1 comment:

Samuel Brown said...

For further information on colour notation, R code and other stuff; all in a soil science context, see the California Soil Science lab webpage: http://casoilresource.lawr.ucdavis.edu/drupal/node/201