【问题标题】:spectral centroid of numpy arraynumpy数组的光谱质心
【发布时间】:2019-01-04 02:43:27
【问题描述】:

我有一个.wav 文件(在本例中称为“piano2.wav”)。

我想在 python 中找到光谱质心。

使用这里另一篇文章中的代码我有这个功能:

import numpy as np
from scipy.io.wavfile import read

def spectral_centroid(x, samplerate=44100):
    magnitudes = np.abs(np.fft.rfft(x))
    length = len(x)
    freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1])
    return np.sum(magnitudes*freqs) / np.sum(magnitudes) 

我使用 scipy.io.wavfile.read 将 wav 文件读取到一个 numpy 数组中,然后尝试将其输入到上述函数中

a=read("piano2.wav")
print("Spectral centroid is " + spectral_centroid(a[1]))

这是我得到的错误

  File "test.py", line 20, in <module>
    print("Spectral centroid is " + spectral_centroid(a[1]))
  File "test.py", line 8, in spectral_centroid
    return np.sum(magnitudes*freqs) / np.sum(magnitudes) 
ValueError: operands could not be broadcast together with shapes (302712,2) (151357,)

【问题讨论】:

    标签: python arrays numpy scipy wav


    【解决方案1】:

    您正在尝试将不同形状的数组相乘(magnitudesfreqs):

    a = np.arange(10)
    b = np.arange(5)
    print(a*b)
    

    ValueError: 操作数无法与形状 (10,) (5,) 一起广播

    这可能会有所帮助:

    def spectral_centroid(x, samplerate=44100):
        magnitudes = np.abs(np.fft.rfft(x))
        length = len(x)
        freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1])
        magnitudes = magnitudes[:length//2+1]
        return np.sum(magnitudes*freqs) / np.sum(magnitudes) 
    

    【讨论】:

    • 不幸的是,我仍然得到同样的错误:ValueError: 操作数不能与形状一起广播 (151357,2) (151357,)
    • 试试magnitudes*freqs[:, None]
    • 这开始看起来像是基本的调试帮助。
    • 不幸的是,我是 python 新手(来自 java,我发现语法有点混乱)。此代码用于学校项目,尽管可能高于我的水平。不过谢谢你,它看起来现在可以工作了@MadPhysicist
    猜你喜欢
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多