【问题标题】:Saving multiple images (~50k) using matplolib with multiprocessing in python在 python 中使用带有多处理的 matplotlib 保存多个图像(~50k)
【发布时间】:2019-10-28 04:49:27
【问题描述】:

我已经在Code review 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。

【问题讨论】:

  • 用ssd代替硬盘
  • colab 中是否有这样的选项?

标签: python image matplotlib audio google-colaboratory


【解决方案1】:

你可以试试这样的:

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)

完全未经测试。您可能需要修复一些问题才能使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多