numpy 如何计算出使用python的频率列表中频率的标准偏差(信号处理)?

zynd9foi  于 2023-02-12  发布在  Python
关注(0)|答案(1)|浏览(167)

'大家好,我是一名电气工程专业的学生,刚刚接触python,我有一个信号处理课程的作业。作业是记录我自己,执行fft,将其通过BPF,并计算平均频率和频率的标准差。接下来,我想用这个结果来分离出我声音的二次和三次谐波,但我在网上找不到答案。
我录下了自己的声音,并执行了FFT,将其传递到巴特沃思带通滤波器,然后计算平均频率,得到了一个合理的答案。当我尝试计算标准差时,结果比平均频率大70倍左右,对于我尝试过的任何星座,这都是没有意义的。我尝试将文件的幅度归一化为最大值,以及频率到其最大值,我还尝试将频率(f)乘以幅度的平方,然后除以幅度平方和的列表,还尝试使用np.std()函数。我在这里添加代码,希望有人能启发我的眼睛,感谢前面的代码。

from scipy.fftpack import fft
from scipy.io import wavfile as wav
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig

def mean_freq(data, sample_rate):
    x = fft(data) # List of magnitudes in frequency domain
    f = np.linspace(0.0, sample_rate / 2.0, len(x) // 2)
    abs_x = abs(x)[0:int(len(x) / 2)]
    x_squared = abs_x ** 2
    numerator = sum(f * x_squared)
    denominator = sum(x_squared)
    average_frequency = round(numerator / denominator)
    stdv = np.sqrt((np.sum(f - average_frequency )** 2 ) / len(x)) ### NEED TO CHECK
    return average_frequency, round(stdv)

# Read the soundfile
fs, signal =wav.read('RECORDEDFILE.wav')
# Design characteristics
n = 3 # Filter's order
nyquist = fs/2
t = np.arange(0, 21, 1/fs) # Creating time variable


# --------------------------------------------------------------------------------------------------
# Design BPF of first harmony, BW=70 Hz
lcf = 85/nyquist # Low cut off (Normalized)
hcf = 155/nyquist # High cut off
b, a = sig.butter(n, [lcf , hcf], btype='bandpass', analog=False, output='ba') # Obtain the filter's coefficients

# Activate the filter
filtered_signal = sig.filtfilt(b, a, signal, axis=0)

# First harmony data
mean1, stdv1 = mean_freq(filtered_signal, fs)
print(f'The average frequency of the first harmony is: {mean1} [Hz]')
print(f'The standard deviation of the first harmony is: {stdv1} [Hz]')
nhhxz33t

nhhxz33t1#

您要更正此行:

# stdv = np.sqrt((np.sum(f - average_frequency )** 2 ) / len(x)) ### NEED TO CHECK
stdv = np.sqrt(np.sum((f - average_frequency)**2) / len(x))

相关问题