rmagick

R: Convert/Read 3D Matrix into a 'magick' object and vice versa


I want to work with the magick package for its fantastic image manipulations capabilities. Looking through here I can't seem to find out how to convert a 3D matrix (width x height x channels) to a magick object I can further manipulate, and vice versa.

But I would like something like:

height <- 100
width <- 80
X <- array(runif(height * width * 3, min = 0, max = 255), c(height, width, 3))

magick::as.magick(X) %>% magick::image_scale("500x400")

(Obviously I could write the matrix to disk as an image, then read it with magick::image_read, that would be an overkill)

What did I miss?


Solution

  • You can use image_read() to read a matrix as well. However note that the convention is to scale the values between 0 and 1 in case of doubles. So you need to divide your X by 255. Try this:

    img <- magick::image_read(X / 255) %>% magick::image_scale("500x400")
    

    If you want to convert the magick object back to an array:

    image_data(img, 'rgba')
    

    Or just img[[1]] works as well.