电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python實現(xiàn)低通濾波器代碼

瀏覽:113日期:2022-08-06 10:38:40

低通濾波器實驗代碼,這是參考別人網(wǎng)上的代碼,所以自己也分享一下,共同進步

# -*- coding: utf-8 -*-import numpy as npfrom scipy.signal import butter, lfilter, freqzimport matplotlib.pyplot as pltdef 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, adef 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 = 6fs = 30.0 # sample rate, Hzcutoff = 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 # secondsn = int(T * fs) # total number of samplest = 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 npfrom scipy.signal import butter, lfilter, freqzimport matplotlib.pyplot as pltimport osdef 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, adef 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 = 5fs = 100000.0 # sample rate, Hzcutoff = 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實現(xiàn)低通濾波器代碼

其中,D0表示通帶的半徑。D(u,v)的計算方式也就是兩點間的距離,很簡單就能得到。

python實現(xiàn)低通濾波器代碼

使用低通濾波器所得到的結果如下所示。低通濾波器濾除了高頻成分,所以使得圖像模糊。由于理想低通濾波器的過度特性過于急峻,所以會產(chǎn)生了振鈴現(xiàn)象。

python實現(xiàn)低通濾波器代碼

2.巴特沃斯低通濾波器

python實現(xiàn)低通濾波器代碼

同樣的,D0表示通帶的半徑,n表示的是巴特沃斯濾波器的次數(shù)。隨著次數(shù)的增加,振鈴現(xiàn)象會越來越明顯。

python實現(xiàn)低通濾波器代碼

void ideal_Low_Pass_Filter(Mat src){Mat img;cvtColor(src, img, CV_BGR2GRAY);imshow('img',img);//調(diào)整圖像加速傅里葉變換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文檔//其實是為了把行和列變成偶數(shù) -2的二進制是11111111.......10 最后一位是0//獲取中心點坐標int cx = mag.cols / 2;int cy = mag.rows / 2;//調(diào)整頻域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;}}}//再調(diào)整頻域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 IDFTinvDFT.convertTo(invDFTcvt, CV_8U);imshow('理想低通濾波器', invDFTcvt);} void Butterworth_Low_Paass_Filter(Mat src){int n = 1;//表示巴特沃斯濾波器的次數(shù)//H = 1 / (1+(D/D0)^2n)Mat img;cvtColor(src, img, CV_BGR2GRAY);imshow('img', img);//調(diào)整圖像加速傅里葉變換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 IDFTinvDFT.convertTo(invDFTcvt, CV_8U);imshow('巴特沃斯低通濾波器', invDFTcvt);}

以上這篇python實現(xiàn)低通濾波器代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 芜湖厨房设备_芜湖商用厨具_芜湖厨具设备-芜湖鑫环厨具有限公司 控显科技 - 工控一体机、工业显示器、工业平板电脑源头厂家 | 游泳池设备安装工程_恒温泳池设备_儿童游泳池设备厂家_游泳池水处理设备-东莞市君达泳池设备有限公司 | 广西教师资格网-广西教师资格证考试网| 焦作网 WWW.JZRB.COM | 深圳宣传片制作-企业宣传视频制作-产品视频拍摄-产品动画制作-短视频拍摄制作公司 | 油漆辅料厂家_阴阳脚线_艺术漆厂家_内外墙涂料施工_乳胶漆专用防霉腻子粉_轻质粉刷石膏-魔法涂涂 | 识禅_对禅的了解,从这里开始| 首页-浙江橙树网络技术有限公司 石磨面粉机|石磨面粉机械|石磨面粉机组|石磨面粉成套设备-河南成立粮油机械有限公司 | 智能气瓶柜(大型气瓶储存柜)百科 | 牛皮纸|牛卡纸|进口牛皮纸|食品级牛皮纸|牛皮纸厂家-伽立实业 | 电脑知识|软件|系统|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网 | 喷涂流水线,涂装流水线,喷漆流水线-山东天意设备科技有限公司 | 常州减速机_减速机厂家_常州市减速机厂有限公司 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 至顶网| 物联网卡_物联网卡购买平台_移动物联网卡办理_移动联通电信流量卡通信模组采购平台? | 塑胶跑道施工-硅pu篮球场施工-塑胶网球场建造-丙烯酸球场材料厂家-奥茵 | 济南品牌包装设计公司_济南VI标志设计公司_山东锐尚文化传播 | 沈阳真空机_沈阳真空包装机_沈阳大米真空包装机-沈阳海鹞真空包装机械有限公司 | 哈尔滨京科脑康神经内科医院-哈尔滨治疗头痛医院-哈尔滨治疗癫痫康复医院 | 两头忙,井下装载机,伸缩臂装载机,30装载机/铲车,50装载机/铲车厂家_价格-莱州巨浪机械有限公司 | 东莞市超赞电子科技有限公司 全系列直插/贴片铝电解电容,电解电容,电容器 | 山东商品混凝土搅拌楼-环保型搅拌站-拌合站-分体仓-搅拌机厂家-天宇 | 警方提醒:赣州约炮论坛真的安全吗?2025年新手必看的网络交友防坑指南 | 外贮压-柜式-悬挂式-七氟丙烷-灭火器-灭火系统-药剂-价格-厂家-IG541-混合气体-贮压-非贮压-超细干粉-自动-灭火装置-气体灭火设备-探火管灭火厂家-东莞汇建消防科技有限公司 | 瑞典Blueair空气净化器租赁服务中心-专注新装修办公室除醛去异味服务! | 山东钢衬塑罐_管道_反应釜厂家-淄博富邦滚塑防腐设备科技有限公司 | 石家庄网站建设|石家庄网站制作|石家庄小程序开发|石家庄微信开发|网站建设公司|网站制作公司|微信小程序开发|手机APP开发|软件开发 | 斗式提升机_链式斗提机_带式斗提机厂家无锡市鸿诚输送机械有限公司 | 蜘蛛车-登高车-高空作业平台-高空作业车-曲臂剪叉式升降机租赁-重庆海克斯公司 | 地埋式垃圾站厂家【佳星环保】小区压缩垃圾中转站转运站 | 郑州律师咨询-郑州律师事务所_河南锦盾律师事务所 | 河南砖机首页-全自动液压免烧砖机,小型砌块水泥砖机厂家[十年老厂] | 湖南教师资格网-湖南教师资格证考试网 | 对夹式止回阀_对夹式蝶形止回阀_对夹式软密封止回阀_超薄型止回阀_不锈钢底阀-温州上炬阀门科技有限公司 | 防爆型气象站_农业气象站_校园气象站_农业四情监测系统「山东万象环境科技有限公司」 | 下水道疏通_管道疏通_马桶疏通_附近疏通电话- 立刻通 | 一体化污水处理设备_生活污水处理设备_全自动加药装置厂家-明基环保 | UV固化机_UVLED光固化机_UV干燥机生产厂家-上海冠顶公司专业生产UV固化机设备 | 背压阀|减压器|不锈钢减压器|减压阀|卫生级背压阀|单向阀|背压阀厂家-上海沃原自控阀门有限公司 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 一体化污水处理设备_生活污水处理设备_全自动加药装置厂家-明基环保 |