ranimationffmpegimagemagickmagick-r-package

Import png files and convert to animation(.mp4) in R


I'm trying to create a short animation with several png files in R. I tried package magick but it only works when I save them to .gif. When I tried to save as .mp4, it will generate an .mp4 file but once you open it, only the first image will be shown.

My code is

  library(magick)
  productPath <- ('/Users/abc/Desktop/products/')
  list <- list.files(productPath, '*.png')
  imagesPath <- paste0(productPath, list)
  images <- image_read(imagesPath)
  animation <- image_animate(images, fps = 20, loop = 1)
  image_write(animation, paste0(productPath, 'test.mp4'))

I found there is also a package called animation, but I don't really know how to import png files with that package. Any solutions? With either package should be fine. Thank you!


Solution

  • You can do like this (assuming the images are in the current directory):

    library(animation)
    imgs <- list.files(pattern="*.png")
    saveVideo({
      for(img in imgs){
        im <- magick::image_read(img)
        plot(as.raster(im))
      }  
    })
    

    By default this create animation.mp4.