将信噪比计算从MATLAB翻译成python语法



这是我想用Python翻译的MATLAB代码。

function [SNR] = bvpsnr(BVP, FS, HR, PlotTF)
HR_F=HR/60;
NyquistF = FS/2;
FResBPM = 0.5; %resolution (bpm) of bins in power spectrum used to determine PR and SNR
N = (60*2*NyquistF)/FResBPM; %number of bins in power spectrum
%% Construct Periodogram
[Pxx,F] = periodogram(BVP,hamming(length(BVP)),N,FS);
GTMask1 = (F >= HR_F-0.1)&(F <= HR_F+0.1);
GTMask2 = (F >= HR_F*2-0.2)&(F <= HR_F*2+0.2);
SPower = sum(Pxx(GTMask1|GTMask2));
FMask2 = (F >= 0.5)&(F <= 4);
AllPower = sum(Pxx(FMask2));
SNR = pow2db(SPower/(AllPower-SPower));

这里我试着用python翻译

def pow2db(x):
return 10 * log10(x)
def SNR(bvp, fps, hr):
HR_F = hr/60
Nyquist = fps/2
FResBPM = 0.5
N = (60*2*Nyquist)/FResBPM
print(N)
f_set, Pxx_den = welch(bvp, fps, window='hann', nperseg=32)
GTMask1 = f_set >= HR_F-0.1 and f_set <= HR_F+0.1
GTMask2 = f_set >= HR_F*2-0.2 and f_set <= HR_F*2+0.2
SPower = sum(Pxx_den[GTMask1:GTMask2])
FMask2 = f_set >= 0.5 and f_set <=3
AllPower = sum(Pxx_den[FMask2])
SNR = pow2db(SPower/(AllPower-SPower))

当我用我的数据运行以下代码时,我得到错误:

GTMask1 = f_set>= HR_F-0.1 and f_set <= HR_F+0.1 ValueError:包含多个元素的数组的真值有二义性。使用a.a any()或a.a all()

要比较numpy数组的元素,请使用&运算符(logical and):

GTMask1 = (f_set >= HR_F-0.1) & (f_set <= HR_F+0.1)
GTMask2 = (f_set >= HR_F*2-0.2) & (f_set <= HR_F*2+0.2)

对于逻辑或使用|:

SPower = sum(Pxx_den[GTMask1|GTMask2])

最新更新