Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • There is no as.magick function
  • The as.matrix function does not work

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?

like image 708
Giora Simchoni Avatar asked Dec 03 '17 11:12

Giora Simchoni


1 Answers

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.

like image 66
Jeroen Ooms Avatar answered Sep 29 '22 18:09

Jeroen Ooms