首页 > 解决方案 > 如何摆脱 matplotlib 动画中的压缩伪影?

问题描述

我正在尝试在 matplotlib 中创建动画并看到压缩伪影静态图像显示平滑连续的颜色,而动画显示压缩伪影。如何在没有这些压缩伪影的情况下保存动画?我从这个答案writer中获取了一些参数,但它们并没有解决问题。

您可以在此 Google Colab 笔记本中运行代码,或在此处查看:

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');

感谢您的任何建议!

标签: matplotlibanimationcompressionartifacts

解决方案


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

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

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

但是,我想要的是 gif,而不是视频,并且我希望能够在 Google Colab 中做到这一点。运行以下命令会转换动画,同时避免压缩伪影。(其中一些参数来自这个答案

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

我已经更新了Google Colab notebook


推荐阅读