Last active
July 24, 2018 01:44
-
-
Save mages/4298433 to your computer and use it in GitHub Desktop.
k-means cluster analysis in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi mages,
Do you think that we cluster similar images following your approach?
Thanks.