How to prepare a movie file (gif / mp4) ?

We create a movie file from a series of data files. For creating a mp4 file, you need "gnuplot" and "ffmpeg", which you can install in Ubuntu by typing on a terminal:
sudo apt install gnuplot-x11
sudo apt install ffmpeg

Data file by a C++ code

#include <fstream>
#include <iomanip>
#include <vector>
#include <iostream>

//
// function for making source data of animation
//
int fileoutput(std::vector<double>& x, int time)
{
  //
  // the output file
  // 
  std::fstream outputfile;
  outputfile.open("outputfile", std::ios::out);

  // fileopen check
  if ( ! outputfile.is_open() ){
    std::cerr << "Open outputfile error" << std::endl;
    return EXIT_FAILURE;
  }

  // write the movement in the "outputfile" (diagonal movement of a point)
  else
    outputfile << x[0] << " " << x[1] << std::endl;
  outputfile.close();


  //
  // shell script file for renaming the "outputfile"
  // 
  std::fstream filerenamecom;
  filerenamecom.open("filerenamecom", std::ios::out);

  // fileopen check
  if ( ! filerenamecom.is_open() ){
    std::cerr << "Open outputfile error" << std::endl;
    return EXIT_FAILURE;
  }
  else{
    filerenamecom << "mv outputfile "
    << std::setfill('0') << std::setw(5) << std::right << time << std::endl;
  }
  filerenamecom.close();

  // excute and remove the filerenamecom
  system("sh ./filerenamecom");
  system("rm ./filerenamecom");
  
  return EXIT_SUCCESS;
}

//
// the main funciton
//
int main(){
  std::vector<double> x(2);

  
  for(int time=0; time<100; ++time){
    x[0] = static_cast<double>(time);
    x[1] = static_cast<double>(time);
    fileoutput(x, time);
  }
  

  return EXIT_SUCCESS;
}

gnuplot + C shell script

gnuplot

anime.gp

set term png set title 'time' set size square unset key unset tics set output "time.png" plot [0:100][0:100] "time" pt 7 ps 5 quit

C shell script

#!/bin/csh -f

foreach file ( 0* )
    sed 's/time/'${file}'/g' anime.gp > tmp.gp
    gnuplot tmp.gp
    rm ${file}
end

convert -delay 10 -loop 0 *.png anime.gif
ffmpeg -i %5d.png -pix_fmt yuv420p anime.mp4
\rm 0*.png tmp.gp

Products of the example

gif (infinite loop)

mp4 (once time only)


Last modified: Fri Aug 25 09:54:01 JST 2017