Mike
Mike

Reputation: 31

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

I'm trying to create an animation in matplotlib and am seeing 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, but they didn't solve the issue.

You can run the code in this Google Colab notebook, or see it here:

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

Thanks for any advice!

Upvotes: 1

Views: 808

Answers (1)

Mike
Mike

Reputation: 31

I was able to find a solution that produces a gif without artifacts and does so in Colab (in part thanks to @JohanC's comment).

First, I needed to save the animation using FFMpeg as an mp4 video. This creates a high quality video without compression artifacts.

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

However, I wanted a gif, not a video, and I wanted to be able to do this in Google Colab. Running the following command converted the animation while avoiding the compression artifacts. (Some of these parameters are from this answer.

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

I've updated the Google Colab notebook.

Upvotes: 2

Related Questions