用plt保存图片需要越来越多的时间

Image saving with plt needs more and more time

我写了一个简单的程序来将 .wav 转换为频谱图并将其另存为 png。 给你:

import numpy as np
import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
import os
import time as t

DATAPATH = 'dataset' #path
CATEGORIES = ['zero','one','two','three','four','five','six','seven','eight','nine']

for categorie in CATEGORIES:
    path = DATAPATH + '/' + categorie + '/'
    filenames = os.listdir(path) #get all filenames in categorie
    print(categorie)

    i = 0
    for file in filenames[:100]:
        start = t.time()
        Fs, aud = wavfile.read(path + file)
        powerSpectrum, frequenciesFound, time, imageAxis = plt.specgram(aud, Fs=Fs)

        plt.subplots_adjust(left=0, right=1, bottom=0, top=1) #cut axis
        plt.axis('off')

        plt.savefig('pics/' + categorie + '/' + str(i) + '.png')
        ende = t.time()
        print(i, str(ende-start)+'s')
        i += 1

问题是每张图片的时间越来越长(仅几毫秒),但在千张图片上,每张图片的时间就像 10 秒一样。这就是为什么我停止时间并将其打印出来的原因。一些解决方案?

FTR,解决方案似乎是在每次迭代后使用 plt.clf():

清理绘图
for categorie in CATEGORIES:
    # ...
    for file in filenames[:100]:
        # ...
        # plt.savefigs(...)
        plt.clf()
        # ...