Tuesday, July 10, 2012

Making a movie out of images .png using ffmpeg

Say you are interested in plotting in three dimensions in R.  This can be quickly done using the rgl package in R.  There are functions called plot3d(), persp3d() and lines3d() which let you plot in three dimensions, light3d() which adds a light to the background, bbox3d() which edits the colors of the 3d box, and view3d() which picks the particular angle of view.  One idea is to quickly write a for loop within R to rotate the image 360 degrees to get a nice little rotation of your 3d image.

Now, say you are interested converting the 360 different views in R into 360 images with a .png format.  This can be done within the rgl package using the rgl.snapshot() function.  In R, type the following

# Load rgl library

# Plot 3d image
plot3d(x, y, z)

# For loop rotating the 3d image 360 degrees
degrees <- seq(1,360, by = 1) # a sequence from 1 to 360
for(i in 1:length(deg)){
    view3d(degrees[i], phi = 0) # pick the angle of view
    rgl.snapshot(paste(paste("/file_directory/filename", "-", 
        formatC(i, digits = 3, flag = "0"), sep = ""), "png", sep = "."))

formatC() is a function that will add -001, -002, -003 etc to each of your images. This will be important in a moment.  

Finally, say you are interested in converting these 360 images to a movie.  I came across a great blogpost that showed me the commands to quickly and painlessly accomplish this.   It requires the use of the ffmpeg command in the terminal. In the terminal, type the following: 

$ cd ./location_of_file/file_directory
$ ffmpeg -f image2 -i filename-0%3d.png video.mpg

This converts the 360 images named 'filename-0001.png', 'filename-0002.png' etc to a video named video.mpg.  I know this won't make sense to most people, but here is what I ended up with: 


No comments:

Post a Comment