我已经在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。
答案 0 :(得分:2)
您尝试这样的事情:
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)
未经测试。您可能需要修复一些问题才能使其正常工作。