基线矫正
基线矫正常用的是AirPLS,详情请见
https://doi.org/10.1002/jrs.2500
工具包导入
import numpy as np
from scipy.sparse import csc_matrix, eye, diags
from scipy.sparse.linalg import spsolve
代码
def WhittakerSmooth(x, w, lambda_, differences=1):
X = np.matrix(x)
m = X.size
E = eye(m, format='csc')
for i in range(differences):
E = E[1:] - E[:-1] # numpy.diff() does not work with sparse matrix. This is a workaround.
W = diags(w, 0, shape=(m, m))
A = csc_matrix(W + (lambda_ * E.T * E))
B = csc_matrix(W * X.T)
background = spsolve(A, B)
return np.array(background)
def airPLS(x, lambda_=2, porder=1, itermax=15):
m = x.shape[0]
w = np.ones(m)
for i in range(1, itermax + 1):
z = WhittakerSmooth(x, w, lambda_, porder)
d = x - z
dssn = np.abs(d[d < 0].sum())
if (dssn < 0.001 * (abs(x)).sum() or i == itermax):
if (i == itermax): print('WARING max iteration reached!')
break
w[d >= 0] = 0 # d>0 means that this point is part of a peak峰值, so its weight is set to 0 in order to ignore it
w[d < 0] = np.exp(i * np.abs(d[d < 0]) / dssn)
w[0] = np.exp(i * (d[d < 0]).max() / dssn)
w[-1] = w[0]
return z
def AirPLS(data):
for item in range(data.shape[0]):
data[item]=data[item]-airPLS(data[item])
return data
效果展示
矫正前
data_AirPlS=AirPLS(data)
plt.plot(data_AirPlS[0])
plt.show()
平滑滤波
代码
from scipy import signal
def SG(data):
return signal.savgol_filter(data,20, 2)
效果展示
data_SG=SG(data_a)
plt.plot(data_SG[0])
plt.show()