使用matplotlib画图时不能同时打开太多张图

使用matplotlib画图时有时会收到来自matplotlib的runtime warming的警告,原因可能是同时打开太多张图,最常见的情况是在一个循环中画图,每次循环都新建一个图,但是未关闭新建的图,当循环次数多了之后内存就吃不消了。

有两种解决方法,一是只建一个图,每次循环结束后通过plt.cla()清除图的内容,下次循环可以使用同一张图作画,例子如下:

import os
import scipy
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm

data_path = r"D:\PycharmProjects\dataset"

def load_mnist():
    path = os.path.join(data_path, 'mnist')
    fd = open(os.path.join(path, 't10k-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teX = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float)

    teX = teX / 255.
    return teX


teX = load_mnist()
fig, ax = plt.subplots(nrows=5, ncols=5, sharex='all', sharey='all') # 只建一张包含25个子图的图
ax = ax.flatten()
for j in range(3):
    for i in range(25):
        img = teX[i + j * 25].reshape(28, 28)
        ax[i].imshow(img, cmap='Greys', interpolation='nearest')
    ax[0].set_xticks([])
    ax[0].set_yticks([])
    plt.tight_layout()  # 自动紧凑布局
    plt.savefig(r"D:\test\%d.png" % j)
    plt.cla() # 清除内容

第二种方法是每次循环都新建一张图,但是每次循环结束后关闭这张图,例子如下:

import os
import scipy
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm

data_path = r"D:\PycharmProjects\dataset"

def load_mnist():
    path = os.path.join(data_path, 'mnist')
    fd = open(os.path.join(path, 't10k-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teX = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float)

    teX = teX / 255.
    return teX


teX = load_mnist() # 获取mnist的测试数据

for j in range(3): # 画三张图
    fig, ax = plt.subplots(nrows=5, ncols=5, sharex='all', sharey='all') # 每次都新建一张包含25个子图的图
    ax = ax.flatten()
    for i in range(25):
        img = teX[i + j * 25].reshape(28, 28)
        ax[i].imshow(img, cmap='Greys', interpolation='nearest')
    ax[0].set_xticks([])
    ax[0].set_yticks([])
    plt.tight_layout()  # 自动紧凑布局
    plt.savefig(r"D:\test\%d.png" % j)
    plt.close()

实验证明,用第二种方法会比第一种方法快很多

你可能感兴趣的:(matplotlib)