Last active
August 29, 2015 14:06
-
-
Save rcquan/bb8066562c15c42678c2 to your computer and use it in GitHub Desktop.
Denoise a PNG Image
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(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