python实现小波变换去噪
# coding = gbk
# 使用小波分析进行阈值去噪声,使用pywt.threshold
import pywt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
data = np.linspace(1, 10, 10)
print(data)
# [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
# pywt.threshold(data, value, mode, substitute) mode 模式有4种,soft, hard, greater, less; substitute是替换值
data_soft = pywt.threshold(data=data, value=6, mode='soft', substitute=12)
print(data_soft)
# [12. 12. 12. 12. 12. 0. 1. 2. 3. 4.] 将小于6 的值设置为12, 大于等于6 的值全部减去6
data_hard = pywt.threshold(data=data, value=6, mode='hard', substitute=12)
print(data_hard)
# [12. 12. 12. 12. 12. 6. 7. 8. 9. 10.] 将小于6 的值设置为12, 其余的值不变
data_greater = pywt.threshold(data, 6, 'greater', 12)
print(data_greater)
# [12. 12. 12. 12. 12. 6. 7. 8. 9. 10.] 将小于6 的值设置为12,大于等于阈值的值不变化
data_less = pywt.threshold(data, 6, 'less', 12)
print(data_less)
# [ 1. 2. 3. 4. 5. 6. 12. 12. 12. 12.] 将大于6 的值设置为12, 小于等于阈值的值不变
#-*-coding:utf-8-*-
#get Data
ecg = pywt.data.ecg() #生成心电信号
index = []
data = []
coffs = []
for i in range(len(ecg)-1):
X = float(i)
Y = float(ecg[i])
index.append(X)
data.append(Y)
#create wavelet object and define parameters
w = pywt.Wavelet('db8') #选用Daubechies8小波
maxlev = pywt.dwt_max_level(len(data),w.dec_len)
print("maximum level is" + str(maxlev))
threshold = 0.1 #Threshold for filtering
#Decompose into wavelet components,to the level selected:
coffs=pywt.wavedec(data,'db8',level=maxlev) #将信号进行小波分解
for i in range(1, len(coffs)):
coffs[i] = pywt.threshold(coffs[i], threshold*max(coffs[i]))
datarec = pywt.waverec(coffs, 'db8') #将信号进行小波重构
mintime = 0
maxtime = mintime + len(data)
print(mintime, maxtime)
plt.figure()
plt.subplot(3,1,1)
plt.plot(index[mintime:maxtime], data[mintime:maxtime])
plt.xlabel('time (s)')
plt.ylabel('microvolts (uV)')
plt.title("Raw signal")
plt.subplot(3, 1, 2)
plt.plot(index[mintime:maxtime], datarec[mintime:maxtime])
plt.xlabel('time (s)')
plt.ylabel('microvolts (uV)')
plt.title("De-noised signal using wavelet techniques")
plt.subplot(3, 1, 3)
plt.plot(index[mintime:maxtime],data[mintime:maxtime]-datarec[mintime:maxtime])
plt.xlabel('time (s)')
plt.ylabel('error (uV)')
plt.tight_layout()
plt.show()
运行结果如下: