将二维ndarray转换为RGB图像

问题描述 投票:0回答:1

我正在使用Librosa库从wav文件创建频谱图。返回的频谱图的类型为ndarray

spectogram_amp = melspectrogram(y=y,S=S,sr=sr,hop_length=hop_length,n_mels=n_mels,fmax=fmax) 
spectogram_decibel = librosa.power_to_db(spectogram_amp, ref=np.max)

我的目标是将频谱图另存为RGB图像。我成功使用了PLT,但是由于无花果形状是英寸,因此无法使用PLT指定像素尺寸。我需要将频谱图另存为128x128图像。

当像这样使用PIL时:

img = Image.fromarray(spectogram_decibel, 'RGB')

我得到这样的嘈杂图像:noisy image

我想我不太了解如何将2D阵列转换为3D RGB矩阵。另外,为什么这对PLT有用,但对PIL不起作用?

使用PIL和相同的ndarray生成RGB光谱图的代码。

librosa.display.specshow(spectogram_decibel,
                                     sr=sr,
                                     fmax=8000)
# Saving the spectogram
plt.gca().set_axis_off()
plt.subplots_adjust(top=1, bottom=0, right=1, left=0,
                                hspace=0, wspace=0)
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.tight_layout()
plt.axis('off')
plt.savefig(save_specto_to + label + str(count) + '.png',
                        bbox_inches='tight', dpi=300, frameon='false')
python numpy python-imaging-library rgb librosa
1个回答
0
投票

使用numpy.stack()可以解决问题

import numpy as np

img = np.stack([spectogram_decibel, spectogram_decibel, spectogram_decibel], axis=-1)

注意:这不会使输出着色,只会将2D(灰度)输入转换为3D表示形式,您可以像处理RGB ndarray一样对其进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.