目录
一、概述
二、代码实现
2.1关键函数
2.2完整代码
三、实现效果
3.1原始点云
3.2拟合后点云
前期试读,后续会将博客加入该专栏,欢迎订阅
Open3D点云算法与点云深度学习案例汇总(长期更新)-CSDN博客
一、概述
RANSAC(RANdom SAmple Consensus)是一种用于估计数学模型参数的迭代方法,尤其适用于包含大量异常值的数据。它通过反复从数据集中随机抽取子集进行拟合,评估模型的适用性,并最终选择内点最多的模型作为最佳拟合。
要使用 RANSAC 算法拟合三维点云球面,可以按照以下步骤进行实现。
1.生成带噪声的球面点云数据:
- 创建一个三维球面点云,并添加噪声以模拟实际数据。
2.定义 RANSAC 球面拟合算法:
- 使用 RANSAC 算法从带噪声的点云中拟合出一个球面。
3.可视化拟合结果:
- 使用 Open3D 可视化原始点云和拟合的球面。
二、代码实现
2.1关键函数
fit 函数是 pyrsc 库中 Sphere 类的方法,用于使用 RANSAC 算法拟合三维点云数据中的球面。
class Sphere():| Sphere()def fit(self, pts, thresh=0.2, maxIteration=1000):
输入参数
- points:三维点云数据,形状为 (N, 3) 的 numpy 数组,其中 N 是点的数量。每个点包含 x, y, z 坐标。
- thresh:内点距离阈值,默认为 0.05。用于判断一个点是否属于拟合的球面。如果点到球面的距离小于该阈值,则认为该点是内点。
- maxIteration:RANSAC 算法的最大迭代次数,默认为 1000。算法将在该次数内尝试找到最佳拟合模型。更多的迭代次数可以提高找到最佳拟合的概率。
返回值
- center:拟合的球面的球心坐标 (cx, cy, cz)。
- radius:拟合的球面的半径 r。
- inliers:内点索引列表,包含所有符合拟合球面条件的点的索引。
2.2完整代码
import open3d as o3d
import numpy as np
import pyransac3d as pyrscdef generate_noisy_sphere(radius=1.0, num_points=1000, noise_level=0.05):"""生成一个带有噪声的三维球面点云。参数:radius (float): 球的半径,默认为 1.0。num_points (int): 点云中的点的数量,默认为 1000。noise_level (float): 噪声水平,默认为 0.05。返回:numpy.ndarray: 生成的点云数据。"""phi = np.random.uniform(0, np.pi, num_points)theta = np.random.uniform(0, 2 * np.pi, num_points)x = radius * np.sin(phi) * np.cos(theta)y = radius * np.sin(phi) * np.sin(theta)z = radius * np.cos(phi)points = np.vstack((x, y, z)).T# 添加噪声noise = np.random.normal(0, noise_level, points.shape)noisy_points = points + noisereturn noisy_pointsdef create_sphere_mesh(cx, cy, cz, r, resolution=20):"""创建一个球形的 Mesh,用于可视化。参数:cx (float): 球心的 x 坐标。cy (float): 球心的 y 坐标。cz (float): 球心的 z 坐标。r (float): 球的半径。resolution (int): 球的分辨率,默认为 20。返回:open3d.geometry.TriangleMesh: 球形 Mesh 对象。"""sphere = o3d.geometry.TriangleMesh.create_sphere(radius=r, resolution=resolution)sphere.translate([cx, cy, cz])sphere.paint_uniform_color([1, 0, 0]) # 设置颜色为红色return sphere# 生成带有噪声的三维球面点云
radius = 1.0
num_points = 1000
noise_level = 0.05
points = generate_noisy_sphere(radius, num_points, noise_level)# 使用 pyrsc 库中的 RANSAC 进行球面拟合
sphere = pyrsc.Sphere()
center, radius, inliers = sphere.fit(points, thresh=0.05, maxIteration=1000)# 创建点云对象
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points)# 给点云设置颜色为蓝色
pcd.paint_uniform_color([0, 0, 1])
# 可视化点云
o3d.visualization.draw_geometries([pcd], window_name="pcd",width=800, height=600, left=50, top=50)
# 创建拟合球的 Mesh 对象
cx, cy, cz = center
sphere_mesh = create_sphere_mesh(cx, cy, cz, radius)# 可视化点云和拟合的球
o3d.visualization.draw_geometries([pcd, sphere_mesh], window_name="RANSAC Sphere Fitting with pyrsc",width=800, height=600, left=50, top=50)