每次通过后 matplotlib 都会变慢
matplotlib slows after every pass
为什么我的代码会随着时间的推移而变慢?当代码最初开始时,循环需要 ~.1 秒到 运行。到第 90 次传球时,我达到了 1+ 秒。我正在显示并保存图像。我注意到如果我按预期注释掉 fig.canvas.draw()
和 fig.canvas.flush_events()
代码 运行s。问题在于显示和更新交互式 window。是否有我需要清除的变量?
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()
因为您为每次迭代添加一张图像:之前的所有图像仍在 matplotlib 缓冲区中,并且它们被渲染了!
您需要清除缓冲区。尝试在 imshow
命令之前使用这行代码:
plt.gca().images.clear()
为什么我的代码会随着时间的推移而变慢?当代码最初开始时,循环需要 ~.1 秒到 运行。到第 90 次传球时,我达到了 1+ 秒。我正在显示并保存图像。我注意到如果我按预期注释掉 fig.canvas.draw()
和 fig.canvas.flush_events()
代码 运行s。问题在于显示和更新交互式 window。是否有我需要清除的变量?
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()
因为您为每次迭代添加一张图像:之前的所有图像仍在 matplotlib 缓冲区中,并且它们被渲染了!
您需要清除缓冲区。尝试在 imshow
命令之前使用这行代码:
plt.gca().images.clear()