Home > Software engineering >  matplotlib slows after every pass
matplotlib slows after every pass

Time:05-04

Why is my code slowing down as time goes on? When the code initially starts the loop takes ~.1 second to run. By the 90th pass I am at 1 second. I am displaying and saving the image. I noticed if I comment out fig.canvas.draw() and fig.canvas.flush_events() the code runs as expected. The issue is with displaying and updating the interactive window. Is there a variable I need to clear?

from flirpy.camera.lepton import Lepton
import matplotlib.pyplot as plt
import numpy as np
import cv2
from PIL import Image as im
import os, sys
import time

%matplotlib notebook
savefold = ('Therm')
if not os.path.exists(savefold):
    os.makedirs(savefold)
    
    
camera = Lepton()
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
                         
def getFrame():
    image = camera.grab()
    
    fimage = np.around((image/100 - 273.15) * 9 / 5   32, 2)
    cimage = np.around(image/100 - 273.15, 2)
    kimage = np.around(image/100, 2)
    
    cimage = np.where(cimage < 20, 20, cimage)
    cimage = np.where(cimage > 30, 30, cimage)
    
    getFrame.z = cimage
    return getFrame.z

getFrame.z = None
i = 0
while True:
    tic = time.perf_counter()

    npimage=getFrame()
    npimage=npimage
    
    data = im.fromarray(npimage)
    plt.imshow(data)
    fig.canvas.draw()
    fig.canvas.flush_events()
    
    plt.imsave(os.path.join(savefold, f'test_{i:05}.png'), data)
    i  = 1
    
    toc = time.perf_counter()
    print(f'Time to execute: {toc - tic:0.4f} seconds')
    

camera.close()

CodePudding user response:

Because you are adding one image for each iteration: all the previous images are still in matplotlib buffer, and they get rendered!

You need to clear the buffer. Try to use this line of code before the imshow command:

plt.gca().images.clear()
  • Related