python实现低通滤波器代码


Posted in Python onFebruary 26, 2020

低通滤波器实验代码,这是参考别人网上的代码,所以自己也分享一下,共同进步

# -*- coding: utf-8 -*-

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
 nyq = 0.5 * fs
 normal_cutoff = cutoff / nyq
 b, a = butter(order, normal_cutoff, btype='low', analog=False)
 return b, a


def butter_lowpass_filter(data, cutoff, fs, order=5):
 b, a = butter_lowpass(cutoff, fs, order=order)
 y = lfilter(b, a, data)
 return y # Filter requirements.


order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz # Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order) # Plot the frequency response.
w, h = freqz(b, a, worN=800)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid() # Demonstrate the use of the filter. # First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False) # "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t) # Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()

实际代码,没有整理,可以读取txt文本文件,然后进行低通滤波,并将滤波前后的波形和FFT变换都显示出来

# -*- coding: utf-8 -*-

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
import os


def butter_lowpass(cutoff, fs, order=5):
 nyq = 0.5 * fs
 normal_cutoff = cutoff / nyq
 b, a = butter(order, normal_cutoff, btype='low', analog=False)
 return b, a


def butter_lowpass_filter(data, cutoff, fs, order=5):
 b, a = butter_lowpass(cutoff, fs, order=order)
 y = lfilter(b, a, data)
 return y # Filter requirements.


order = 5
fs = 100000.0 # sample rate, Hz
cutoff = 1000 # desired cutoff frequency of the filter, Hz # Get the filter coefficients so we can check its frequency response.
# b, a = butter_lowpass(cutoff, fs, order) # Plot the frequency response.
# w, h = freqz(b, a, worN=1000)
# plt.subplot(3, 1, 1)
# plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
# plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
# plt.axvline(cutoff, color='k')
# plt.xlim(0, 1000)
# plt.title("Lowpass Filter Frequency Response")
# plt.xlabel('Frequency [Hz]')
# plt.grid() # Demonstrate the use of the filter. # First make some data to be filtered.
# T = 5.0 # seconds
# n = int(T * fs) # total number of samples
# t = np.linspace(0, T, n, endpoint=False) # "Noisy" data. We want to recover the 1.2 Hz signal from this.
# # data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t) # Filter the data, and plot both the original and filtered signals.


path = "*****"

