Hacking Matplotlib for Transparent Background Animations

It is difficult to make a video with a transparent background using Matplotlib/Python. This is because the method is officially blocked.

# https://github.com/matplotlib/matplotlib/blob/9e18a343fb58a2978a8e27df03190ed21c61c343/lib/matplotlib/animation.py#L1085
savefig_kwargs['transparent'] = False   # just to be safe!

This article bypasses this block by non-secure means. We are not responsible for any problems that may occur in reference to this article.

We also do not show a program that works properly with copy-paste, but only a fragment of it.

Hacking MovieWriter

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter

class HackedFFMpegWriter(FFMpegWriter):
  def grab_frame(self, **savefig_kwargs):
    # Arguments that are forced to be set within the Animation.save method are forced to be specified.
    savefig_kwargs["facecolor"]   = "#00000000"
    savefig_kwargs["transparent"] = True

    super().grab_frame(**savefig_kwargs)

writer = HackedFFMpegWriter(
  fps     = ...,
  bitrate = ...,
  codec   = "png",
)

# The way fig and ax are set up is not important for background transparency.
# However, there are useful ways to set it up.
fig = plt.figure(figsize=(..))
ax  = fig.add_axes([0, 0, 1, 1], frameon=False)
...

anim = FuncAnimation(fig = fig, ...)

anim.save(writer = writer, filename="output.mov", ...)

If it is properly transparent, the PNG file per frame cut from the MOV file should also have a transparent background.

ffmpeg -i output.mov -frames:v 10 output%d.png

Key Points

1. savefig_kwargs (Hacking)

The Animation.save method takes savefig_kwargs as arguments, which are implicitly rewritten internally. Therefore, the transparent specification is always false. This was addressed by overriding the grab_frame method called by the save method.

If you want to experiment, give savefig_kwargs to the save method and let it display savefig_kwargs before and after the rewrite in the grab_frame.

2. codec

In the case of ffmpeg (FFMpegWriter), the default video codec ('h264') is not transparent; in addition to 'png', 'qtrle', etc. must be explicitly specified. Specify when instantiating the MovieWriter object.

3. (filename) extension

The file name for saving a video must have a file extension with transparency information, such as MOV. MP4 is not suitable because it does not have this extension.

Non-Safe Method

Matplotlib developers have gone to the trouble of implicitly rewriting arguments to make them more secure. It is unclear what the results of the method shown in this article will be (the developers should comment in more detail...).

Reference Sites

I hear there's a behind-the-scenes spec that even the officials won't talk about

Source code is eloquent.

I see these are in trouble.


この記事が気に入ったらサポートをしてみませんか?