open3d 使用 RANSAC 算法拟合平面

发布于:2025-06-27 ⋅ 阅读:(16) ⋅ 点赞:(0)

1、功能介绍:

一个python代码演示了如何使用 open3d 和 numpy 来完成一个完整的点云平面拟合任务。它包括以下几个主要部分:生成符合某一平面方程的随机点云数据、使用 RANSAC 算法对这些点云进行平面拟合、可视化原始点云和平面拟合结果

2、代码部分:

import numpy as np
import open3d as o3d

# 生成随机点云
np.random.seed(42)
n_points = 100
# 假设这些点在平面 x + 2y + 3z = 1 上
a, b, c = 1, 2, 3  # 平面的法向量
d = 1  # 平面的常数项

# 随机生成 x 和 y
x = np.random.uniform(-5, 5, n_points)
y = np.random.uniform(-5, 5, n_points)
# 根据平面方程计算 z
z = (d - a * x - b * y) / c

# 将点组合成点云
points = np.vstack((x, y, z)).T

# 创建 open3d 点云对象
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points)

# 平面拟合:使用 open3d 提供的函数进行平面拟合
plane_model, inlier_indices = pcd.segment_plane(distance_threshold=0.01,
                                                ransac_n=3,
                                                num_iterations=1000)

# 提取平面模型的系数 (a, b, c, d)
a, b, c, d = plane_model

# 创建拟合平面的网格(TriangleMesh)
# 设置平面的显示范围,确保覆盖所有点云
x_min, x_max = -5, 5
y_min, y_max = -5, 5

# 计算对应的 z 值(通过平面方程)
z_min = (-a * x_min - b * y_min - d) / c
z_max = (-a * x_max - b * y_min - d) / c
z_max_y = (-a * x_max - b * y_max - d) / c
z_min_y = (-a * x_min - b * y_max - d) / c

# 创建四个顶点
vertices = np.array([
    [x_min, y_min, z_min],
    [x_max, y_min, z_max],
    [x_max, y_max, z_max_y],
    [x_min, y_max, z_min_y]
])

# 创建两个三角形以形成平面网格
triangles = [[0, 1, 2], [0, 2, 3]]

# 创建 TriangleMesh 对象
plane_mesh = o3d.geometry.TriangleMesh()
plane_mesh.vertices = o3d.utility.Vector3dVector(vertices)
plane_mesh.triangles = o3d.utility.Vector3iVector(triangles)

# 给平面网格着色
plane_mesh.paint_uniform_color([0.1, 0.9, 0.1])  # 设置颜色为绿色

# 可视化点云和拟合的平面网格
o3d.visualization.draw_geometries([pcd, plane_mesh], window_name="Fitted Plane")

3、参数说明:

【distance_threshold=0.01】:距离阈值,是一个浮动值,用于确定哪些点被认为是“内点”(inliers),即平面模型的拟合点。

【ransac_n=3】:每次 RANSAC 迭代的采样点数),是在每次 RANSAC 迭代中用于拟合平面的最小点数。

【num_iterations=1000】:(RANSAC 迭代次数),RANSAC 算法运行的总迭代次数,是尝试拟合平面的次数。

4、运行结果:


网站公告

今日签到

点亮在社区的每一天
去签到