Create video illustrations from numerical experiments data with Paraview and Python 2

See updated note.

One of the common tasks in computer modeling is visualization of numerical experiment as a movie. Usually it is one datafile per frame and target is to create frame-by-frame animation. If these files can be loaded and visualized in Paraview, it is easy to create the full video: load file in paraview with predefined parameters, create screenshot, load second file, etc. This process may be automated.

We will use latest stable build of Paraview from official site. Note: latest version of Paraview has strange error: it loses color while rendering. You may use previous Paraview 4.1 without this bug.

Extract tarball into ~/bin/paraview folder. Run paraview and prepare scene as you like. Remember the name of the pipeline with file you want to change every frame (in my case it is data). Save state (File->Save State) in folder with datafiles you want to visualize as state.pvsm.

Paraview with prepared state: Paraview State

Now we need for every file:

  • change pipeline data file for frame
  • render it
  • save frame picture

It can be done with following python 2 script:

#!/usr/bin/env python
from sys import path
path.append("/home/bikulov/bin/paraview/lib/paraview-4.2/site-packages")
path.append("/home/bikulov/bin/paraview/lib/paraview-4.2/site-packages/vtk")
path.append("/home/bikulov/bin/paraview/lib/paraview-4.2")

import glob, natsort, os
from paraview.simple import *

filenames = natsort.natsorted(glob.glob("*.raw"))

servermanager.LoadState("state.pvsm")
view = servermanager.GetRenderView()
camera = view.GetActiveCamera()
phase = FindSource('data')

try:
	os.makedirs("img")
except:
	pass

imgNum = 0

phase.FilePrefix = filenames[0]
phase.FileNameChanged()
view.WriteImage("img/"+str(imgNum).zfill(6)+".png","vtkPNGWriter",1)

for file in filenames:
    phase.FilePrefix = file
    phase.FileNameChanged()
    view.WriteImage("img/"+str(imgNum).zfill(6)+".png","vtkPNGWriter",1)
    imgNum += 1

All images will be created in img folder, crop them and build video with mogrify and ffmpeg (you may need to replace ffmpeg with avconv in newer versions of Ubuntu).