首页 > 编程语言 >Python环境下基于小波分析的Linear电磁谱降噪

Python环境下基于小波分析的Linear电磁谱降噪

时间:2024-04-03 18:59:18浏览次数:46  
标签:plot plt Linear Python 于小波 label color DWTcoeffs np

小波变换以其良好的时频局部化特性,成功地解决了保护信号局部性和抑制噪声之间的矛盾,因此小波技术在信号降噪中得到了广泛的研究,并获得了非常好的应用效果。小波降噪中最常用的方法是小波阈值降噪。基于小波变换的阈值降噪关键是要解决两个问题:阈值的选取和阈值函数的确定,目前常用的阈值选取原则有以下四种:通用阈值(sqtwolog原则)、Stein无偏似然估计阈值(rigrsure原则)、启发式阈值(heursure原则)、极大极小阈值(minimaxi原则)。

鉴于此,采用小波分析对电磁谱信号进行降噪,完整代码如下:

import numpy as npimport matplotlib.pyplot as pltimport pywtfrom scipy import constants as cons

data = open('Data.txt', 'r')
wl = []intensity = []
for line in data:    rows = [i for i in line.split()]    wl.append(float(rows[0]))    intensity.append(float(rows[1]))
h = 6.626e-34  # Planck's constant (J·s)c = 3e8       # Speed of light (m/s)k = 1.381e-23  # Boltzmann constant (J/K)temperature = 5800  # Temperature (K)wien_constant = 2.897e-3  # Wien's displacement constant (m/K)
desired_peak = 2
# Wavelength range (in meters)wavelengths = np.linspace(280, 1100, 941) * 1e-9
# Planck's law for spectral radiancedef planck_law(wavelength, temperature):    return (8 * np.pi * h * c) / (wavelength**5) / (np.exp((h * c) / (wavelength * k * temperature)) - 1)
# Calculate spectral radiance for the Sunspectral_irradiance = planck_law(wavelengths, temperature)
# Normalize to have the peak value equal to the desired valuescaling_factor = desired_peak / np.max(spectral_irradiance)spectral_irradiance *= scaling_factor
peak_wavelength = 1e9*wien_constant / temperaturepeak_wavelength
DWTcoeffs = pywt.wavedec(intensity, 'db4')DWTcoeffs[-1] = np.zeros_like(DWTcoeffs[-1])DWTcoeffs[-2] = np.zeros_like(DWTcoeffs[-2])DWTcoeffs[-3] = np.zeros_like(DWTcoeffs[-3])DWTcoeffs[-4] = np.zeros_like(DWTcoeffs[-4])#DWTcoeffs[-5] = np.zeros_like(DWTcoeffs[-5])#DWTcoeffs[-6] = np.zeros_like(DWTcoeffs[-6])#DWTcoeffs[-7] = np.zeros_like(DWTcoeffs[-7])#DWTcoeffs[-8] = np.zeros_like(DWTcoeffs[-8])#DWTcoeffs[-9] = np.zeros_like(DWTcoeffs[-9])
filtered_data=pywt.waverec(DWTcoeffs,'db4')filtered_data = filtered_data[:len(wl)]
plt.figure(figsize=(10, 6))plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.plot(wl, filtered_data,  markerfacecolor='none',color='black', label='Denoised Signal')
plt.annotate(    str(temperature)+' K BlackBody Spectrum',    ha = 'center', va = 'bottom',    xytext = (900,1.75),    xy = (700,1.60),    arrowprops = { 'facecolor' : 'black', 'shrink' : 0.05 })
plt.legend()plt.title('Wavelet Denoising of Solar Linear Spectra (280nm - 1100nm)')plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([280, 1100, 0, 2.5])plt.show()
plt.figure(figsize=(10, 12))  # Set the figure size for both subplots
# Subplot 1plt.subplot(3, 1, 1)  # Three rows, one column, index 1plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.legend()plt.title('Wavelet Denoising of Solar Linear UVB and UVA Spectra (280nm - 400nm)')plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([280, 400, 0, 2])
# Subplot 2plt.subplot(3, 1, 2)  # Three rows, one column, index 2plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([280, 400, 0, 2])
# Subplot 2plt.subplot(3, 1, 3)  # Three rows, one column, index 3plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Real Data')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([280, 400, 0, 2])
plt.tight_layout()  # Adjust layout to prevent overlappingplt.show()
plt.figure(figsize=(10, 12))  # Set the figure size for both subplots
# Subplot 1plt.subplot(3, 1, 1)  # Three rows, one column, index 1plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.legend()plt.title('Wavelet Denoising of Solar Linear Visible Spectra (400nm - 700nm)')plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([400, 700, 1, 2.5])
# Subplot 2plt.subplot(3, 1, 2)  # Three rows, one column, index 2plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([400, 700, 1, 2.5])
# Subplot 2plt.subplot(3, 1, 3)  # Three rows, one column, index 3plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Intensity $(\frac{W}{m^2nm})$')plt.axis([400, 700, 1, 2.5])
plt.tight_layout()  # Adjust layout to prevent overlappingplt.show()
plt.figure(figsize=(10, 12))  # Set the figure size for both subplots
# Subplot 1plt.subplot(3, 1, 1)  # Three rows, one column, index 1plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.legend()plt.title('Wavelet Denoising of Solar Linear Visible Spectra (400nm - 700nm)')plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([700, 1100, 0, 2.5])
# Subplot 2plt.subplot(3, 1, 2)  # Three rows, one column, index 2plt.plot(wl, intensity, color='red', label='Noisy Signal')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([700, 1100, 0, 2.5])
# Subplot 2plt.subplot(3, 1, 3)  # Three rows, one column, index 3plt.plot(wavelengths * 1e9, spectral_irradiance, color='green', label='Theoretical Irradiance')plt.plot(wl, filtered_data, markerfacecolor='none', color='black', label='Denoised Signal')plt.legend()plt.xlabel(r'Wavelength (nm)')plt.ylabel(r'Spectral Irradiance $(\frac{W}{m^2nm})$')plt.axis([700, 1100, 0, 2.5])
plt.tight_layout()  # Adjust layout to prevent overlappingplt.show()
def calculate_mse(original, denoised):    mse = np.mean(np.square(np.subtract(original, denoised)))    return mse
def calculate_rmse(original, denoised):    mse = calculate_mse(original, denoised)    rmse = np.sqrt(mse)    return rmse
def calculate_psnr(original, denoised):    max_pixel_value = 255.0  # Assuming pixel values are in the range [0, 255]    mse_value = calculate_mse(original, denoised)    psnr = 10 * np.log10((max_pixel_value ** 2) / mse_value)    return psnr
# Assuming 'original_signal' and 'denoised_signal' are your original and denoised signals as lists or arraysmse_value = calculate_mse(spectral_irradiance, filtered_data)rmse_value = calculate_rmse(spectral_irradiance, filtered_data)psnr_value = calculate_psnr(spectral_irradiance, filtered_data)
print(f"MSE: {mse_value}")print(f"RMSE: {rmse_value}")print(f"PSNR: {psnr_value} dB")

