python实现低通滤波器代码

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

# -*- 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.理想的低通滤波器

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

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

2.巴特沃斯低通滤波器

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

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实现低通滤波器代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python实现中值滤波去噪方式

    中值滤波器去噪: 中值滤波的主要原理是将数字图像中的某点用该点的邻域中各个像素值的中值所来代替,这样就能让目标像素周围能够更好的接近真实值,比如一张白纸上有一个黑点时,黑点的像素值比较大,经过中值滤波过后,黑点附近的像素值可能就会变小.经过中值滤波后一些相对孤立的噪声点就容易被清除掉,这样就能提高图像的质量. 所以中值滤波器去噪的一个优点就是对椒盐噪声的去除具有很好的效果,具体操作是选取一个中心邻域,然后给邻域类各个像素的灰度值按大小进行排序,选取排序序列中的中值作为该邻域中心点的像素值的灰度值

  • Python利用FFT进行简单滤波的实现

    1.流程 大体流程如下,无论图像.声音.ADC数据都是如下流程: (1)将原信号进行FFT; (2)将进行FFT得到的数据去掉需要滤波的频率: (3)进行FFT逆变换得到信号数据: 2.算法仿真 2.1 生成数据: #采样点选择1400个,因为设置的信号频率分量最高为600Hz,根据采样定理知采样频率要大于信号频率2倍,所以这里设置采样频率为1400Hz(即一秒内有1400个采样点) x=np.linspace(0,1,1400) #设置需要采样的信号,频率分量有180,390和600 y=2*

  • python实现逆滤波与维纳滤波示例

    构建运动模糊模型 现假定相机不动,图像f(x,y)在图像面上移动并且图像f(x,y)除移动外不随时间变化.令x0(t)和y0(t)分别代表位移的x分量和y分量,那么在快门开启的时间T内,胶片上某点的总曝光量是图像在移动过程中一系列相应像素的亮度对该点作用之总和.也就是说,运动模糊图像是由同一图像在产生距离延迟后与原图像想叠加而成.如果快门开启与关闭的时间忽略不计,则有: 由于各种运动都是匀速直线运动的叠加,因而我们只需考虑匀速直线运动即可.但由于我们自身水平有限,且旨在探讨找到实现运动模糊复原方

  • python实现低通滤波器代码

    低通滤波器实验代码,这是参考别人网上的代码,所以自己也分享一下,共同进步 # -*- 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

  • Python定时器实例代码

    在实际应用中,我们经常需要使用定时器去触发一些事件.Python中通过线程实现定时器timer,其使用非常简单.看示例: import threading def fun_timer(): print('Hello Timer!') timer = threading.Timer(1, fun_timer) timer.start() 输出结果: Hello Timer! Process finished with exit code 0 注意,只输出了一次,程序就结束了,显然不是我们想要的结果

  • python对html代码进行escape编码的方法

    本文实例讲述了python对html代码进行escape编码的方法.分享给大家供大家参考.具体分析如下: python包含一个cgi模块,该模块有一个escape函数可以用来对html代码进行编码转换 import cgi s1 = "Hello <strong>world</strong>" s2 = cgi.escape(s1) assert s2 == "Hello <strong>world</strong>"

  • Python在线运行代码助手

    Python代码运行助手可以让你在线输入Python代码,然后通过本机运行的一个Python脚本来执行代码.原理如下: 在网页输入代码: 点击Run按钮,代码被发送到本机正在运行的Python代码运行助手: Python代码运行助手将代码保存为临时文件,然后调用Python解释器执行代码: 网页显示代码执行结果: 下载 点击右键,目标另存为:learning.py 备用下载地址:learning.py 完整代码: #!/usr/bin/env python3 # -*- coding: utf-

  • python 随机数生成的代码的详细分析

    以下的文章主要是以介绍python随机数生成的代码来介绍Python随机数生成在实际操作过程中的具体应用,如果你对其的相关内容感兴趣的话,你就可以点击以下的文章.希望你会对它有所收获. Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. 复制代码 代码如下: random.randomrandom.random() 用于生成一个0到1的随机符点数: 复制代码 代码如下: 0 <= n < 1.0random.uniformrandom.unifor

  • Python实现统计代码行的方法分析

    本文实例讲述了Python实现统计代码行的方法.分享给大家供大家参考,具体如下: 参加光荣之路测试开发班已三月有余,吴总上课也总问" 咱们的课上了这么多次了大家实践了多少行代码了?".这里是一个一脸懵逼的表情.该怎么统计呢?一个个文件数当然不可取,能用代码解决的事咱们坚决不动手.最近在网上刷题时也正好遇到有这么一道题,所以决定撸一撸. 题目:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码.包括空行和注释,但是要分别列出来. 首先分析一下思路捋一下大象装冰箱的步骤,从一个给定

  • python实现统计代码行数的方法

    本文实例讲述了python实现统计代码行数的方法.分享给大家供大家参考.具体实现方法如下: ''' Author: liupengfei Function: count lines of code in a folder iteratively Shell-format: cmd [dir] Attention: default file encode is utf8 and default file type is java-source-file. But users can customi

  • Python实现去除代码前行号的方法

    本文实例讲述了Python实现去除代码前行号的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: # -*- coding: utf-8 -*- import wx class MainWindow(wx.Frame):     def __init__(self, parent, id):         wx.Frame.__init__(self, parent, id,         u'去除代码前行号的Python小工具 - wxPython版 - Develop

  • Python科学画图代码分享

    Python画图主要用到matplotlib这个库.Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形. 这里有一本电子书供大家参考:<Python图表绘制:matplotlib绘图库入门> 具体来说是pylab和pyplot这两个子库.这两个库可以满足基本的画图需求,而条形图,散点图等特殊图,下面再单独具体介绍. 首先给出pylab神器镇文:pylab.rcParams.update(params).这个函数几乎可以调节图

  • Python实现调度算法代码详解

    调度算法 操作系统管理了系统的有限资源,当有多个进程(或多个进程发出的请求)要使用这些资源时,因为资源的有限性,必须按照一定的原则选择进程(请求)来占用资源.这就是调度.目的是控制资源使用者的数量,选取资源使用者许可占用资源或占用资源. 在操作系统中调度是指一种资源分配,因而调度算法是指:根据系统的资源分配策略所规定的资源分配算法.对于不同的的系统和系统目标,通常采用不同的调度算法,例如,在批处理系统中,为了照顾为数众多的段作业,应采用短作业优先的调度算法:又如在分时系统中,为了保证系统具有合理

随机推荐