0

I have a program that uses matplotlib to plot an array then save the plot as a .png file. The array is updated, plotted again, and saved as a new .png file. The image files are titled image0, image1, etc. Currently, I use a MATLAB program that uses WriteVideo() to put the images into a video. Does anyone know how to do this in Python?

Daniel
  • 11
  • Maybe [Animation](https://matplotlib.org/3.2.1/api/animation_api.html) is helpful for you. – Quang Hoang Nov 03 '20 at 20:10
  • You could make a [gif](https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python) and then turn it into a [mp4 file](https://stackoverflow.com/questions/40726502/python-convert-gif-to-videomp4) – dontbanmeplz Nov 03 '20 at 20:11
  • take a look at `pillow` – Paul H Nov 03 '20 at 20:31

1 Answers1

1

As Quang mentioned, matplotlib does have an animation module, but in the backend it's using ffmpeg (or ImageMagick or a number of other engines). From my personal experience, I'd recommend saving individual image files, then using ffmpeg directly to create the video. This gives you greater control over your final output.

Given a directory of sequentially named files, your ffmpeg command could look like this:

ffmpegCommand = "ffmpeg -start_number {0} -framerate 25 -i image%d.png -c:v libx264 -r 25 -pix_fmt yuv420p {1}.mp4".format(0, "output")

which you invoke with:

os.chdir(thisWorkDir)  #change to the directory where your files sit
os.system(ffmpegCommand)   #or use subprocess module

Use a lower framerate if you want the video to go slower (meaning, hold on each image for longer)

One other tip, for this method - use a starting counter of, say, 1000, so your sequentially numbered image filenames are image1000, image1001, image1002, etc. (you'd change the -start_number accordingly in your ffmpeg command)

James_SO
  • 1,169
  • 5
  • 11