Python实现十种滤波算法

1、限幅滤波法(又称程序判断滤波法)

2、中位值滤波法

3、算术平均滤波法

4、递推平均滤波法(又称滑动平均滤波法)

5、中位值平均滤波法(又称防脉冲干扰平均滤波法)

6、限幅平均滤波法

7、一阶滞后滤波法

8、加权递推平均滤波法

9、消抖滤波法

10、限幅消抖滤波法

import scipy.signal as signal
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
import matplotlib
 
'''
算术平均滤波法
'''
def ArithmeticAverage(inputs,per):
	if np.shape(inputs)[0] % per != 0:
		lengh = np.shape(inputs)[0] / per
		for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
			inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
	inputs = inputs.reshape((-1,per))
	mean = []
	for tmp in inputs:
		mean.append(tmp.mean())
	return mean
 
'''
递推平均滤波法
'''
def SlidingAverage(inputs,per):
	if np.shape(inputs)[0] % per != 0:
		lengh = np.shape(inputs)[0] / per
		for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
			inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
	inputs = inputs.reshape((-1,per))
	tmpmean = inputs[0].mean()
	mean = []
	for tmp in inputs:
		mean.append((tmpmean+tmp.mean())/2)
		tmpmean = tmp.mean()
	return mean
 
'''
中位值平均滤波法
'''
def MedianAverage(inputs,per):
	if np.shape(inputs)[0] % per != 0:
		lengh = np.shape(inputs)[0] / per
		for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
			inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
	inputs = inputs.reshape((-1,per))
	mean = []
	for tmp in inputs:
		tmp = np.delete(tmp,np.where(tmp==tmp.max())[0],axis = 0)
		tmp = np.delete(tmp,np.where(tmp==tmp.min())[0],axis = 0)
		mean.append(tmp.mean())
	return mean
 
'''
限幅平均滤波法
Amplitude:	限制最大振幅
'''
def AmplitudeLimitingAverage(inputs,per,Amplitude):
	if np.shape(inputs)[0] % per != 0:
		lengh = np.shape(inputs)[0] / per
		for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
			inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
	inputs = inputs.reshape((-1,per))
	mean = []
	tmpmean = inputs[0].mean()
	tmpnum = inputs[0][0]						#上一次限幅后结果
	for tmp in inputs:
		for index,newtmp in enumerate(tmp):
			if np.abs(tmpnum-newtmp) > Amplitude:
				tmp[index] = tmpnum
			tmpnum = newtmp
		mean.append((tmpmean+tmp.mean())/2)
		tmpmean = tmp.mean()
	return mean
 
'''
一阶滞后滤波法
a:			滞后程度决定因子,0~1
'''
def FirstOrderLag(inputs,a):
	tmpnum = inputs[0]							#上一次滤波结果
	for index,tmp in enumerate(inputs):
		inputs[index] = (1-a)*tmp + a*tmpnum
		tmpnum = tmp
	return inputs
 
'''
加权递推平均滤波法
'''
def WeightBackstepAverage(inputs,per):
	weight = np.array(range(1,np.shape(inputs)[0]+1))			#权值列表
	weight = weight/weight.sum()
 
	for index,tmp in enumerate(inputs):
		inputs[index] = inputs[index]*weight[index]
	return inputs
 
'''
消抖滤波法
N:			消抖上限
'''
def ShakeOff(inputs,N):
	usenum = inputs[0]								#有效值
	i = 0 											#标记计数器
	for index,tmp in enumerate(inputs):
		if tmp != usenum:					
			i = i + 1
			if i >= N:
				i = 0
				inputs[index] = usenum
	return inputs
 
'''
限幅消抖滤波法
Amplitude:	限制最大振幅
N:			消抖上限
'''
def AmplitudeLimitingShakeOff(inputs,Amplitude,N):
	#print(inputs)
	tmpnum = inputs[0]
	for index,newtmp in enumerate(inputs):
		if np.abs(tmpnum-newtmp) > Amplitude:
			inputs[index] = tmpnum
		tmpnum = newtmp
	#print(inputs)
	usenum = inputs[0]
	i = 0
	for index2,tmp2 in enumerate(inputs):
		if tmp2 != usenum:
			i = i + 1
			if i >= N:
				i = 0
				inputs[index2] = usenum
	#print(inputs)
	return inputs
 
