贝塞尔曲线python代码
时间: 2023-10-12 14:54:23 浏览: 116
python绘制贝塞尔曲线
5星 · 资源好评率100%
以下是一个简单的贝塞尔曲线的 Python 代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
def bernstein_poly(i, n, t):
"""
The Bernstein polynomial of n, i as a function of t
"""
return scipy.special.comb(n, i) * t**i * (1 - t)**(n - i)
def bezier_curve(points, nTimes=1000):
"""
Given a set of control points, return the
bezier curve defined by the control points.
points should be a list of lists, or list of tuples
such as [ [1,1],
[2,3],
[4,5], ..[Xn, Yn] ]
nTimes is the number of time steps, defaults to 1000
See http://processingjs.nihongoresources.com/bezierinfo/
"""
nPoints = len(points)
xPoints = np.array([p[0] for p in points])
yPoints = 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(xPoints, polynomial_array)
yvals = np.dot(yPoints, polynomial_array)
return xvals, yvals
# Example usage:
if __name__ == "__main__":
# Define control points
control_points = [[1, 1], [2, 3], [4, 5], [7, 7], [10, 5], [6, 2]]
# Calculate the Bezier curve
x_curve, y_curve = bezier_curve(control_points)
# Plot the Bezier curve
plt.plot(x_curve, y_curve, '-b')
plt.plot([p[0] for p in control_points], [p[1] for p in control_points], 'or')
plt.title("Bezier Curve")
plt.show()
```
这个代码使用了 `numpy` 和 `matplotlib` 库,可以生成一个简单的贝塞尔曲线并在画布上绘制出来。
阅读全文