2017-02-17 268 views
1

我想在一组500个随机点上拟合一个三次贝塞尔曲线。适合立方贝塞尔曲线的最小二乘法

下面是我对贝塞尔曲线代码:

import numpy as np 
from scipy.misc import comb 

def bernstein_poly(i, n, t): 
    """ 
    The Bernstein polynomial of n, i as a function of t 
    """ 

    return comb(n, i) * (t**(n-i)) * (1 - t)**i 


def bezier_curve(points, nTimes=1000): 

    nPoints = len(points) 
    x = np.array([p[0] for p in points]) 
    y = np.array([p[1] for p in points]) 

    t = np.linspace(0.0, 1.0, nTimes) 

    polynomial_array = np.array([ bernstein_poly(i, nPoints-1, t) for i in range(0, nPoints) ]) 

    xvals = np.dot(x, polynomial_array) 
    yvals = np.dot(y, polynomial_array) 

    return xvals, yvals 


if __name__ == "__main__": 
    from matplotlib import pyplot as plt 

    nPoints = 4 
    points = np.random.rand(nPoints,2)*200 
    xpoints = [p[0] for p in points] 
    ypoints = [p[1] for p in points] 

    xvals, yvals = bezier_curve(points, nTimes=1000) 
    plt.plot(xvals, yvals) 
    plt.plot(xpoints, ypoints, "ro") 
    for nr in range(len(points)): 
     plt.text(points[nr][0], points[nr][1], nr) 

    plt.show() 

我知道,与NumPy和SciPy的有最小二乘法:numpy.linalg.lstsqscipy.optimize.least_squares

但我不知道我怎么能用它们来拟合500点的曲线。有人可以提供一些帮助吗?

谢谢

+0

什么部分数据证明使用贝塞尔曲线,而不是更适合噪音数据拟合的东西?因为在某人回答你的问题之前,你应该能够回答为什么你认为你需要贝塞尔曲线而不是更合适的东西。 –

+0

在这种情况下,我特别使用Bezier曲线,因为我按照书中的说明进行操作,并且希望实施该操作。我知道有更好的选择,但在这个特定的例子中,我需要使用贝塞尔曲线。 – stepp0

+0

这表明你的问题还没有完全诚实。我确定说出你刚才在文章中所说的内容,并说*哪本书是不必要的信息的反面。 –

回答

1

使用在SciPy的功能curve_fit,https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

import numpy as np 
from scipy.optimize import curve_fit 
def func(x, a, b, c): 
    return a * np.exp(-b * x) + c 

xdata = np.linspace(0, 4, 50) 
y = func(xdata, 2.5, 1.3, 0.5) 
ydata = y + 0.2 * np.random.normal(size=len(xdata)) 

popt, pcov = curve_fit(func, xdata, ydata) 

#Constrain the optimization to the region of 0 < a < 3, 0 < b < 2 and 0 < c < 1: 


popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 2., 1.])) 
0

的SciPy的文档本身对这里使用花键最优秀的教程:

https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html

有很多代码,示例和比较不同类型样条的酷图。

+0

Bezier曲线和Bezier样条曲线不同吗?感谢您的参考,但我不明白我怎么可以在我的情况下使用 – stepp0

+0

我的歉意。来自pypi的这个参考怎么样?所显示的代码示例和图表看起来像是你在... https://pypi.python.org/pypi/bezier/0.3.0 –