如何消除 matplotlib 动画中的压缩伪影?

How can I get rid of the compression artifacts in my matplotlib animation?

我正在尝试在 matplotlib 中创建动画,我看到 compression artifacts. The static image shows a smooth continuum of colors while the animation shows compression artifacts. How can I save an animation without these compression artifacts? I took some of the writer parameters from this answer,但他们没有解决问题。

您可以 运行 this Google Colab notebook 中的代码,或在此处查看:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

images = np.array([
  np.tile(np.linspace(0, 1, 500), (50, 1)), 
  np.tile(np.linspace(1, 0, 500), (50, 1)), 
])
fps = 1

fig = plt.figure(frameon=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
fig.add_axes(ax)
artists = [[ax.imshow(image, animated=True, cmap='jet')] for image in images]
anim = animation.ArtistAnimation(fig, artists, interval=1000/fps, repeat_delay=1000)
writer = animation.PillowWriter(fps=fps, bitrate=500, codec="libx264", extra_args=['-pix_fmt', 'yuv420p'])
anim.save('./test_animation.gif', writer=writer)
ax.imshow(images[0], animated=True, cmap='jet');

感谢任何建议!

我找到了一个解决方案,可以生成没有伪影的 gif 并在 Colab 中这样做(部分归功于@JohanC 的评论)。

首先,我需要使用 FFMpeg 将动画保存为 mp4 视频。这会创建没有压缩伪影的高质量视频。

writer = animation.FFMpegWriter(fps=fps)
anim.save('./test_animation.mp4', writer=writer)

但是,我想要一个 gif,而不是视频,并且我希望能够在 Google Colab 中完成此操作。 运行 以下命令转换了动画,同时避免了压缩瑕疵。 (其中一些参数来自 this answer.

!ffmpeg -i test_animation.mp4 -vf "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 test_animation.gif

我更新了 Google Colab notebook