Search code examples
rmagick

R magick: compose images without vectorization


The description of the image_composite function in the magick R package states:

The image_composite function is vectorized over both image arguments: if the first image has n frames and the second m frames, the output image will contain n * m frames.

Here an ugly example:

banana <- image_read("https://jeroen.github.io/images/banana.gif")
image_composite(banana, banana, offset = "+70+00", operator = "Add")

Is there a way to avoid vectorisation so that the bananas can dance together? Alternatively, is there another function (also from other packages) that allows for this?


Solution

  • In the case where it's the same image, you can just modify each frame, turning the vectorization inside-out, sort of.

    image_apply(
      banana, FUN = function(img) {
        image_composite(img, img, offset = "+70+00", operator = "Add")
      }
    )
    

    enter image description here

    If you have two images of the same number of frames, that's harder using only the exposed functions in magick. An easier way is to just separate the magick-image objects into lists, and use functional programming tools like purrr::map2, then rejoin them afterwards:

    purrr::map2(
      as.list(banana), as.list(image_negate(banana)),
      ~image_composite(.x, .y, operator = "Add", offset = "+70+00")
      ) %>% 
      image_join()
    

    enter image description here