Faster way to use matplotlib.pyplot.savefig() in python

Viewed 260

I am trying to save a graph over a series of images (300 images). I thought the best way to do this would be using matplotlib.pyplot.savefig(); however, this takes a long time. How can I accomplish this faster? Here is my code.

for b in range(300):
    im = plt.imshow(green[b])
    plt.plot([b,3],[5,b])  # This isn't the actual plot. Just an example
    plt.savefig('frame_' + str(b) + '.tif')

Then with those results, I am just adding them to a list to concatenate them into a single tiff file. Therefore, my final results are a video of these images with the same plot overlayed throughout. This second part of code is not an issue. I am just including this for reference of what I am trying to accomplish overall.

my_list = []
for a in range(300):
   my_list.append('frame_'+str(a)+'.tif')

tifftools.tiff_concat(my_list, 'Tracks.tiff')
1 Answers

I found this to be faster than matplotlib's savefig. It uses moviepy that can be installed through conda install -c conda-forge moviepy :

from PIL import Image
from moviepy.video.io.bindings import mplfig_to_npimage
import matplotlib.pyplot as plt 
def savefig(fig, path):
    Image.fromarray(mplfig_to_npimage(fig)).save(path)
    
fig, ax = plt.subplots()
for b in range(3):
    ax.plot([b,3],[5,b])  # This isn't the actual plot. Just an example
    savefig(fig, 'name.tif')
Related