for file in os.listdir(path):
 if file.endswith("txt"):
  data=[]
  filePath = os.path.join(path, file)
  with open(filePath, 'r') as f:
   lines = f.readlines()[8:]
   for line in lines:
    # print(line)
    data.append(float(line)*100)
  # print(len(data))
  t1=[i*10 for i in range(len(data))]
  plt.subplot(231)
  # plt.plot(range(len(data)), data)
  plt.plot(t1, data, linewidth=2,label='original data')
  # plt.title('ori wave', fontsize=10, color='#F08080')
  plt.xlabel('Time [us]')
  plt.legend()

  # filter_data = data[30000:35000]
  # filter_data=data[60000:80000]
  # filter_data2=data[60000:80000]
  # filter_data = data[80000:100000]
  # filter_data = data[100000:120000]
  filter_data = data[120000:140000]

  filter_data2=filter_data
  t2=[i*10 for i in range(len(filter_data))]
  plt.subplot(232)
  plt.plot(t2, filter_data, linewidth=2,label='cut off wave before filter')
  plt.xlabel('Time [us]')
  plt.legend()
  # plt.title('cut off wave', fontsize=10, color='#F08080')

  # filter_data=zip(range(1,len(data),int(fs/len(data))),data)
  # print(filter_data)
  n1 = len(filter_data)
  Yamp1 = abs(np.fft.fft(filter_data) / (n1 / 2))
  Yamp1 = Yamp1[range(len(Yamp1) // 2)]
  # x_axis=range(0,n//2,int(fs/len
  # 计算最大赋值点频率
  max1 = np.max(Yamp1)
  max1_index = np.where(Yamp1 == max1)
  if (len(max1_index[0]) == 2):
   print((max1_index[0][0] )* fs / n1, (max1_index[0][1]) * fs / n1)
  else:
   Y_second = Yamp1
   Y_second = np.sort(Y_second)
   print(np.where(Yamp1 == max1)[0] * fs / n1,
     (np.where(Yamp1 == Y_second[-2])[0]) * fs / n1)
  N1 = len(Yamp1)
  # print(N1)
  x_axis1 = [i * fs / n1 for i in range(N1)]

  plt.subplot(233)
  plt.plot(x_axis1[:300], Yamp1[:300], linewidth=2,label='FFT data')
  plt.xlabel('Frequence [Hz]')
  # plt.title('FFT', fontsize=10, color='#F08080')
  plt.legend()
  # plt.savefig(filePath.replace("txt", "png"))
  # plt.close()
  # plt.show()



  Y = butter_lowpass_filter(filter_data2, cutoff, fs, order)
  n3 = len(Y)
  t3 = [i * 10 for i in range(n3)]
  plt.subplot(235)
  plt.plot(t3, Y, linewidth=2, label='cut off wave after filter')
  plt.xlabel('Time [us]')
  plt.legend()
  Yamp2 = abs(np.fft.fft(Y) / (n3 / 2))
  Yamp2 = Yamp2[range(len(Yamp2) // 2)]
  # x_axis = range(0, n // 2, int(fs / len(Yamp)))
  max2 = np.max(Yamp2)
  max2_index = np.where(Yamp2 == max2)
  if (len(max2_index[0]) == 2):
   print(max2, max2_index[0][0] * fs / n3, max2_index[0][1] * fs / n3)
  else:
   Y_second2 = Yamp2
   Y_second2 = np.sort(Y_second2)
   print((np.where(Yamp2 == max2)[0]) * fs / n3,
     (np.where(Yamp2 == Y_second2[-2])[0]) * fs / n3)
  N2=len(Yamp2)
  # print(N2)
  x_axis2 = [i * fs / n3 for i in range(N2)]

  plt.subplot(236)
  plt.plot(x_axis2[:300], Yamp2[:300],linewidth=2, label='FFT data after filter')
  plt.xlabel('Frequence [Hz]')
  # plt.title('FFT after low_filter', fontsize=10, color='#F08080')
  plt.legend()
  # plt.show()
  plt.savefig(filePath.replace("txt", "png"))
  plt.close()
  print('*'*50)

  # plt.subplot(3, 1, 2)
  # plt.plot(range(len(data)), data, 'b-', linewidth=2,label='original data')
  # plt.grid()
  # plt.legend()
  #
  # plt.subplot(3, 1, 3)
  # plt.plot(range(len(y)), y, 'g-', linewidth=2, label='filtered data')
  # plt.xlabel('Time')
  # plt.grid()
  # plt.legend()
  # plt.subplots_adjust(hspace=0.35)
  # plt.show()
  '''
  # Y_fft = Y[60000:80000]
  Y_fft = Y
  # Y_fft = Y[80000:100000]
  # Y_fft = Y[100000:120000]
  # Y_fft = Y[120000:140000]
  n = len(Y_fft)
  Yamp = np.fft.fft(Y_fft)/(n/2)
  Yamp = Yamp[range(len(Yamp)//2)]

  max = np.max(Yamp)
  # print(max, np.where(Yamp == max))

  Y_second = Yamp
  Y_second=np.sort(Y_second)
  print(float(np.where(Yamp == max)[0])* fs / len(Yamp),float(np.where(Yamp==Y_second[-2])[0])* fs / len(Yamp))
  # print(float(np.where(Yamp == max)[0]) * fs / len(Yamp))
  '''

补充拓展:浅谈opencv的理想低通滤波器和巴特沃斯低通滤波器

低通滤波器

1.理想的低通滤波器

python实现低通滤波器代码

其中,D0表示通带的半径。D(u,v)的计算方式也就是两点间的距离,很简单就能得到。

python实现低通滤波器代码

使用低通滤波器所得到的结果如下所示。低通滤波器滤除了高频成分,所以使得图像模糊。由于理想低通滤波器的过度特性过于急峻,所以会产生了振铃现象。

python实现低通滤波器代码

2.巴特沃斯低通滤波器

python实现低通滤波器代码

同样的,D0表示通带的半径,n表示的是巴特沃斯滤波器的次数。随着次数的增加,振铃现象会越来越明显。

python实现低通滤波器代码

void ideal_Low_Pass_Filter(Mat src){
	Mat img;
	cvtColor(src, img, CV_BGR2GRAY);
	imshow("img",img);
	//调整图像加速傅里叶变换
	int M = getOptimalDFTSize(img.rows);
	int N = getOptimalDFTSize(img.cols);
	Mat padded;
	copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
	//记录傅里叶变换的实部和虚部
	Mat planes[] = { Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F) };
	Mat complexImg;
	merge(planes, 2, complexImg);
	//进行傅里叶变换
	dft(complexImg, complexImg);
	//获取图像
	Mat mag = complexImg;
	mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));//这里为什么&上-2具体查看opencv文档
	//其实是为了把行和列变成偶数 -2的二进制是11111111.......10 最后一位是0
	//获取中心点坐标
	int cx = mag.cols / 2;
	int cy = mag.rows / 2;
	//调整频域
	Mat tmp;
	Mat q0(mag, Rect(0, 0, cx, cy));
	Mat q1(mag, Rect(cx, 0, cx, cy));
	Mat q2(mag, Rect(0, cy, cx, cy));
	Mat q3(mag, Rect(cx, cy, cx, cy));
 
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);
 
	q1.copyTo(tmp);
	q2.copyTo(q1);
	tmp.copyTo(q2);
	//Do为自己设定的阀值具体看公式
	double D0 = 60;
	//处理按公式保留中心部分
	for (int y = 0; y < mag.rows; y++){
		double* data = mag.ptr<double>(y);
		for (int x = 0; x < mag.cols; x++){
			double d = sqrt(pow((y - cy),2) + pow((x - cx),2));
			if (d <= D0){
				
			}
			else{
				data[x] = 0;
			}
		}
	}
	//再调整频域
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);
	q1.copyTo(tmp);
	q2.copyTo(q1);
	tmp.copyTo(q2);
	//逆变换
	Mat invDFT, invDFTcvt;
	idft(mag, invDFT, DFT_SCALE | DFT_REAL_OUTPUT); // Applying IDFT
	invDFT.convertTo(invDFTcvt, CV_8U);
	imshow("理想低通滤波器", invDFTcvt);
}
 
