Open3d: 点云曲线拟合
因为项目需要分析点云数据, 此文总结其中拟合点云的部分。
拟合
首先定一个曲线方程:
def func(x, a, b, c):
return a * x**2 + b * x + c
然后将点云数据结构转换为numpy
数组:
points = np.asarray(pcd.points)
读取点数组中,x轴、y轴的数组:
xy_points = points[:, :2]
x = xy_points[:,x_axis_idx]
y = xy_points[:,y_axis_idx]
调用scipy.optimize
中的curve_fit
进行点拟合, 得到各项系数:
popt, pcov = curve_fit(func,x, y)
以上结果系数在返回值popt
中, 为一个元组
为了评估其拟合的好坏, 此处计算了残差, 然后分析其分布情况:
residuals = y - func(x, *popt)
# 通过标准差, 判断其离散程度
np.sqrt(np.sum(residuals**2)/x.shape[0]) < std_threshold
可视化
import matplotlib.pyplot as plt
import matplotlib
# 保证中文显示正常
matplotlib.rcParams['axes.unicode_minus'] = False
matplotlib.rcParams['font.family'] = 'SimHei'
x_fit = np.linspace(np.min(x), np.max(x), x.shape[0])
y_fit = func(x_fit, a_fit, b_fit, c_fit)
# 创建两个子图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
ax1.scatter(x,y, color='blue', label='Point Cloud')
ax1.plot(x_fit,y_fit, color='red', linewidth=2, label='Fitted Curve')
ax1.legend()
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_title(f"曲线拟合(Fitted Curve)\n$y={a_fit:.3f}*x^2+{b_fit:.3f}*x+{c_fit:.3f}$")
# 绘制残差图
ax2.scatter(x, residuals)
ax2.axhline(y=0, color='r', linestyle='--')
ax2.set_xlabel('X')
ax2.set_ylabel('Residuals')
ax2.set_title('残差(Residuals)')
# 计算R-squared
mean_y = np.mean(y)
ss_total = np.sum((y - mean_y) ** 2)
ss_residual = np.sum(residuals ** 2)
r_squared = 1 - (ss_residual / ss_total)
# 值越大拟合效果越好
ax2.text(0.02, 0.95, f"R平方:{r_squared:.3f},残差的标准差:{np.sqrt(np.sum(residuals**2)/x.shape[0]):.3f}", transform=ax2.transAxes, fontsize=14,verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
# 0.06为观测阈值
fig.suptitle("点云拟合分析", fontsize=20)
plt.tight_layout()
plt.show()
最终效果: