Skip to content

Instantly share code, notes, and snippets.

@rcquan
Last active August 29, 2015 14:06
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 rcquan/089e47403c5290a65b31 to your computer and use it in GitHub Desktop.
Save rcquan/089e47403c5290a65b31 to your computer and use it in GitHub Desktop.
Reduce Dimensions of PNG Image using PCA
library(png)
library(abind)
ProjectImage <- function(prcomp.obj, pc.num) {
# project image onto n principal components
scores <- prcomp.obj$x
loadings <- prcomp.obj$rotation
img.proj <- scores[, c(1:pc.num)] %*% t(loadings[, c(1:pc.num)])
return(img.proj)
}
SplitImage <- function(rgb.array) {
# decompose image into RGB elements
rgb.list <- list()
for (i in 1:dim(rgb.array)[3]) {
rgb.list[[i]] <- rgb.array[, , i]
}
return(rgb.list)
}
ReduceDimsPNG <- function(png.file, pc.num, display.only=TRUE) {
# reduce dimensions of PNG image
rgb.array <- readPNG(png.file)
rgb.list <- SplitImage(rgb.array)
# apply pca and reproject onto new principal components
rgb.list <- lapply(rgb.list, prcomp, center=FALSE)
rgb.proj <- lapply(rgb.list, ProjectImage, pc.num=pc.num)
# restore original dimensions
restored.img <- abind(rgb.proj, along=3)
filename <- sprintf("reduced_pc%s_%s", pc.num, png.file)
writePNG(restored.img, filename)
grid.raster(readPNG(filename, native=TRUE))
if (display.only){
file.remove(filename)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment