Blog-like notes

Combining movies with ImageMagick and Mencoder

During my PhD, one of my coworkers once asked me to help her to prepare a presentation. She had two short movies representing each a different channel of a time-lapse microscopy experiment, and wanted to combine them into a single movie displaying both channels side by side.

The following picture illustrates what she wanted to achieve:

Combining two movies

She had no clue on how to do that and, at that time, neither did I. Another coworker suggested to use some full-featured movie editing program such as Adobe Premiere, but I had the feeling that the desired result could be achieved using only the tools already installed on my GNU/Linux system. It turned out I was right, and for the record, here is how I performed the task.

The first step was to extract the individual frames of each movie. I used MPlayer with the png video output driver:

$ mkdir first_movie_frames second_movie_frames
$ mplayer -vo png:outdir=first_movie_frames first_movie.avi
$ mplayer -vo png:outdir=second_movie_frames second_movie.avi

There was 25 frames in each movie, so I ended with 25 png files in each directory first_movie_frames and second_movie_frames.

Next, I used ImageMagick’s montage tool to create the combined frames:

$ mkdir combined_frames
$ for i in $(seq 25); do
    montage -geometry +1+1 \
      first_movie_frames/$(printf %08d $i).png \
      second_movie_frames/$(printf %08d $i).png \
      combined_frames/$(printf %08d $i).png
done

Finally, I used MEncoder to create a new movie from the combined frames:

$ mencoder "mf://combined_frames/*.png" \
    -mf type=png:fps=5 -o combined_movie.avi \
    -ovc lavc -lavcopts vcodec=mpeg4

And that’s all. It was even simpler than I had anticipated, and very time efficient. Reading the manual pages and figuring out the appropriate options took me more time than actually running the commands, and the whole process took a lot less time than downloading and installing a movie editing program!