python - 在 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。
解决方案
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.
推荐阅读
- r - 如何在 R 的 selectInput 中添加空格/空白选项
- oracle - 创建一个定时作业,其他人不运行时运行
- python - 如何从我不小心更改的 keras.layers 恢复 core.py 文件
- android - 在复选框上使用 putExtra,但无法转到下一个活动
- excel - 根据键合并列excel
- java - 附加时 URL 有效#
- java - 从 getRuntime().exec 获取信息帽子 java 应用程序挂起
- java - 在 Maven 中搜索
- swift - Xcode 在 1 个工作区下有 2 个项目
- jquery - 无法启用 jQuery UI datepicker 的选定日期