以下是一个使用Python和matplotlib库绘制贝塞尔曲线的示例代码:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def bezier_curve(control_points, num_samples=100):
t = np.linspace(0, 1, num_samples)
n = len(control_points) - 1
curve = np.zeros((num_samples, 3))
for i in range(num_samples):
point = np.zeros(3)
for j in range(n + 1):
point += control_points[j] * binomial_coefficient(n, j) * (1 - t[i])**(n - j) * t[i]**j
curve[i] = point
return curve
def binomial_coefficient(n, k):
return np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n - k))
# 控制点坐标
control_points = np.array([[0, 0, 0], [1, 2, 3], [3, 2, 1], [4, 0, 0]])
curve = bezier_curve(control_points)
# 绘制结果
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(curve[:, 0], curve[:, 1], curve[:, 2])
ax.scatter(control_points[:, 0], control_points[:, 1], control_points[:, 2], c='r')
plt.show()
在上面的示例中,我们首先定义了一个bezier_curve
函数,该函数接受控制点的坐标数组和采样点数作为输入,并返回贝塞尔曲线的坐标数组。然后,我们使用binomial_coefficient
函数计算二项式系数。最后,我们通过调用bezier_curve
函数和绘图函数来绘制贝塞尔曲线。控制点通过红色散点图表示,而曲线由连续的蓝色线条表示。
上一篇:贝塞尔曲线数学
下一篇:被删除部分的Git罪状