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

5.6k views Asked by At

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!

3

There are 3 answers

8
Stéphane Laurent On BEST ANSWER

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.

0
Cristian David Pachacama On
library(purrr)
library(magick)
list.files(pattern = "*.png") %>% 
    map(image_read) %>% # reads each path file
    image_join() %>% # joins image
    image_animate(fps=5) %>% # animates
    image_write("animation.gif") # write to current dir
0
moho wu On

The selected best answer requires you to install ffmpeg first. If you haven't and due to limited administrative right you can't install other programs on you PC you can try the av package.

This works without needing to install any other program.

av::av_encode_video(list.files(productPath, '*.png'), framerate = 30,
                    output = 'test.mp4')