1

I'm trying to save each frame of an animation as a png. The relevant code looks like this:

ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, beta, survival, theta),
                              frames=30,
                              interval=updateInterval,
                              save_count=50)
ani.save("animationpng_%03d.png")
plt.show()

I get 30 png files numbered correctly but I can't open them in any image viewer - they seem to be corrupted or either "pretend" files with nothing in them. The animation itself definitely works - it appears with plt.show() and I've successfully saved an mp4 version. Can someone point me to a solution?

TIF
  • 191
  • 1
  • 2
  • 11

2 Answers2

0

You can save the animation as gif and then easily convert it to png format.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • That would work and I'll probably use that if no easy solution turns up, it's just a case of wondering why this *doesn't* work :) – TIF Aug 27 '20 at 21:34
0

Here's a workaround / alternative solution:

If you are using a FuncAnimation, my first thought would be to add a plt.savefig command in your update function - so as the animation is built, you save individual PNGs. Here is an example animation from another post I answered (just using it b/c it is available), but I have modified it to include savefig for each frame:

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

time_steps = 50
N_nodes = 100

positions = []
solutions = []
for i in range(time_steps):
    positions.append(np.random.rand(2, N_nodes))
    solutions.append(np.random.random(N_nodes))

fig, ax = plt.subplots()
marker_size = 5 #upped this to make points more visible

def animate(i):
    """ Perform animation step. """
    #important - the figure is cleared and new axes are added
    fig.clear()
    ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(0, 1), ylim=(0, 1))
    #the new axes must be re-formatted
    ax.set_xlim(0,1)
    ax.set_ylim(0,1)
    # and the elements for this frame are added
    ax.text(0.02, 0.95, 'Time step = %d' % i, transform=ax.transAxes)
    s = ax.scatter(positions[i][0], positions[i][1], s = marker_size, c = solutions[i], cmap = "RdBu_r", marker = ".", edgecolor = None)
    fig.colorbar(s)
    #
    # HERE IS THE NEW LINE
    # v v v v v v v v v v 
    plt.savefig('frame {}.png'.format(str(i)))

plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.grid(b=None)
ani = animation.FuncAnimation(fig, animate, interval=100, frames=range(time_steps))

ani.save('animation.gif', writer='pillow')

Note that you still have to include the saving of the animation as a GIF (last line), or else there won't actually be iteration over every frame.

Trying to adapt your code, I couldn't get my frames to save as images after creating the animation - I'm not sure why this should work or what is going on with your unopenable files (sorry!).

Tom
  • 8,310
  • 2
  • 16
  • 36