I can't resist to write about this here as well. David's first post is about k-means cluster analysis. One of the popular algorithms for k-means is Lloyd's algorithm. So, on that note I will use a picture of the Lloyd's of London building to play around with David's code, despite the fact that the two Lloyds have nothing to do with each other. Lloyd's provides pictures of its building copyright free on its web site. However, I will use a reduced file size version hosted on wikimedia.
The ReadImages package by Markus Löcher  allows me to load a jpeg-file into R. The R object of the images is an array, which has the structure of three layered matrices, representing the value of the colours red, green and blue for each x and y coordinate. I convert the array into a data frame, as this is an accepted structure by k-means and plot the data.
url <- "http://upload.wikimedia.org/wikipedia/commons/6/6a/6414A_1_copy.jpg"
fn <- tempfile()
readImage <- read.jpeg(fn)
dm <- dim(readImage)
rgbImage <- data.frame(
plot(y ~ x, data=rgbImage, main="Lloyd's building",
col = rgb(rgbImage[c("r.value", "g.value", "b.value")]),
asp = 1, pch = ".")
Running a k-means analysis on the three colour columns in my data frame allows me to reduce the picture to k colours. The output gives me for each x and y coordinate the colour cluster it belongs to. Thus, I plot my picture again, but replace the original colours with the cluster colours.