void Butterworth_Low_Paass_Filter(Mat src){
	int n = 1;//表示巴特沃斯滤波器的次数
	//H = 1 / (1+(D/D0)^2n)
	Mat img;
	cvtColor(src, img, CV_BGR2GRAY);
	imshow("img", img);
	//调整图像加速傅里叶变换
	int M = getOptimalDFTSize(img.rows);
	int N = getOptimalDFTSize(img.cols);
	Mat padded;
	copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
 
	Mat planes[] = { Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F) };
	Mat complexImg;
	merge(planes, 2, complexImg);
 
	dft(complexImg, complexImg);
 
	Mat mag = complexImg;
	mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
 
	int cx = mag.cols / 2;
	int cy = mag.rows / 2;
 
	Mat tmp;
	Mat q0(mag, Rect(0, 0, cx, cy));
	Mat q1(mag, Rect(cx, 0, cx, cy));
	Mat q2(mag, Rect(0, cy, cx, cy));
	Mat q3(mag, Rect(cx, cy, cx, cy));
 
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);
 
	q1.copyTo(tmp);
	q2.copyTo(q1);
	tmp.copyTo(q2);
 
	double D0 = 100;
 
	for (int y = 0; y < mag.rows; y++){
		double* data = mag.ptr<double>(y);
		for (int x = 0; x < mag.cols; x++){
			//cout << data[x] << endl;
			double d = sqrt(pow((y - cy), 2) + pow((x - cx), 2));
			//cout << d << endl;
			double h = 1.0 / (1 + pow(d / D0, 2 * n));
			if (h <= 0.5){
				data[x] = 0;
			}
			else{
				//data[x] = data[x]*0.5;
				//cout << h << endl;
			}
			
			//cout << data[x] << endl;
		}
	}
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);
	q1.copyTo(tmp);
	q2.copyTo(q1);
	tmp.copyTo(q2);
	//逆变换
	Mat invDFT, invDFTcvt;
	idft(complexImg, invDFT, DFT_SCALE | DFT_REAL_OUTPUT); // Applying IDFT
	invDFT.convertTo(invDFTcvt, CV_8U);
	imshow("巴特沃斯低通滤波器", invDFTcvt);
}

