I have a list corresponding to the matrix of a .png image without the RGB transparency information. The dimension of the matrix is 128 128 3. So I have a 128 x 128 matrix coding the red hues in each pixel; a 128 x 128 matrix coding the greens; and a 128 x 128 matrix for the blues. There is no transparency in the image, but to write this .png, I think I need to include a 128x128 matrix of 1's and tag it to my list so as to get a 128 x 128 x 4 matrix.
How can I append this matrix of ones to my list?
I have a list named compressed with these dimensions (128 128 3), and I've tried multiple single and double-bracketed ways to include something like matrix(rep(1, 128^2), nrow= 128) without success.
The idea is to eventually save it as:
require(png)
writePNG(compressed, "compressed.picture")
without doing away with color.
Here's an example depending on whether you have an array or a list of matrices currently. Looking at ?writePNG it seems you need a n x n x 4 array as the final product, so I included a conversion from list to array.
Plenty of other solutions are offered e.g. here.
n <- 4
# generate matrices
r <- matrix(runif(n^2), n, n)
g <- matrix(runif(n^2), n, n)
b <- matrix(runif(n^2), n, n)
a <- matrix(1, n, n)
# list or array format for the data you have
li <- list(r, g, b)
ar <- array(c(r, g, b), dim = c(n, n, 3))
# appending the fourth matrix
li[[4]] <- a
ar1 <- array(c(ar, a), dim = c(n, n, 4))
# alternatively for array
library(abind)
ar2 <- abind(ar, a, along = 3)
# if you have a list and need an array
sapply(li, identity, simplify = "array")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With