1. 程式人生 > >matplotlib繪制大量圖片內存問題

matplotlib繪制大量圖片內存問題

set orm nump off txt margin left adjust pan

采用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

matplotlib繪制大量圖片內存問題