以上这篇python实现低通滤波器代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 匹配任意字符(包括换行符)的正则表达式写法
Oct 29 Python
python网络编程学习笔记(10):webpy框架
Jun 09 Python
python变量不能以数字打头详解
Jul 06 Python
用python写个自动SSH登录远程服务器的小工具(实例)
Jun 17 Python
python 文件查找及内容匹配方法
Oct 25 Python
python 列表中[ ]中冒号‘:’的作用
Apr 30 Python
使用Python实现将list中的每一项的首字母大写
Jun 11 Python
Python字符串格式化输出代码实例
Nov 22 Python
Python面向对象中类(class)的简单理解与用法分析
Feb 21 Python
快速解决jupyter notebook启动需要密码的问题
Apr 21 Python
使用Tensorflow-GPU禁用GPU设置(CPU与GPU速度对比)
Jun 30 Python
python3 实现mysql数据库连接池的示例代码
Apr 17 Python
Python解释器及PyCharm工具安装过程
Feb 26 #Python
Python基础之列表常见操作经典实例详解
Feb 26 #Python
Python TKinter如何自动关闭主窗口
Feb 26 #Python
Flask和pyecharts实现动态数据可视化
Feb 26 #Python
Python图像处理库PIL的ImageEnhance模块使用介绍
Feb 26 #Python
Python基础之字符串常见操作经典实例详解
Feb 26 #Python
浅析python表达式4+0.5值的数据类型
Feb 26 #Python
You might like
linux mint下安装phpstorm2020包括JDK部分的教程详解
2020/09/17 PHP
学习ExtJS Panel常用方法
2009/10/07 Javascript
JQuery优缺点分析说明
2010/06/09 Javascript
jQuery EasyUI 的EasyLoader功能介绍
2010/09/12 Javascript
获取元素距离浏览器周边的位置的方法getBoundingClientRect
2013/04/17 Javascript
解析页面加载与js函数的执行 onload or ready
2013/12/12 Javascript
基于jQuery实现表单提交验证
2014/11/24 Javascript
node.js中的fs.readSync方法使用说明
2014/12/17 Javascript
js实现格式化金额,字符,时间的方法
2015/02/26 Javascript
详解JavaScript中getFullYear()方法的使用
2015/06/10 Javascript
JS实现图片平面旋转的方法
2016/03/01 Javascript
JS定时器使用,定时定点,固定时刻,循环执行详解
2016/05/31 Javascript
javascirpt实现2个iframe之间传值的方法
2016/06/30 Javascript
最丑的时钟效果!js canvas时钟制作方法
2016/08/15 Javascript
node.js中的事件处理机制详解
2016/11/26 Javascript
详解使用grunt完成requirejs的合并压缩和js文件的版本控制
2017/03/02 Javascript
react开发教程之React 组件之间的通信方式
2017/08/12 Javascript
Vue 换肤的示例实践
2018/01/23 Javascript
axios的拦截请求与响应方法
2018/08/11 Javascript
JavaScript和TypeScript中的void的具体使用
2019/09/12 Javascript
Vue文本模糊匹配功能如何实现
2020/07/30 Javascript
如何在Python中编写并发程序
2016/02/27 Python
将TensorFlow的模型网络导出为单个文件的方法
2018/04/23 Python
python tkinter窗口最大化的实现
2019/07/15 Python
python实现二分类的卡方分箱示例
2019/11/22 Python
python 定义类时,实现内部方法的互相调用
2019/12/25 Python
Python日志logging模块功能与用法详解
2020/04/09 Python
python实现简单的学生管理系统
2021/02/22 Python
Paradigit比利时电脑卖场:购买笔记本、电脑、平板和外围设备
2016/11/28 全球购物
金融与证券专业求职信
2014/06/22 职场文书
高二学年自我鉴定范文(2篇)
2014/09/26 职场文书
单位个人查摆问题及整改措施
2014/10/28 职场文书
2015年中秋节主持词
2015/07/30 职场文书
在酒桌上的敬酒词
2015/08/12 职场文书
2019求职信:应届生求职信范文
2019/04/24 职场文书
Python实现信息轰炸工具(再也不怕说不过别人了)
2021/06/11 Python