0

I have an image that must be processed with the package magick. So the output belongs to class magick-image. I need to transform it to a class rasterBrick for further processing.

How can I transform an object magick-image to rasterBrick? I need to avoid saving and loading an intermediate temp file.

library(magick)
library(raster)

# load sample image
i <- image_read("https://i.picsum.photos/id/10/2500/1667.jpg?hmac=J04WWC_ebchx3WwzbM-Z4_KC_LeLBWr5LZMaAkWkF68")

# does not work
r <- raster::raster(i)

# workaround that I must avoid
image_write(i,"temp_image.jpg")
t <- brick("temp_image.jpg")
t

1 Answers1

2

You can do this:

library(terra)
r <- as.raster(i) |> as.matrix() |> rast()
r
#class       : SpatRaster 
#dimensions  : 1667, 2500, 3  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 0, 2500, 0, 1667  (xmin, xmax, ymin, ymax)
#coord. ref. :  
#source      : memory 
#colors RGB  : 1, 2, 3 
#names       : red, green, blue 
#min values  :   0,     8,    0 
#max values  : 252,   250,  248 

plot(r)

enter image description here

You may want to stick with terra, but if you want to go back to a RasterBrick, you can add

library(raster)
b <- brick(r)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63