工学博士,担任《Mechanical System and Signal Processing》审稿专家,担任《中国电机工程学报》优秀审稿专家,《控制与决策》,《系统工程与电子技术》,《电力系统保护与控制》,《宇航学报》等EI期刊审稿专家。

擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

标签:plot,plt,Linear,Python,于小波,label,color,DWTcoeffs,np
From: https://blog.csdn.net/weixin_39402231/article/details/137254433

相关文章

  • Python中处理JSON字段时,和如何将Python对象转换为JSON字符串
    在Python中处理JSON字段时,通常使用内置的json模块。这个模块允许你将Python对象转换为JSON字符串,以及将JSON字符串解析为Python对象。以下是一些常见的JSON字段处理操作:1.将Python对象转换为JSON字符串python复制importjson#定义一个Python字典data={  "name"......
  • 软测WebUI Python安装selenium模块失败,用VSCode安装成功
    Dos命令行下Python安装selenium模块失败,安了python,pip也好着呢,安装失败,网上没有查到类似报错。  报错还有一些,截图不全使用vsc安装selenium模块,成功了。  ......
  • Python实现【贪吃蛇大作战】+源码
    文章目录前言:一、游戏概述1.游戏玩法2.游戏特色二、游戏规则三、工具选择四、主要技术pygame库numpy库cocos2d五、源码分享六、项目地址前言:今天的GitHub小游戏分享,我们将聚焦于一个经典而又极富趣味性的游戏——贪吃蛇大作战。这款游戏不仅考验玩家的反应速度......
  • 安装Ray包,Python降版本
    平常安装ray包使用的是:1pipinstallray然而今天在安装了新的Anaconda之后安装ray包提示:1ERROR:Couldnotfindaversionthatsatisfiestherequirementray(fromversions:none)2ERROR:Nomatchingdistributionfoundforray参考了Ray的documentation:https:......
  • python解压rar文件,直接在内存读取
    必须要的依赖:aptinstallunrarfromrarfileimportRarFileio_buffer=io.BytesIO(response.body)withRarFile(io_buffer)asfs:foreachinfs.infolist():content=""bytes_info=b''for......
  • python常见数据结构及方法
    Python提供了多种内置的数据结构,这些数据结构非常灵活且功能强大,能够满足各种程序设计需求。下面是一些最常用的Python数据结构及其内置方法的详细说明:1.列表(List)列表是Python中最基本的数据结构之一。列表可以包含不同类型的元素,包括另一个列表。常用内置方法:append(x......
  • 【Python列表的使用和创建(详细版)】
    一.列表概念1.概念:在Python中列表是一个对象的集合。二.列表的创建1.基本语法[]创建例:a=[10,20,30,"无限",'txt']a=[]#创建一个空列表2.list()创建(1).使用list()可以将任何可迭代的数据转化成列表。例:a=list("cosfirst")b=list(range(10))print(a)prin......
  • Python语法学习三之函数
    一、简单函数定义和调用def函数名():代码#无参数,无返回值的函数defprintName():print"cehae"printName()#无参数,有返回值的函数defgetAge():return18printgetAge()#有参数,无返回值的函数defprintSex(sex):printsexpr......
  • Python语法学习四之IO操作
    一、文件操作1-1、打开/创建文件在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件open(文件名,访问模式)f=open('C:/Users/cehae/Desktop/test.txt','w')访问模式1-2、关闭文件close()f=open('C:/Users/cehae/Desktop/test.txt','r')#关闭文......
  • Python语法学习五之面向对象
    一、面向对象11-1、定义类语法:class类名:方法列表#定义类classCar:defgetCarInfo(self):#定义属性,和Java等语言差别很大。print('车轮子个数:%d,颜色%s'%(self.wheelNum,self.color))defmove(self):print("车正在移......