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/bb8066562c15c42678c2 to your computer and use it in GitHub Desktop.
Save rcquan/bb8066562c15c42678c2 to your computer and use it in GitHub Desktop.
Denoise a PNG Image
library(png)
library(abind)
library(impute)
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)
}
DenoisePNG <- function(png.file, k=10, display.only=TRUE) {
# denoise PNG image
rgb.array <- readPNG(png.file)
rgb.list <- SplitImage(rgb.array)
ZerosToNA <- function(mat) {
mat[mat == 0] <- NA
return(mat)
}
# change zero value pixels to NA
# impute NA values using kNN
rgb.list <- lapply(rgb.list, ZerosToNA)
rgb.imputed <- lapply(rgb.list, function(mat) {
imputed <- impute.knn(mat, k=k)
return(imputed$data)
})
# restore original dimensions
denoised.img <- abind(rgb.imputed, along=3)
filename <- sprintf("denoised_k%s_%s", k, png.file)
writePNG(denoised.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