Skip to content

Instantly share code, notes, and snippets.

@mages
Last active July 24, 2018 01:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mages/4298433 to your computer and use it in GitHub Desktop.
Save mages/4298433 to your computer and use it in GitHub Desktop.
k-means cluster analysis in R
library(jpeg)
library(RCurl)
url <-"https://raw.githubusercontent.com/mages/diesunddas/master/Blog/LloydsBuilding.jpg"
readImage <- readJPEG(getURLContent(url, binary=TRUE))
dm <- dim(readImage)
rgbImage <- data.frame(
x=rep(1:dm[2], each=dm[1]),
y=rep(dm[1]:1, dm[2]),
r.value=as.vector(readImage[,,1]),
g.value=as.vector(readImage[,,2]),
b.value=as.vector(readImage[,,3]))
plot(y ~ x, data=rgbImage, main="Lloyd's building",
col = rgb(rgbImage[c("r.value", "g.value", "b.value")]),
asp = 1, pch = ".")
kColors <- 5
kMeans <- kmeans(rgbImage[, c("r.value", "g.value", "b.value")], centers = kColors)
approximateColor <- rgb(kMeans$centers[kMeans$cluster, ])
plot(y ~ x, data=rgbImage, main="Lloyd's building",
col = approximateColor, asp = 1, pch = ".",
axes=FALSE, ylab="",
xlab="k-means cluster analysis of 5 colours")
nRegions <- 2000
voronoiMeans <- kmeans(rgbImage, centers = nRegions, iter.max = 50)
voronoiColor <- rgb(voronoiMeans$centers[voronoiMeans$cluster, 3:5])
plot(y ~ x, data=rgbImage, col = voronoiColor,
asp = 1, pch = ".", main="Lloyd's building",
axes=FALSE, ylab="", xlab="2000 local clusters")
nRegions <- 500
voronoiMeans <- kmeans(rgbImage, centers = nRegions, iter.max = 50)
voronoiColor <- rgb(voronoiMeans$centers[,3:5])
plot(y ~ x, data=voronoiMeans$centers,
col = voronoiColor, cex=4.5,
asp = 1, pch = 15, main="Lloyd's building",
axes=FALSE, ylab="", xlab="500 local clusters")
@dcabanillas
Copy link

Hi mages,

Do you think that we cluster similar images following your approach?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment