前文介绍:橡皮筋基线校正
def get_portion_interest(x,y,bir):
birlen = np.array(bir.shape[0])#用于获取 bir 的行数,也就是要提取信号的区域数量
sp = np.transpose(np.vstack((x.reshape(-1),y.reshape(-1))))
### selection of bir data
for i in range(birlen):
if i == 0:
yafit = sp[np.where((sp[:,0]> bir[i,0]) & (sp[:,0] < bir[i,1]))]
else:
je = sp[np.where((sp[:,0]> bir[i,0]) & (sp[:,0] < bir[i,1]))]
yafit = np.vstack((yafit,je))
return yafit
参数
----------
x : ndarray
x 轴
y : ndarray
y 值
bir : n x 2 数组
需要提取信号的区域的 x 值、
必须是一个 n x 2 维数组,其中 n 是要提取的区域数。
第 0 列为低边界,第 1 列为高边界。
返回值
-------
yafit : ndarray
一个 2 列 x-y 数组,包含 bir 中的信号。
import numpy as np
from scipy.spatial import ConvexHull
def Rubberband_baseline (x_input,y_input,bir):
# we get the signals in the bir
yafit_unscaled = get_portion_interest(x_input,y_input,bir)
# signal standard standardization with sklearn
# this helps for polynomial fitting
X_scaler = preprocessing.StandardScaler().fit(x_input.reshape(-1, 1))
Y_scaler = preprocessing.StandardScaler().fit(y_input.reshape(-1, 1))
# transformation
x = X_scaler.transform(x_input.reshape(-1, 1))
y = Y_scaler.transform(y_input.reshape(-1, 1))
yafit = np.copy(yafit_unscaled)
yafit[:,0] = X_scaler.transform(yafit_unscaled[:,0].reshape(-1, 1))[:,0]
yafit[:,1] = Y_scaler.transform(yafit_unscaled[:,1].reshape(-1, 1))[:,0]
y = y.reshape(len(y_input))
x=x.flatten()
# Find the convex hull
v = ConvexHull(np.array(list(zip(x, y))), incremental=True).vertices
#v = ConvexHull(np.vstack((x.ravel(), y.ravel())).T).vertices
# Rotate convex hull vertices until they start from the lowest one
v = np.roll(v, -v.argmin())
# Leave only the ascending part
v = v[:v.argmax()]
# Create baseline using linear interpolation between vertices
baseline_fitted = np.interp(x, x[v], y[v])
return y_input.reshape(500,1)-Y_scaler.inverse_transform(baseline_fitted.reshape(500, 1)), Y_scaler.inverse_transform(baseline_fitted.reshape(500, 1))
plt.figure(dpi=150)
plt.plot(x, y, "k-", label="Raw")
plt.plot(x, baseline_fit.T, "-", color="r", label="baseline")
plt.plot(x, y-baseline_fit[1,:], "-", color="g", label="Rubberband_baseline")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()