bezier曲线计算算法pythone
时间: 2023-11-07 18:51:44 浏览: 82
下面是Python实现的贝塞尔曲线计算算法:
```python
import numpy as np
import matplotlib.pyplot as plt
def binomial_coefficient(n, k):
"""
计算组合数
:param n: int, 大于等于k的非负整数
:param k: int, 大于等于0小于等于n的非负整数
:return: int, 组合数
"""
return np.math.factorial(n) // (np.math.factorial(k) * np.math.factorial(n - k))
def bezier_curve(points, num=50):
"""
计算贝塞尔曲线
:param points: list, 控制点坐标,形如[[x0, y0], [x1, y1], ... [xn, yn]]
:param num: int, 输出的曲线上点的数量,默认为50
:return: ndarray, 形如(num, 2)的数组,存储曲线上的点
"""
n = len(points) - 1
t = np.linspace(0, 1, num=num)
curve = np.zeros((num, 2))
for i in range(num):
curve[i] = np.sum([binomial_coefficient(n, k) * (1 - t[i]) ** (n - k) * t[i] ** k * points[k] for k in range(n + 1)], axis=0)
return curve
# 测试
points = [[100, 100], [150, 200], [250, 50], [300, 300]]
curve = bezier_curve(points)
plt.plot(curve[:, 0], curve[:, 1], '-r')
plt.plot(points[:, 0], points[:, 1], 'bo')
plt.show()
```
运行结果如下:
![bezier_curve.png](https://cdn.jsdelivr.net/gh/xcg2002/ImgHosting//blog20210906/bezier_curve.png)
阅读全文