T = np.arange(0, 0.5, 1/4410.0)
num = signal.chirp(T, f0=10, t1 = 0.5, f1=1000.0)
pl.subplot(2,1,1)
pl.plot(num)
result = ArithmeticAverage(num.copy(),30)
 
#print(num - result)
pl.subplot(2,1,2)
pl.plot(result)
pl.show()

限幅滤波法(又称程序判断滤波法)

设定两次采样允许的最大偏差为A
如果(本次值-上次值)的绝对值大于A,则本次值无效,用上次值代替本次值
如果(本次值-上次值)的绝对值小于等于于A,则本次值有效,采用本次值

优点:  能有效克服因偶然因素引起的脉冲干扰  

缺点  无法抑制那种周期性的干扰  平滑度差  

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

plt.figure(figsize = (20,8))
list_s = []

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')

for i in range(len(s)-1):
    if abs(s[i+1] - s[i]) >= 15:
        s[i+1] = s[i]
    list_s.append(s[i+1])

plt.plot(list_s,label = '滤波后数据')
plt.title('限幅滤波法')
plt.legend()
plt.show()
中位值滤波法  

方法:  连续采样N次(N取奇数)  把N次采样值按大小排列  取中位数为本次有效值 

优点:  能有效克服因偶然因素引起的波动干扰  对温度、液位的变化缓慢的被测参数有良好的滤波效果  

缺点:  对流量、速度等快速变化的参数不宜  

plt.figure(figsize = (20,8))

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')

n = 7     #一次采样的次数
rank = []
for i in range(int(len(s)/n)):
    select_s = s[i*n:(i+1)*n]     #切片选取一次采样的个数
    mid_s = np.median(select_s)
    for j in range(n):       #将取到的值都赋值为中值,方便画图体现,实际中可以只要一次值
        rank.append(mid_s)

plt.plot(rank,label = '滤波后的数据')
plt.title('中值滤波算法')
plt.legend()
plt.show()
算术平均滤波法

 方法:  连续取N个采样值进行算术平均运算,得到的平均数为本次采样结果  

N值较大时:信号平滑度较高,但灵敏度较低 

N值较小时:信号平滑度较低,但灵敏度较高  

N值的选取:一般流量,N=12;压力:N=4 

优点:  适用于对一般具有随机干扰的信号进行滤波  这样信号的特点是有一个平均值,信号在某一数值范围附近上下波动  

缺点:  对于测量速度较慢或要求数据计算速度较快的实时控制不适用  比较浪费RAM  

plt.figure(figsize = (20,8))

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')
mean = []
n = 7     #一次采样的次数
for i in range(int(len(s)/n)):
    select_s = s[i*n:(i+1)*n]     #切片选取一次采样的个数
    mean_s = np.mean(select_s)
    for j in range(n):       #将取到的值都赋值为平均值,方便画图体现,实际中可以只要一次值
        mean.append(mean_s)

plt.plot(mean,label = '滤波后的数据')
plt.title('算数平均滤波算法')
plt.legend()
plt.show()

'''
算术平均滤波法(另一篇文章的代码)

def ArithmeticAverage(inputs,per):
    if np.shape(inputs)[0] % per != 0:
        lengh = np.shape(inputs)[0] / per
        for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
            inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
    inputs = inputs.reshape((-1,per))
    mean = []
    for tmp in inputs:
        mean.append(tmp.mean())
    return mean
'''
递推平均滤波法(又称滑动平均滤波法) 

方法:  把连续取N个采样值看成一个队列,遵循先进先出原则  队列的长度固定为N  每次采样到一个新数据放入队尾,并扔掉原来队首的一次数据.(先进先出原则)  把队列中的N个数据进行算术平均运算,就可获得新的滤波结果  N值的选取:流量,N=12;压力:N=4;液面,N=4~12;温度,N=1~4 

优点:  对周期性干扰有良好的抑制作用,平滑度高  适用于高频振荡的系统 

缺点:  灵敏度低  对偶然出现的脉冲性干扰的抑制作用较差  不易消除由于脉冲干扰所引起的采样值偏差  不适用于脉冲干扰比较严重的场合  比较浪费RAM  

plt.figure(figsize = (20,8))

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')

N = 7      #队列大小
mean_list = []
select_s = list(s[i:i+N])      #先选择一个队列的数据,求平均
mean = np.mean(select_s)
select_s.insert(len(select_s),select_s[0])    #左移一位
select_s.remove(select_s[0])
#select_s[-1] = mean
mean_list.append(mean)

for i in range(len(s)-N):       #然后添加一个新数据,左移一位,去头去尾,重复迭代
    select_s.append(s[i+N])
    select_s.insert(len(select_s),select_s[0])    #左移一位
    select_s.remove(select_s[0])
    select_s.remove(select_s[-1])
    mean = np.mean(select_s)
    #select_s[-1] = mean
    mean_list.append(mean)

plt.plot(mean_list,label = '滤波后的数据')
plt.title('滑动平均滤波算法')
plt.legend()
plt.show()


'''
递推平均滤波法

def SlidingAverage(inputs,per):
    if np.shape(inputs)[0] % per != 0:
        lengh = np.shape(inputs)[0] / per
        for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
            inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
    inputs = inputs.reshape((-1,per))
    tmpmean = inputs[0].mean()
    mean = []
    for tmp in inputs:
        mean.append((tmpmean+tmp.mean())/2)
        tmpmean = tmp.mean()
    return mean
'''
中位值平均滤波法(又称防脉冲干扰平均滤波法)  

方法:  相当于“中位值滤波法”+“算术平均滤波法”  连续采样N个数据,去掉一个最大值和一个最小值  然后计算N-2个数据的算术平均值  N值的选取:3~14  

优点:  融合了两种滤波法的优点  对于偶然出现的脉冲性干扰,可消除由于脉冲干扰所引起的采样值偏差  

缺点:  测量速度较慢,和算术平均滤波法一样  比较浪费RAM  

plt.figure(figsize = (20,8))

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')
mean = []
n = 7     #一次采样的次数
for i in range(int(len(s)/n)):
    select_s = s[i*n:(i+1)*n]     #切片选取一次采样的个数
    select_s = sorted(select_s)
    select_s.remove(select_s[0])
    select_s.remove(select_s[-1])

    mean_s = np.mean(select_s)
    for j in range(n):       #将取到的值都赋值为平均值,方便画图体现,实际中可以只要一次值
        mean.append(mean_s)

plt.plot(mean,label = '滤波后的数据')
plt.title('中位值平均滤波算法')
plt.legend()
plt.show()

'''
中位值平均滤波法

def MedianAverage(inputs,per):
    if np.shape(inputs)[0] % per != 0:
        lengh = np.shape(inputs)[0] / per
        for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
            inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
    inputs = inputs.reshape((-1,per))
    mean = []
    for tmp in inputs:
        tmp = np.delete(tmp,np.where(tmp==tmp.max())[0],axis = 0)
        tmp = np.delete(tmp,np.where(tmp==tmp.min())[0],axis = 0)
        mean.append(tmp.mean())
    return mean

'''
限幅平均滤波法 

方法:  相当于“限幅滤波法”+“递推平均滤波法”  每次采样到的新数据先进行限幅处理,  再送入队列进行递推平均滤波处理  (此处稍微做了改动,代码中将每次得到的平均值送入队尾,这样得到的滤波数据更偏向于稳定)

优点:  融合了两种滤波法的优点  对于偶然出现的脉冲性干扰,可消除由于脉冲干扰所引起的采样值偏差  

缺点:  比较浪费RAM  

plt.figure(figsize = (20,8))

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')

N = 8      #队列大小
mean_list = []
select_s = list(s[i:i+N])      #先选择一个队列的数据,求平均
mean = np.mean(select_s)
select_s.insert(len(select_s),select_s[0])    #左移一位
select_s.remove(select_s[0])
select_s[-1] = mean
mean_list.append(mean)

for i in range(len(s)-N):       #然后添加一个新数据,左移一位,去头去尾,重复迭代
    if abs(select_s[-1] - s[i+N]) >= 30:
        s[i+N] = select_s[-1]
    else:
        s[i+N] = s[i+N]

    select_s.append(s[i+N])
    select_s.insert(len(select_s),select_s[0])    #左移一位
    select_s.remove(select_s[0])
    select_s.remove(select_s[-1])
    mean = np.mean(select_s)
    select_s[-1] = mean
    mean_list.append(mean)

plt.plot(mean_list,label = '滤波后的数据')
plt.title('限幅平均滤波算法')
plt.legend()
plt.show()

'''
限幅平均滤波法
Amplitude:    限制最大振幅

def AmplitudeLimitingAverage(inputs,per,Amplitude):
    if np.shape(inputs)[0] % per != 0:
        lengh = np.shape(inputs)[0] / per
        for x in range(int(np.shape(inputs)[0]),int(lengh + 1)*per):
            inputs = np.append(inputs,inputs[np.shape(inputs)[0]-1])
    inputs = inputs.reshape((-1,per))
    mean = []
    tmpmean = inputs[0].mean()
    tmpnum = inputs[0][0]                        #上一次限幅后结果
    for tmp in inputs:
        for index,newtmp in enumerate(tmp):
            if np.abs(tmpnum-newtmp) > Amplitude:
                tmp[index] = tmpnum
            tmpnum = newtmp
        mean.append((tmpmean+tmp.mean())/2)
        tmpmean = tmp.mean()
    return mean

'''
一阶滞后滤波法 

方法:  取a=0~1  本次滤波结果=(1-a)*本次采样值+a*上次滤波结果 

优点:  对周期性干扰具有良好的抑制作用  适用于波动频率较高的场合  

缺点:  相位滞后,灵敏度低  滞后程度取决于a值大小  不能消除滤波频率高于采样频率的1/2的干扰信号  

plt.figure(figsize = (20,8))
list_s = []

s = np.random.normal(0,25,400)
plt.plot(s,label = '原始数据')
a = 0.7    #a取0-1之间,a越接近1越稳定,越接近0越灵敏

for i in range(len(s)-1):
    s[i+1] = (1-a) * s[i+1] + a * s[i]
    list_s.append(s[i+1])

plt.plot(list_s,label = '滤波后数据')
plt.title('一阶滞后滤波算法')
plt.legend()
plt.show()

'''
一阶滞后滤波法
a:            滞后程度决定因子,0~1

def FirstOrderLag(inputs,a):
    tmpnum = inputs[0]                            #上一次滤波结果
    for index,tmp in enumerate(inputs):
        inputs[index] = (1-a)*tmp + a*tmpnum
        tmpnum = tmp
    return inputs

'''
加权递推平均滤波法 

 方法:  是对递推平均滤波法的改进,即不同时刻的数据加以不同的权  通常是,越接近现时刻的数据,权取得越大。  给予新采样值的权系数越大,则灵敏度越高,但信号平滑度越低 

优点:  适用于有较大纯滞后时间常数的对象  和采样周期较短的系统  

缺点:  对于纯滞后时间常数较小,采样周期较长,变化缓慢的信号  不能迅速反应系统当前所受干扰的严重程度,滤波效果差 

'''
加权递推平均滤波法
'''
def WeightBackstepAverage(inputs,per):
    weight = np.array(range(1,np.shape(inputs)[0]+1))            #权值列表
    weight = weight/weight.sum()

    for index,tmp in enumerate(inputs):
        inputs[index] = inputs[index]*weight[index]
    return inputs
消抖滤波法  

方法:  设置一个滤波计数器  将每次采样值与当前有效值比较:  如果采样值=当前有效值,则计数器清零  如果采样值<>当前有效值,则计数器+1,并判断计数器是否>=上限N(溢出)  如果计数器溢出,则将本次值替换当前有效值,并清计数器  

