Skip to content

Instantly share code, notes, and snippets.

@mages
Forked from dsparks/kmeans_palette.R
Created November 27, 2012 22:16
Show Gist options
  • Save mages/4157518 to your computer and use it in GitHub Desktop.
Save mages/4157518 to your computer and use it in GitHub Desktop.
Image Manipulation of the Lloyd's Building
library("ReadImages")
url <-"http://upload.wikimedia.org/wikipedia/commons/6/6a/6414A_1_copy.jpg"
download.file(url, "tempPicture.jpg", mode = "wb") # Stash image locally
readImage <- read.jpeg("tempPicture.jpg")
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]))
with(rgbImage,
plot(x, y,
col = rgb(rgbImage[c("r.value", "g.value", "b.value")]),
asp = 1, pch = "."))
# Cluster in color space:
kColors <- 5 # Number of palette colors
kMeans <- kmeans(rgbImage[, c("r.value", "g.value", "b.value")], centers = kColors)
plot(factor(kMeans$cluster), col=rgb(kMeans$centers),
xlab="Cluster", ylab="Count")
approximateColor <- kMeans$centers[kMeans$cluster, ]
pdf("~/Desktop/LloydsBuilding.pdf")
with(rgbImage, plot(x, y, col = rgb(approximateColor), asp = 1, pch = ".",
axes=FALSE, ylab="", xlab="Lloyd's building"))
dev.off()
## Using data.table
pkgs <- c("ReadImages", "data.table")
lapply(pkgs, library, character.only = TRUE)
url <-"http://upload.wikimedia.org/wikipedia/commons/6/6a/6414A_1_copy.jpg"
download.file(url, "tempPicture.jpg", mode = "wb") # Stash image locally
readImage <- read.jpeg("tempPicture.jpg")
dm <- dim(readImage)
rgbImage <- data.table(
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]))
with(rgbImage,
plot(x, y,
col = rgb(rgbImage[, list(r.value, g.value, b.value)]),
asp = 1, pch = "."))
# Cluster in color space:
kColors <- 5 # Number of palette colors
kMeans <- kmeans(rgbImage[, list(r.value, g.value, b.value)], centers = kColors)
plot(factor(kMeans$cluster), col=rgb(kMeans$centers),
xlab="Cluster", ylab="Count")
approximateColor <- kMeans$centers[kMeans$cluster, ]
pdf("~/Desktop/LloydsBuilding.pdf")
with(rgbImage, plot(x, y, col = rgb(approximateColor), asp = 1, pch = ".",
axes=FALSE, ylab="", xlab="Lloyd's building"))
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment