采样一致性探测平面

 

PCL中所列有两个RANSAC与LMedS两种采样方法,原理在这里不做详细介绍了。但是涉及到如何将分割的对象单独保存出来,以及使用不同颜色进行显示,官网上介绍比较少。现给出一个案例,进行讲解,以RANSAC探测平面为例,其他的以及LMedS不再做详细介绍。

 

//RANSAC探测多个平面
#include<pcl\point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>   //随机参数估计方法头文件
#include <pcl/sample_consensus/model_types.h>   //模型定义头文件
#include <pcl/segmentation/sac_segmentation.h>   //基于采样一致性分割的类的头文件
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/filters/extract_indices.h>
#include<stdlib.h>
#include<time.h> 
#include<sstream>
using namespace std;
int GetRandomNumber()
{
	
	int RandomNumber;
	RandomNumber = rand() % (256) + 0;//0到255之间选择颜色
	//生成其他范围的数字:RandomNumber = rand() % (b-a+1) + a;
	return RandomNumber;
}
void main()
{
	//第一步:定义输入的原始数据及滤波后的点,以及分割获得的点、平面系数coefficients、存储内点的索引集合对象inliers、用于显示的窗口
	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
	pcl::PointCloud<pcl::PointXYZ>::Ptr planar_segment(new pcl::PointCloud<pcl::PointXYZ>);//创建分割对象
	pcl::io::loadPCDFile("table_scene_lms400.pcd", *cloud);
	//pcl::io::loadPCDFile("E:\\program_study\\C++\\pcd_data\\cubic.pcd", *cloud);
	pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);//模型系数
	pcl::PointIndices::Ptr inliers(new pcl::PointIndices);//索引列表
	pcl::SACSegmentation<pcl::PointXYZ> seg;//分割对象
	pcl::visualization::PCLVisualizer viewer("planar segment");
	viewer.setBackgroundColor(0, 0, 0);
	pcl::ExtractIndices<pcl::PointXYZ> extract;//提取器

	int n_piece=2;//需要探测的面的个数

	//第二步:将原始点加载进入
	pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 255, 0, 0);//第二个平面颜色设置成蓝色 single_color_02
	viewer.addPointCloud<pcl::PointXYZ>(cloud, single_color, "sample");//将single_color在viewer中进行显示
	viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample");
	//第三步:使用RANSAC获取点数最多的面
    srand((int)time(0));//确保每次运行,产生的数字不一样(面片颜色不一样)
	for (int i = 0; i < n_piece; i++)
	{
		
		seg.setOptimizeCoefficients(true);		//使用内部点重新估算模型参数
		seg.setModelType(pcl::SACMODEL_PLANE);   //设置模型类型
		seg.setMethodType(pcl::SAC_RANSAC);      //设置随机采样一致性方法类型
		seg.setDistanceThreshold(0.01);    //设定距离阀值,距离阀值决定了点被认为是局内点是必须满足的条件
		seg.setInputCloud(cloud);
		seg.segment(*inliers, *coefficients);

		extract.setInputCloud(cloud);
		extract.setIndices(inliers);
		extract.setNegative(false);
		//提取探测出来的平面
		extract.filter(*planar_segment);
		//planar_segment为该次探测出来的面片,可以单独进行保存,此处省略

		//剔除探测出的平面,在剩余点中继续探测平面
		extract.setNegative(true);
		extract.filter(*cloud);

		
		int R = GetRandomNumber();
		int G = GetRandomNumber();
		int B = GetRandomNumber();
		stringstream ss;
		ss << i + 1; 
		string str;
		ss >> str;
		pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(planar_segment, R, G, B);//第二个平面颜色设置成蓝色 single_color_02
		viewer.addPointCloud<pcl::PointXYZ>(planar_segment, single_color, str);//将single_color在viewer中进行显示
		viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3,str);

	}
	while (!viewer.wasStopped())
	{
		viewer.spinOnce(1);
	}

}

配上提取效果:

提取三个平面的效果图:

提取两个平面效果图

附上代码下载链接:

https://download.youkuaiyun.com/download/qq_32867925/10681915

### RANSAC算法用于平面分割及孔洞检测 RANSAC(Random Sample Consensus,随机采样一致性)是一种常用的鲁棒估计方法,广泛应用于点云数据的平面拟合和平面分割。通过该算法可以有效提取点云中的平面区域,并进一步利用其他技术检测或提取孔洞。 #### 平面分割流程 以下是使用RANSAC进行平面分割的主要过程: 1. **初始化参数** 设置初始参数,包括迭代次数`N`、距离阈值`threshold`以及最小样本数`min_samples`。对于平面拟合而言,`min_samples=3`,因为三点决定一个平面[^1]。 2. **随机选取样本集** 随机从点云中抽取三个不共线的点作为候选平面的基础点集合。 3. **构建假设模型** 利用这三个点计算平面方程 \( Ax + By + Cz + D = 0 \),其中系数可通过矩阵求解得到[^3]。 4. **评估模型质量** 计算其余点到此平面的距离,筛选出满足条件的内点(inliers),即距离小于`threshold`的点。记录当前模型及其对应内点数量。 5. **重复优化** 迭代执行上述步骤直至达到最大迭代次数`N`,最终选择具有最多内点的模型作为最佳平面。 6. **分离目标与背景** 将最优平面对应的内点视为目标平面的一部分,剩余外点则构成新的子点云集,可继续递归应用RANSAC或其他方法处理。 #### 孔洞检测策略 完成平面分割后,需针对残留点云实施孔洞探测操作。常用的技术手段包括但不限于以下几种方式: - **半径滤波** 应用半径滤波器移除孤立噪点或者稀疏分布的小规模簇群,从而初步清理干扰因素。 - **连通域分析** 基于欧几里得聚类等方法划分独立连接组件,统计各组的空间特性指标如面积、周长等属性差异显著者可能指示潜在缺陷位置[^2]。 - **曲率估算** 结合局部几何结构信息推导表面弯曲程度的变化趋势,异常突变处往往暗示存在凹陷型缺损状况[^4]。 - **边界追踪** 使用特定规则界定轮廓边缘路径走向,配合拓扑学理论验证闭合状态是否完好无损,进而确认开口范围界限所在之处。 ```python import numpy as np from sklearn.linear_model import RANSACRegressor def ransac_plane_segmentation(points, max_iterations=100, threshold=0.01): best_inlier_count = 0 best_model = None for _ in range(max_iterations): sample_indices = np.random.choice(len(points), size=3, replace=False) sampled_points = points[sample_indices] # Fit plane model using the three sampled points A = np.hstack([sampled_points[:, :2], np.ones((3, 1))]) B = sampled_points[:, 2].reshape(-1, 1) try: coeffs, residuals, rank, s = np.linalg.lstsq(A, B, rcond=None) except Exception as e: continue normal_vector = np.append(coeffs[:2], -1).flatten() d = -coeffs[-1][0] distances = abs(np.dot(normal_vector, points.T) + d) / np.linalg.norm(normal_vector) inliers = points[distances < threshold] if len(inliers) > best_inlier_count: best_inlier_count = len(inliers) best_model = (normal_vector, d) return best_model # Example usage with synthetic data points = np.array([[x, y, z] for x in np.linspace(0, 1, 100) for y in np.linspace(0, 1, 100)]) noise = np.random.normal(scale=0.01, size=(len(points), 3)) points += noise model = ransac_plane_segmentation(points) print(f"Fitted Plane Model: {model}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点云实验室lab

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值