如何摆脱 matplotlib 动画中的压缩伪影?

问题描述

我正在尝试在 matplotlib 中创建动画并看到 compression artifactsstatic 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...