Skip to content

Instantly share code, notes, and snippets.

@mieciu
Last active March 6, 2016 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mieciu/a602d65b2caaba1aa86f to your computer and use it in GitHub Desktop.
Save mieciu/a602d65b2caaba1aa86f to your computer and use it in GitHub Desktop.
K-means in R
install.packages("plot3D")
library(jpeg)
library(rgl)
img <- readJPEG("akira2.jpg")
# > dim(img)
# [1] 514 694 3 <height width RGB>
# load image into data frame
pixels_df <- data.frame(r=as.vector(img[,,1]),g=as.vector(img[,,2]),b=as.vector(img[,,3]))
(kc <- kmeans(pixels_df,3))
v=kc$centers[1,]
# col1 = rgb(0.7684497, 0.34786568, 0.1734653)
# col2 = rgb(0.3514383, 0.40002754, 0.4495053)
# col3 = rgb(0.1447469, 0.09403485, 0.1339514)
# plot(x, y, pch = 15, col = col1)
# plot(x, y, pch = 15, col = col2)
# plot(x, y, pch = 15, col = col3)
# rect(0, 0, 10,10, col=col1)
# rect(10,10,10,20, col=col2)
# rect(0, 20,10,30, col=col3)
# ref http://www.colorschemer.com/online.html
# http://www.rdatamining.com/examples/kmeans-clustering
# http://www.statmethods.net/graphs/scatterplot.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment