使用scipy.interpolate进行具有固定起点和终点的平滑样条曲线逼近

2024-06-02 22:10:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试平滑缩放的opencv轮廓线段。我使用的是平滑样条曲线,我希望在实际数据点中开始和结束样条曲线。我不太熟悉插值和样条曲线拟合的术语,所以我真的不知道要搜索什么

我想要实现的是类似于下面红色图表的东西,它是平滑的,我想在其他图表开始和结束的相同点开始/结束。我不介意它不通过剩余的数据点,我更愿意控制平滑量,但起点和终点需要固定。这可以通过scipy.interpolate实现吗?还有其他选择吗

我发现https://stackoverflow.com/a/47233842/4556546用于橙色图形,它与s=0splprep版本非常相似,即插值,但它也使用s=0,因此我看不出它如何有助于平滑

我还发现https://stackoverflow.com/a/32421626/4556546系数在哪里被操纵;同样,我看不出这有助于实现我的目标。通过平滑splprep产生的系数已经指向红色图形的起点

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import splprep, splev, make_interp_spline

border_segment = 16 * np.asarray([[[2, 8], [2, 9], [2, 10], [2, 11], [1, 12], [0, 13], [0, 14], [0, 15], [1, 16], [2, 17], [2, 18]]])

plt.scatter( border_segment[0].T[0], border_segment[0].T[1] )

# With smoothing s<>0
tck, u = splprep(border_segment[0].T, u=None, s=border_segment[0].shape[0]*16, per=0)
u_new = np.linspace(u.min(), u.max(), border_segment[0].shape[0]*16)
x_new, y_new = splev(u_new, tck, der=0)
plt.plot(x_new, y_new, color='red')

# With interpolation s=0
tck, u = splprep(border_segment[0].T, u=None, s=0.0, per=0)
x_new, y_new = splev(u_new, tck, der=0)
plt.plot(x_new, y_new, color='green')

# With boundary conditions, also see https://stackoverflow.com/a/47233842/4556546
l, r = [(1, (0, 0))], [(1, (0, 0))]
clamped_spline = make_interp_spline(u, np.array(border_segment[0].T).T, bc_type=(l, r))
x_new, y_new = clamped_spline(u_new).T
plt.plot(x_new, y_new, color='orange')

Plotting result from the code above


Tags: httpsimportcomnewwithnpsegmentplt