将 imshow 频谱图转换为图像

Convert imshow spectrogram to image

我只想将此处显示的小波图像(没有刻度或标签)保存到 png 文件中。

我尝试遵循解决方案 posted here for saving a spectrogram plot,但这种方法对我不起作用。

这是我得到的:

这是我用过的代码:

import librosa
import librosa.display

import os
import pywt
import matplotlib.pyplot as plt
import soundfile as sf

import skimage.io

from tftb.generators import anasing
from mpl_toolkits.axes_grid1 import make_axes_locatable

import numpy as np
from ssqueezepy import cwt
from ssqueezepy.visuals import plot, imshow

# Set the path to the Binary Class dataset
fulldatasetpath = 'G:/AudioFile'

input_file = (r'G:/Audiofile.wav')


[data1, sample_rate1] = sf.read(input_file)
#[sample_rate1, data1] = wav.read(input_file);
duration = len(data1)/sample_rate1

time = np.arange(0, duration, 1/sample_rate1) #time vector

#%%##############            Take CWT & plot                ##################################################
Wx, scales = cwt(data1, 'morlet')

imshow(Wx,  abs=1)
plt.show()

Wx = abs(Wx)

#%%##############            SAVE TO IMAGE                ###########################################
def scale_minmax(X, min=0.0, max=1.0):
    X_std = (X - X.min()) / (X.max() - X.min())
    X_scaled = X_std * (max - min) + min
    return X_scaled

wave1 = np.log(Wx + 1e-9) # add small number to avoid log(0)

# min-max scale to fit inside 8-bit range
img = scale_minmax(Wx, 0, 255).astype(np.uint8)
img = np.flip(img, axis=0)  # put low frequencies at the bottom in image
img = 255-img # invert. make black==more energy
out = 'out.png'
# save as PNG
skimage.io.imsave(out, img)

可以设置坐标轴的位置覆盖整个图形,还可以玩figsize。例如:

import matplotlib.pyplot as plt
import numpy as np
from ssqueezepy import imshow

# test image
img = np.zeros((500, 40000, 3), dtype=int)
for i in range(img.shape[1]):
    img[:, i, 0] = int(abs(1 - 2 * i / img.shape[1]) * 255)

# create a figure and set the size
f = plt.figure(figsize=(8, 4))
# add a new axis into which ssqueezepy is going to plot
ax = f.add_subplot()
imshow(img)
# turn off tick labels
ax.axis(False)
# make the axis to cover the entire figure
ax.set_position([0, 0, 1, 1])

f.savefig("result.png")