优点:  对于变化缓慢的被测参数有较好的滤波效果,  可避免在临界值附近控制器的反复开/关跳动或显示器上数值抖动  

缺点:  对于快速变化的参数不宜  如果在计数器溢出的那一次采样到的值恰好是干扰值,则会将干扰值当作有效值导入系统  

'''
消抖滤波法
N:            消抖上限
'''
def ShakeOff(inputs,N):
    usenum = inputs[0]                                #有效值
    i = 0                                             #标记计数器
    for index,tmp in enumerate(inputs):
        if tmp != usenum:
            i = i + 1
            if i >= N:
                i = 0
                inputs[index] = usenum
    return inputs
限幅消抖滤波法  

方法:  相当于“限幅滤波法”+“消抖滤波法”  先限幅,后消抖  

优点:  继承了“限幅”和“消抖”的优点  改进了“消抖滤波法”中的某些缺陷,避免将干扰值导入系统  

缺点:  对于快速变化的参数不宜 

'''
限幅消抖滤波法
Amplitude:    限制最大振幅
N:            消抖上限
'''
def AmplitudeLimitingShakeOff(inputs,Amplitude,N):
    #print(inputs)
    tmpnum = inputs[0]
    for index,newtmp in enumerate(inputs):
        if np.abs(tmpnum-newtmp) > Amplitude:
            inputs[index] = tmpnum
        tmpnum = newtmp
    #print(inputs)
    usenum = inputs[0]
    i = 0
    for index2,tmp2 in enumerate(inputs):
        if tmp2 != usenum:
            i = i + 1
            if i >= N:
                i = 0
                inputs[index2] = usenum
    #print(inputs)
    return inputs

T = np.arange(0, 0.5, 1/4410.0)
num = signal.chirp(T, f0=10, t1 = 0.5, f1=1000.0)
pl.subplot(2,1,1)
pl.plot(num)
result = ArithmeticAverage(num.copy(),30)

#print(num - result)
pl.subplot(2,1,2)
pl.plot(result)
pl.show() 

  • 14
    点赞
  • 107
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
自适应LMS滤波算法是一种常见的数字信号处理算法,可以用于信号降噪、信号分离、信号估计等领域。下面是用Python实现自适应LMS滤波算法的代码示例: ```python import numpy as np def lms_filter(x, d, M, mu): """ 自适应LMS滤波算法 :param x: 输入信号 :param d: 目标信号 :param M: 滤波器阶数 :param mu: 步长因子 :return: 滤波器系数和滤波后的输出信号 """ N = len(x) w = np.zeros(M) # 初始化滤波器系数 y = np.zeros(N-M) # 初始化输出信号 for n in range(M, N): x_n = x[n-M:n] # 取M个输入信号 y[n-M] = np.dot(w, x_n) # 计算输出信号 e = d[n] - y[n-M] # 计算误差 delta_w = mu * e * x_n # 计算权值更新量 w = w + delta_w # 更新滤波器系数 return w, y ``` 其中,`x`表示输入信号,`d`表示目标信号,`M`表示滤波器的阶数,`mu`表示步长因子。函数返回滤波器系数和滤波后的输出信号。 下面是一个示例: ```python import matplotlib.pyplot as plt # 生成带噪音的信号 t = np.arange(0, 1, 0.01) x = np.sin(2*np.pi*10*t) + 0.5*np.random.randn(len(t)) # 生成目标信号 d = np.sin(2*np.pi*10*t) # 自适应LMS滤波 M = 50 mu = 0.01 w, y = lms_filter(x, d, M, mu) # 绘制结果 plt.plot(t, x, label='Input Signal') plt.plot(t, d, label='Desired Signal') plt.plot(t[M:], y, label='Output Signal') plt.legend() plt.show() ``` 运行上述代码,可以得到滤波后的结果图像。可以看到,自适应LMS滤波算法可以有效地去除输入信号中的噪音,提取出目标信号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值