matplotlib绘制大量图片内存问题

采用matplotlib绘制大量图片时会产生内存问题,最好的办法是,只创建一个 figure 对象,在画下一个图之前,使用 plt.clf() 清理掉 axes,这样可以复用 figure。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5,4)) # 在循环外部创建一个fig对象,循环利用
for i in range(10000):
    print('figure %d' % i)
    filename = 'D:\\Desktop\\计算机视觉\\data\\'+str(i)+'.txt'
    data = np.loadtxt(filename)
    x = data[:, 1]
    y = data[:, 0]

    plt.plot(x, y, 'k', linewidth=0.2)
    plt.axis('off')
    # 去除边框
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
    plt.margins(0,0)
    
    filesave = 'D:\\Desktop\\计算机视觉\\image\\'+str(i)+'.png'
    fig.savefig(filesave, format='png', transparent=True, dpi=200, pad_inches = 0) # 选择合适的分辨率
    plt.clf() # 使用 plt.clf() 清理掉 axes

 

posted on 2018-12-06 22:55  那抹阳光1994  阅读(2748)  评论(0编辑  收藏  举报

导航