Skip to main content
 首页 » 编程设计

python之三次贝塞尔曲线上的最小二乘拟合

2025年02月15日12落叶无声

我想在一组 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.lstsq和 scipy.optimize.least_squares

但我不确定如何使用它们来拟合 500 点上的曲线。有人可以提供一些帮助吗?

谢谢

请您参考如下方法:

在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.]))