Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib animation movie: quality of movie decreasing with time

I am trying to create a movie with the animation.FuncAnimation function in matplotlib. The movie looks fine interactively, but when I save it with the command

anim2.save('somefilm.mp4',codec='mpeg4', fps=15)

It starts out fine, but then becomes blurry (both using QuickTime and vlc, so I figured it's the movie, not the player).

I've played around with blitting, since I thought it was maybe the fact that the canvas wasn't redrawn, but to no avail. Increasing the bitrate also doesn't help.

Setting dpi=500 does improve the quality of the movie somewhat, though then it gets stuck repeatedly, which makes it difficult to watch.

I was just wondering whether this is the best one can do, or am I missing something?

like image 800
mzzx Avatar asked Aug 08 '14 12:08

mzzx


2 Answers

In order to dig into this problem it is important to understand that video files are usually compressed with a highly lossy compression whereas the interactive display is not compressed. The usual movie compressions are often extremely bad with graphs, and it is a matter of compression parameters.

There are four things you can do:

  • set the image resolution (by dpi), but this may actually make the output visually poorer, as the problem is usually not in the lacking pixels

  • set the image bitrate (by bitrate); the higher your bitrate, the better your movie will be - one possibility is to set bitrate=-1 and let matplotlib choose the best bitrate

  • change the codec (e.g., to codec="libx264")

  • give extra arguments to the codec (e.g., extra_args=['-pix_fmt', 'yuv420p'])

Unfortunately, these options really depend on the video codec, which is a third-party program (usually ffmpeg), the intended use of your video, and your platform. I would start by adding the kwarg bitrate=-1 to see if it improves things.

If you cannot make it work, please add a full (but as simple as possible) example of how to create a bad file. Then it is easier to debug!

like image 162
DrV Avatar answered Oct 10 '22 05:10

DrV


I was having the same problem while animating ~3500 frames of some subsurface water current vectors over a basemap and finally fixed the problem. I had been trying to set the bitrate in the anim.save declaration but was still getting the same blurriness later in the animation. What I had to do was set the bitrate when defining the writer:

plt.rcParams['animation.ffmpeg_path']='C:/ffmpeg/bin/ffmpeg.exe'
writer=animation.FFMpegWriter(bitrate=500)
anim.save('T:/baysestuaries/USERS/TSansom/Tiltmeters/testdeployment/tilt2.mp4',
          writer=writer,fps=8)

If I set the bitrate to anything less than 500 the animation would still get blurry. bitrate=-1 and codec='libx264' did nothing for me. Hope this helps!

like image 34
Taylor Avatar answered Oct 10 '22 05:10

Taylor