Last active
September 13, 2017 02:02
-
-
Save primaryobjects/06c2deca989af9c1acf735521ba9db81 to your computer and use it in GitHub Desktop.
Read a PNG as a grayscale single-channel image. Converts from RGB to G (single channel color array of bytes 0-255).
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') | |
# Load a png image as a grayscale single-channel byte array (0-255). | |
loadImage <- function(filename) { | |
data <- readPNG(filename) | |
result <- c() | |
# Convert to single-channel grayscale RGBA -> G, using the average method. | |
for (i in 1:nrow(data)) { | |
for (j in 1:ncol(data)) { | |
rgba <- data[i,j,] # Row i column j | |
g <- round(256 * mean(rgba[1:3]) / 3) | |
result <- c(g, result) | |
} | |
} | |
list(bytes=result, nrow=nrow(data), ncol=ncol(data)) | |
} | |
d <- loadImage('shirt2-28x28.png') | |
dd <- matrix(d$bytes, d$nrow, d$ncol) | |
image(dd, col=gray(seq(0, 1, length=256))) |
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
# This version is compatible with the readMNIST.R example. The only difference is the orientation of the resulting byte array. | |
# c(result, g) versus c(g, result) | |
library('png') | |
show_digit <- function(arr784, col=gray(12:1/12), ...) { | |
image(matrix(arr784, nrow=28)[,28:1], col=col, ...) | |
} | |
# Load a png image as a grayscale single-channel byte array (0-255). | |
loadImage <- function(filename) { | |
data <- readPNG(filename) | |
result <- c() | |
# Convert to single-channel grayscale RGBA -> G, using the average method. | |
for (i in 1:nrow(data)) { | |
for (j in 1:ncol(data)) { | |
rgba <- data[i,j,] # Row i column j | |
g <- round(256 * mean(rgba[1:3]) / 3) | |
result <- c(result, g) | |
} | |
} | |
list(bytes=result, nrow=nrow(data), ncol=ncol(data)) | |
} | |
d <- loadImage('shirt3-28x28.png') | |
show_digit(d$bytes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment