python实现给定信号生成任意信噪比的带噪声信号
产生叠加高斯白噪声的带噪语音
功能:
输入x为需加噪的信号,是一个numpy的1D张量
输入snr为设定信噪比,单位为dB,是一个32为的float数
输出noise是叠加在纯语音上的白噪声信号,与x格式相同,是一个numpy的1D张量
输出y是与需加噪声信号x格式相同的噪声信号,是一个numpy的1D张量
调用格式{(y, noise)=Gnoisegen(x,snr)}
代码:
import numpy as np
import math
x = np.array([1.,2.,3.,4.])
snr=-5
Nx = len(x) # 求出信号的长度
noise = np.random.randn(Nx)# 用randn产生正态分布随机数
print('noise=',noise)
signal_power = np.sum(x*x)/Nx# 求信号的平均能量
noise_power = np.sum(noise*noise)/Nx# 求信号的平均能量
noise_variance = signal_power/(math.pow(10., (snr/10)))#计算噪声设定的方差值
noise = math.sqrt(noise_variance/noise_power)*noise# 按照噪声能量构成相应的白噪声
y=x+noise
print('x=',x)
print('Nx=',Nx)
print('signal_power=',signal_power)
print('noise_power=',noise_power)
print('noise_variance=',noise_variance)
print('noise=',noise)
print('y=',y)
运行结果:
noise= [-0.40411468 -0.20302849 1.80350405 -0.37878525]
x= [1. 2. 3. 4.]
Nx= 4
signal_power= 7.5
noise_power= 0.9001585877551574
noise_variance= 23.717082451262844
noise= [-2.07431994 -1.0421449 9.25738313 -1.94430404]
y= [-1.07431994 0.9578551 12.25738313 2.05569596]
调用:
import numpy as np
import math
def Gnoisegen(x, snr):
Nx = len(x) # 求出信号的长度
noise = np.random.randn(Nx)# 用randn产生正态分布随机数
signal_power = np.sum(x*x)/Nx# 求信号的平均能量
noise_power = np.sum(noise*noise)/Nx# 求信号的平均能量
noise_variance = signal_power/(math.pow(10., (snr/10)))#计算噪声设定的方差值
noise = math.sqrt(noise_variance/noise_power)*noise# 按照噪声能量构成相应的白噪声
y=x+noise
return(y, noise)
x = np.array([1.,2.,3.,4.])
(y, noise)=Gnoisegen(x,-5)
print('noise=',noise)
print('y=',y)
结果:
noise= [ 2.47139973 -4.02557881 0.16798872 -8.51627901]
y= [ 3.47139973 -2.02557881 3.16798872 -4.51627901]
参考:《MATLAB在语音信号分析与合成中的应用》