不断刷新 matplotlib 图形会导致速度变慢

Continously refreshing a matplotlib figure results in a slowdown

我有以下代码显示带有两个图像的图形:

import numpy as np
import matplotlib.pyplot as plt

img1 = np.zeros((400,400,3), dtype=np.uint8)
img2 = np.ones((400,400,3), dtype=np.uint8) * 255

f, axarr = plt.subplots(1,2)

counter = 0
while True:
    print('Counter=', counter)
    counter += 1
    axarr[0].imshow(img1)
    axarr[1].imshow(img2)
    plt.draw()
    plt.pause(0.01)

图像将在每次迭代时重新生成,我想不断刷新图形。该代码有效,但在每次迭代中它越来越慢。我怀疑存在某种泄漏,或者至少是我做错了什么。

但是什么?

我可以调用 clf() 吗?我试过了,它在每次迭代时都会创建一个新的 window 。要我打电话吗

fig = plt.figure()

并以某种方式在每次迭代时释放新创建的图形? (但在这种情况下如何?)

每次你调用axarr[0].imshow(img1),一个新的图像将被添加到坐标区。尝试在每次迭代时清除使用 axarr[0].images = []axarr[1].images = [](或 axarr[0].images.clear()axarr[1].images.clear())存储的图像。