平面分割
bool PclTool::planeSegmentation(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, pcl::ModelCoefficients::Ptr coefficients, pcl::PointIndices::Ptr inliers)
{std::cout << "Point cloud data: " << cloud->points.size() << " points" << std::endl;// 创建分割时所需要的模型系数对象,coefficients及存储内点的点索引集合对象inliers// pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);// pcl::PointIndices::Ptr inliers(new pcl::PointIndices);// pcl::ModelCoefficients用于存储平面模型的系数(A、B、C和D)。// Model coefficients: 0 0 1 -1:平面模型的系数表示为[A, B, C, D],其中A、B、C表示平面的法向量,D表示平面到原点的距离。在这里,系数为[0, 0, 1, -1],表示平面的法向量在Z轴上,距离原点的距离为1,即平面方程为Z=1。// 而pcl::PointIndices用于存储内点的索引// 创建分割对象pcl::SACSegmentation<pcl::PointXYZ> seg;// 可选择配置,设置模型系数需要优化seg.setOptimizeCoefficients(true);// 必要的配置,设置分割的模型类型,所用的随机参数估计方法,距离阀值,输入点云seg.setModelType(pcl::SACMODEL_PLANE); // 设置模型类型seg.setMethodType(pcl::SAC_RANSAC); // 设置随机采样一致性方法类型seg.setDistanceThreshold(0.01); // 设定距离阀值,距离阀值决定了点被认为是局内点是必须满足的条件// 表示点到估计模型的距离最大值,seg.setInputCloud(cloud);// 引发分割实现,存储分割结果到点几何inliers及存储平面模型的系数coefficientsseg.segment(*inliers, *coefficients);if (inliers->indices.size() == 0){std::cout << "Could not estimate a planar model for the given dataset." << std::endl;return false;}return true;
}
测试代码
// 平面分割pcl::PointCloud<pcl::PointXYZ>::Ptr planeSeg_cloud(new pcl::PointCloud<pcl::PointXYZ>);// 填充点云planeSeg_cloud->width = 15;planeSeg_cloud->height = 1;planeSeg_cloud->points.resize(planeSeg_cloud->width * planeSeg_cloud->height);// 生成数据,采用随机数填充点云的x,y坐标,都处于z为1的平面上for (size_t i = 0; i < planeSeg_cloud->points.size(); ++i){planeSeg_cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);planeSeg_cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);planeSeg_cloud->points[i].z = 1.0;}// 设置几个局外点,即重新设置几个点的z值,使其偏离z为1的平面planeSeg_cloud->points[0].z = 2.0;planeSeg_cloud->points[3].z = -2.0;planeSeg_cloud->points[6].z = 4.0;pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);pcl::PointIndices::Ptr inliers(new pcl::PointIndices);PclTool::planeSegmentation(planeSeg_cloud, coefficients, inliers);if (inliers->indices.size() == 0){std::cout << "Could not estimate a planar model for the given dataset." << std::endl;}// 打印出平面模型std::cout << "Model coefficients: " << coefficients->values[0] << " " << coefficients->values[1] << " " << coefficients->values[2] << " " << coefficients->values[3] << std::endl;std::cout << "Model inliers: " << inliers->indices.size() << std::endl;for (size_t i = 0; i < inliers->indices.size(); ++i){std::cout << inliers->indices[i] << "\t" << planeSeg_cloud->points[inliers->indices[i]].x << " " << planeSeg_cloud->points[inliers->indices[i]].y << " " << planeSeg_cloud->points[inliers->indices[i]].z << std::endl;}return 0;
反馈结果
- Model coefficients: 0 0 1 -1:平面模型的系数表示为[A, B, C, D],其中A、B、C表示平面的法向量,D表示平面到原点的距离。在这里,系数为[0, 0, 1, -1],表示平面的法向量在Z轴上,距离原点的距离为1,即平面方程为Z=1。
- pcl::PointIndices用于存储内点的索引