import math
import numpy as np
import matplotlib.pyplot as plt
import pywt
from matplotlib.widgets import Slider, Button, RadioButtons, TextBox
from numpy import ndarray
# 封装成函数
def sgn(num):
if num > 0.0:
return 1.0
elif num == 0.0:
return 0.0
else:
return -1.0
def wavelet_noising(np_arr: ndarray,wavelet_name='sym8',level=5):
if level==0:
return np_arr[1]
data = np_arr[1]
data = data.tolist()
w = pywt.Wavelet(wavelet_name) # 选择sym8小波基
ca, *cds = pywt.wavedec(data, w, level=level) # 5层小波分解
*_,cd1=cds
Cd1 = np.array(cd1)
abs_cd1 = np.abs(Cd1)
median_cd1 = np.median(abs_cd1)
sigma = (1.0 / 0.6745) * median_cd1
threshold = sigma * math.sqrt(2.0 * math.log(float(len(data)), math.e)) # 固定阈值计算
usecoeffs = [ca]
# 软硬阈值折中的方法
a = 0.5
for cd in cds:
for k in range(len(cd)):
cd[k]=sgn(cd[k]) * (abs(cd[k]) - a * threshold) if abs(cd[k]) >= threshold else 0.0
usecoeffs.append(cd)
print('wavelet_name={0},level={1}'.format(wavelet_name,level))
return pywt.waverec(usecoeffs, w)
class WaveletDemo:
def __init__(self, data: ndarray):
self.fig, self.ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
self.data = data
plt.plot(data[0], data[1], c='r', alpha=0.5, linewidth=0.3)
self.l, = plt.plot(data[0], data[1], alpha=1.0, linewidth=0.8)
self.slider = Slider(plt.axes([0.25, 0.15, 0.65, 0.03]),
"Amp", 0, 6,
valinit=1, valstep=1,
color="green")
self.slider.on_changed(self.update)
self.reset_button = Button(plt.axes([0.8, 0.025, 0.1, 0.04]), 'Reset', hovercolor='0.975')
self.txt = TextBox(plt.axes([0.6, 0.025, 0.1, 0.04]), 'wavelet_type')
self.txt.set_val('sym5')
def update(self, val):
# type=self.txt.text
self.l.set_ydata(wavelet_noising(data, wavelet_name=self.txt.text, level=int(val)))
self.fig.canvas.draw_idle()
def show(self):
plt.show()
path = './data.csv' # 数据路径
# 提取数据
data = np.loadtxt(path, delimiter=',').T
noise_data = data[1] + np.random.randint(0, 2000, size=data[1].shape)
data = np.array([data[0], noise_data])
demo = WaveletDemo(data)
demo.show()
小波分析信号重构,pywt实现,matplotlib添加交互控件
最新推荐文章于 2024-11-07 16:50:01 发布
该博客介绍了一个Python实现的小波去噪方法,通过`pywt`库进行小波分解和重构,以去除数据中的噪声。文章展示了如何封装`sgn`函数和`wavelet_noising`函数,用于设定阈值并应用软硬阈值处理。同时,创建了一个交互式示例`WaveletDemo`,允许用户调整去噪级别并实时查看结果。此方法对于信号处理和数据分析领域具有实用价值。
摘要由CSDN通过智能技术生成