问题描述
我正在尝试在 matplotlib 中创建动画并看到 compression artifacts。 static image 显示平滑连续的颜色,而 animation shows compression artifacts。如何在没有这些压缩伪影的情况下保存动画?我从 this answer 中获取了一些 writer
参数,但它们没有解决问题。
您可以在 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,])
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],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。