首页 > 解决方案 > 在 python 中使用 matplolib 和多处理保存多个图像(~50k)

问题描述

我已经在代码审查 StackExchange中发布了这个问题(仅用于代码审查),但无法得到答案,所以我在这里非常具体地提出我的问题。下面的代码遍历一个音频文件目录(~50k)并将它们转换为频谱图图像并将它们中的每一个保存在同一个顶级目录中。

def plot_and_save(denoised_data, f_name):
    fig, ax = plt.subplots()

    i = 0
    # Add this line to show plots else ignore warnings
    # plt.ion()

    ax.imshow(denoised_data)

    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    fig.set_size_inches(10, 10)
    fig.savefig(
        f"{f_name}" + "_{:04d}.png".format(i),
        dpi=80,
        bbox_inches="tight",
        quality=95,
        pad_inches=0.0)

    ax.draw_artist(ax.xaxis)
    ax.draw_artist(ax.yaxis)

    i += 1


def standardize_and_plot(sampling_rate, file_path_image):
    logger.info(f"All files will be resampled to {sampling_rate}Hz")

    output_image_folder = "PreProcessed_image/"

    for dirs, subdirs, files in os.walk(file_path_image):
        for i, file in enumerate(files):
            if file.endswith(('.wav', '.WAV')):
                logger.info(f"Pre-Processing file: {file}")
                data, sr = librosa.core.load(
                    os.path.join(dirs, file), sr=sampling_rate, res_type='kaiser_fast')
                target_path = os.path.join(output_image_folder, dirs)

                pcen_S = apply_per_channel_energy_norm(data, sr)

                denoised_data = wavelet_denoising(pcen_S)

                work_dir = os.getcwd()

                if not os.path.exists(target_path):
                    os.makedirs(target_path)

                os.chdir(target_path)

                f_name, _ = os.path.splitext(os.path.basename(file))

                plot_and_save(denoised_data, f_name)

                os.chdir(work_dir)

if __name__ == '__main__':
    chunkSize = 3
    sampling_rate = 44100
    file_path_audio = 'Recordings'
    file_path_audio = "data/"
    output_audio_folder = "PreProcessed_audio/"

    file_path_image = os.path.join(output_audio_folder, file_path_audio)

    standardize_and_plot(sampling_rate, file_path_image)

如何使用多处理优化 plot_and_save() 方法?将这么多图像保存在磁盘中需要很多时间。为此,我正在使用 Google Colab。

标签: pythonimagematplotlibaudiogoogle-colaboratory

解决方案


you an try something like this:

from joblib import Parallel, delayed

chunkSize = 3
sampling_rate = 44100
file_path_audio = 'Recordings'
file_path_audio = "data/"
output_audio_folder = "PreProcessed_audio/"



def process_and_save(filename):
    data, sr = librosa.core.load(filename, sr=sampling_rate, res_type='kaiser_fast')
    target_path = os.path.join(output_image_folder, dirs)

    pcen_S = apply_per_channel_energy_norm(data, sr)

    denoised_data = wavelet_denoising(pcen_S)

    work_dir = os.getcwd()

    if not os.path.exists(target_path):
        os.makedirs(target_path)

    os.chdir(target_path)

    f_name, _ = os.path.splitext(os.path.basename(file))

    fig, ax = plt.subplots()

    i = 0
    # Add this line to show plots else ignore warnings
    # plt.ion()

    ax.imshow(denoised_data)

    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    fig.set_size_inches(10, 10)
    fig.savefig(
        f"{f_name}" + "_{:04d}.png".format(i),
        dpi=80,
        bbox_inches="tight",
        quality=95,
        pad_inches=0.0)
    ax.draw_artist(ax.xaxis)
    ax.draw_artist(ax.yaxis)
    i += 1


wav_files = []
for dirs, subdirs, files in os.walk(file_path_image):
    for i, file in enumerate(files):
        if file.endswith(('.wav', '.WAV')):
            wav_files.append(os.path.join(dirs, file))

Parallel(n_jobs=4, backend='multiprocessing')(delayed(process_and_save)(w) for w in wav_files)

fully untested. you might need to fix a few things to make it work.


推荐阅读