Last active
April 25, 2023 08:39
-
-
Save TeaPoly/83e6892ba8a36edc644104cf13e2a4b4 to your computer and use it in GitHub Desktop.
plot audio in SummaryWriter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# Copyright 2022 Lucky Wong | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License | |
import matplotlib.pyplot as plt | |
import numpy as np | |
tgt = target[0].cpu().detach().numpy() | |
noisy = probe[0].cpu().detach().numpy() | |
pred = prediction[0].cpu().detach().numpy() | |
fig, axs = plt.subplots(nrows=3, ncols=2, figsize=(10, 20)) | |
for idx, info in enumerate([(tgt, "tgt"), (noisy, "noisy"), (pred, "pred")]): | |
# wave | |
y, title = info | |
axs[idx, 0].plot(y) | |
axs[idx, 0].set_title(f'Waveform of {title}') | |
axs[idx, 0].set_xlabel('Time (samples)') | |
axs[idx, 0].set_ylabel('Amplitude') | |
# specgram | |
axs[idx, 1].specgram(y, NFFT=512, Fs=16000, | |
cmap='viridis', mode='magnitude') | |
axs[idx, 1].set_title(f'Log-frequency power spectrogram of {title}') | |
axs[idx, 1].set_xlabel('Time (seconds)') | |
axs[idx, 1].set_ylabel('Frequency (Hz)') | |
fig.canvas.draw() | |
w, h = fig.canvas.get_width_height() | |
image = np.frombuffer(fig.canvas.tostring_rgb(), | |
dtype='uint8').reshape((h, w, 3)) | |
image = torch.from_numpy(image).permute(2, 0, 1) | |
self.writer.add_image('Audio', image, global_step=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment