https://pcl.readthedocs.io/projects/tutorials/en/latest/#segmentation
https://pointclouds.org/documentation/group__segmentation.html

PCL中分割_欧式分割(1)
PCL中分割方法的介绍(2)
PCL中分割方法的介绍(3)

PCL点云分割(1)官方文档tutorials 前三示例
PCL点云分割(2)
PCL点云分割(3)

此模块个人代码:https://github.com/HuangCongQing/pcl-learning/tree/master/12segmentation

介绍

点云分割是根据空间,几何和纹理等特征对点云进行划分,使得同一划分内的点云拥有相似的特征,点云的有效分割往往是许多应用的前提,例如逆向工作,CAD领域对零件的不同扫描表面进行分割,然后才能更好的进行空洞修复曲面重建,特征描述和提取,进而进行基于3D内容的检索,组合重用等。

官方tutorials

1 Plane model segmentation 平面分割

代码实现

创建文件:planar_segmentation.cpp
准备资源:
编译执行:./planar_segmentation

个人代码:12segmentation分割

  1. /*
  2. * @Description: 用一组点云数据做简单的平面的分割:https://www.cnblogs.com/li-yao7758258/p/6496664.html
  3. * @Author: HCQ
  4. * @Company(School): UCAS
  5. * @Date: 2020-10-13 16:33:43
  6. * @LastEditors: HCQ
  7. * @LastEditTime: 2020-10-13 17:32:41
  8. */
  9. #include <iostream>
  10. #include <pcl/ModelCoefficients.h>
  11. #include <pcl/io/pcd_io.h>
  12. #include <pcl/point_types.h>
  13. #include <pcl/sample_consensus/method_types.h> //随机参数估计方法头文件
  14. #include <pcl/sample_consensus/model_types.h> //模型定义头文件
  15. #include <pcl/segmentation/sac_segmentation.h> //基于采样一致性分割的类的头文件
  16. int main(int argc, char **argv)
  17. {
  18. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
  19. // 填充点云
  20. cloud->width = 15;
  21. cloud->height = 1;
  22. cloud->points.resize(cloud->width * cloud->height);
  23. // 生成数据,采用随机数填充点云的x,y坐标,都处于z为1的平面上
  24. for (size_t i = 0; i < cloud->points.size(); ++i)
  25. {
  26. cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
  27. cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
  28. cloud->points[i].z = 1.0;
  29. }
  30. // 设置几个局外点,即重新设置几个点的z值,使其偏离z为1的平面
  31. cloud->points[0].z = 2.0;
  32. cloud->points[3].z = -2.0;
  33. cloud->points[6].z = 4.0;
  34. std::cerr << "Point cloud data: " << cloud->points.size() << " points" << std::endl; //打印
  35. for (size_t i = 0; i < cloud->points.size(); ++i)
  36. std::cerr << " " << cloud->points[i].x << " "
  37. << cloud->points[i].y << " "
  38. << cloud->points[i].z << std::endl;
  39. //创建分割时所需要的模型系数对象,coefficients及存储内点的点索引集合对象inliers
  40. pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
  41. pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
  42. // 创建分割对象
  43. pcl::SACSegmentation<pcl::PointXYZ> seg;
  44. // 可选择配置,设置模型系数需要优化
  45. seg.setOptimizeCoefficients(true);
  46. // 必要的配置,设置分割的模型类型,所用的随机参数估计方法,距离阀值,输入点云
  47. seg.setModelType(pcl::SACMODEL_PLANE); //设置模型类型
  48. seg.setMethodType(pcl::SAC_RANSAC); //设置随机采样一致性方法类型
  49. seg.setDistanceThreshold(0.01); //设定距离阀值,距离阀值决定了点被认为是局内点是必须满足的条件
  50. //表示点到估计模型的距离最大值,
  51. seg.setInputCloud(cloud);
  52. //引发分割实现,存储分割结果到点几何inliers及存储平面模型的系数coefficients
  53. seg.segment(*inliers, *coefficients);
  54. if (inliers->indices.size() == 0)
  55. {
  56. PCL_ERROR("Could not estimate a planar model for the given dataset.");
  57. return (-1);
  58. }
  59. //打印出平面模型
  60. std::cerr << "Model coefficients: " << coefficients->values[0] << " "
  61. << coefficients->values[1] << " "
  62. << coefficients->values[2] << " "
  63. << coefficients->values[3] << std::endl;
  64. std::cerr << "Model inliers: " << inliers->indices.size() << std::endl;
  65. for (size_t i = 0; i < inliers->indices.size(); ++i)
  66. std::cerr << inliers->indices[i] << " " << cloud->points[inliers->indices[i]].x << " "
  67. << cloud->points[inliers->indices[i]].y << " "
  68. << cloud->points[inliers->indices[i]].z << std::endl;
  69. return (0);
  70. }

输出结果

image.png

实现效果

无可视图

2 Cylinder model segmentation 圆柱体分割

实现圆柱体模型的分割:采用随机采样一致性估计从带有噪声的点云中提取一个圆柱体模型。

  1. /*
  2. * @Description: 实现圆柱体模型的分割:采用随机采样一致性估计从带有噪声的点云中提取一个圆柱体模型。:https://www.cnblogs.com/li-yao7758258/p/6496664.html
  3. * @Author: HCQ
  4. * @Company(School): UCAS
  5. * @Date: 2020-10-13 16:33:43
  6. * @LastEditors: HCQ
  7. * @LastEditTime: 2020-10-14 18:41:30
  8. */
  9. #include <pcl/ModelCoefficients.h>
  10. #include <pcl/io/pcd_io.h>
  11. #include <pcl/point_types.h>
  12. #include <pcl/filters/extract_indices.h>
  13. #include <pcl/filters/passthrough.h>
  14. #include <pcl/features/normal_3d.h>
  15. #include <pcl/sample_consensus/method_types.h>
  16. #include <pcl/sample_consensus/model_types.h>
  17. #include <pcl/segmentation/sac_segmentation.h>
  18. #include <pcl/visualization/pcl_visualizer.h> // 可视化
  19. typedef pcl::PointXYZ PointT;
  20. int main(int argc, char **argv)
  21. {
  22. // All the objects needed
  23. pcl::PCDReader reader; //PCD文件读取对象
  24. pcl::PassThrough<PointT> pass; //直通滤波对象
  25. pcl::NormalEstimation<PointT, pcl::Normal> ne; //法线估计对象
  26. pcl::SACSegmentationFromNormals<PointT, pcl::Normal> seg; //分割对象
  27. pcl::PCDWriter writer; //PCD文件读取对象
  28. pcl::ExtractIndices<PointT> extract; //点提取对象
  29. pcl::ExtractIndices<pcl::Normal> extract_normals; ///点提取对象
  30. pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>());
  31. // Datasets
  32. pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);
  33. pcl::PointCloud<PointT>::Ptr cloud_filtered(new pcl::PointCloud<PointT>);
  34. pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>);
  35. pcl::PointCloud<PointT>::Ptr cloud_filtered2(new pcl::PointCloud<PointT>);
  36. pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2(new pcl::PointCloud<pcl::Normal>);
  37. pcl::ModelCoefficients::Ptr coefficients_plane(new pcl::ModelCoefficients), coefficients_cylinder(new pcl::ModelCoefficients);
  38. pcl::PointIndices::Ptr inliers_plane(new pcl::PointIndices), inliers_cylinder(new pcl::PointIndices);
  39. // Read in the cloud data
  40. reader.read("../table_scene_mug_stereo_textured.pcd", *cloud);
  41. std::cerr << "PointCloud has: " << cloud->points.size() << " data points." << std::endl;
  42. // 直通滤波,将Z轴不在(0,1.5)范围的点过滤掉,将剩余的点存储到cloud_filtered对象中
  43. pass.setInputCloud(cloud);
  44. pass.setFilterFieldName("z");
  45. pass.setFilterLimits(0, 1.5);
  46. pass.filter(*cloud_filtered);
  47. std::cerr << "PointCloud after filtering has: " << cloud_filtered->points.size() << " data points." << std::endl;
  48. // 过滤后的点云进行法线估计,为后续进行基于法线的分割准备数据
  49. ne.setSearchMethod(tree);
  50. ne.setInputCloud(cloud_filtered);
  51. ne.setKSearch(50);
  52. ne.compute(*cloud_normals);
  53. // Create the segmentation object for the planar model and set all the parameters
  54. seg.setOptimizeCoefficients(true);
  55. seg.setModelType(pcl::SACMODEL_NORMAL_PLANE);
  56. seg.setNormalDistanceWeight(0.1);
  57. seg.setMethodType(pcl::SAC_RANSAC);
  58. seg.setMaxIterations(100);
  59. seg.setDistanceThreshold(0.03);
  60. seg.setInputCloud(cloud_filtered);
  61. seg.setInputNormals(cloud_normals);
  62. //获取平面模型的系数和处在平面的内点
  63. seg.segment(*inliers_plane, *coefficients_plane);
  64. std::cerr << "Plane coefficients: " << *coefficients_plane << std::endl;
  65. // 从点云中抽取分割的处在平面上的点集
  66. extract.setInputCloud(cloud_filtered);
  67. extract.setIndices(inliers_plane);
  68. extract.setNegative(false);
  69. // 存储分割得到的平面上的点到点云文件
  70. pcl::PointCloud<PointT>::Ptr cloud_plane(new pcl::PointCloud<PointT>());
  71. extract.filter(*cloud_plane);
  72. std::cerr << "PointCloud representing the planar component: " << cloud_plane->points.size() << " data points." << std::endl;
  73. writer.write("table_scene_mug_stereo_textured_plane.pcd", *cloud_plane, false); // 分割得到的平面
  74. // Remove the planar inliers, extract the rest
  75. extract.setNegative(true);
  76. extract.filter(*cloud_filtered2);
  77. extract_normals.setNegative(true);
  78. extract_normals.setInputCloud(cloud_normals);
  79. extract_normals.setIndices(inliers_plane);
  80. extract_normals.filter(*cloud_normals2);
  81. // Create the segmentation object for cylinder segmentation and set all the parameters
  82. seg.setOptimizeCoefficients(true); //设置对估计模型优化
  83. seg.setModelType(pcl::SACMODEL_CYLINDER); //设置分割模型为圆柱形
  84. seg.setMethodType(pcl::SAC_RANSAC); //参数估计方法
  85. seg.setNormalDistanceWeight(0.1); //设置表面法线权重系数
  86. seg.setMaxIterations(10000); //设置迭代的最大次数10000
  87. seg.setDistanceThreshold(0.05); //设置内点到模型的距离允许最大值
  88. seg.setRadiusLimits(0, 0.1); //设置估计出的圆柱模型的半径的范围
  89. seg.setInputCloud(cloud_filtered2);
  90. seg.setInputNormals(cloud_normals2);
  91. // Obtain the cylinder inliers and coefficients
  92. seg.segment(*inliers_cylinder, *coefficients_cylinder);
  93. std::cerr << "Cylinder coefficients: " << *coefficients_cylinder << std::endl;
  94. // Write the cylinder inliers to disk
  95. extract.setInputCloud(cloud_filtered2);
  96. extract.setIndices(inliers_cylinder);
  97. extract.setNegative(false);
  98. pcl::PointCloud<PointT>::Ptr cloud_cylinder(new pcl::PointCloud<PointT>());
  99. extract.filter(*cloud_cylinder);
  100. if (cloud_cylinder->points.empty())
  101. std::cerr << "Can't find the cylindrical component." << std::endl;
  102. else
  103. {
  104. std::cerr << "PointCloud representing the cylindrical component: " << cloud_cylinder->points.size() << " data points." << std::endl;
  105. writer.write("table_scene_mug_stereo_textured_cylinder.pcd", *cloud_cylinder, false); // 分割得到的平面
  106. }
  107. // 可视化
  108. pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("three 三窗口 "));
  109. int v1(0); //设置左右窗口
  110. int v2(1);
  111. int v3(2);
  112. viewer->createViewPort(0.0, 0.0, 0.5,1.0, v1); //(Xmin,Ymin,Xmax,Ymax)设置窗口坐标
  113. viewer->createViewPort(0.5, 0.0, 1.0, 0.5, v2);
  114. viewer->createViewPort(0.5, 0.5, 1.0, 1.0, v3);
  115. pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_red(cloud, 255, 0, 0); // 显示红色点云
  116. viewer->addPointCloud(cloud, cloud_out_red, "cloud_out1", v1);
  117. pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_green(cloud, 0, 255, 0); // 显示绿色点云
  118. viewer->addPointCloud(cloud_plane, cloud_out_green, "cloud_out2", v2); // 平面
  119. pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_blue(cloud, 0, 0, 255); // 显示蓝色点云
  120. viewer->addPointCloud(cloud_cylinder, cloud_out_blue, "cloud_out3", v3); // 圆柱
  121. // 1. 阻塞式
  122. viewer->spin();
  123. // 2. 非阻塞式
  124. // while (!viewer->wasStopped())
  125. // {
  126. // viewer->spinOnce();
  127. // }
  128. return (0);
  129. }

代码实现

创建文件:cylinder_segmentation.cpp
准备资源:../table_scene_mug_stereo_textured.pcd
编译执行:./cylinder_segmentation

个人代码:12segmentation分割

/*
 * @Description: 实现圆柱体模型的分割:采用随机采样一致性估计从带有噪声的点云中提取一个圆柱体模型。:https://www.cnblogs.com/li-yao7758258/p/6496664.html
 * @Author: HCQ
 * @Company(School): UCAS
 * @Date: 2020-10-13 16:33:43
 * @LastEditors: HCQ
 * @LastEditTime: 2020-10-14 18:41:30
 */

#include <pcl/ModelCoefficients.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/passthrough.h>
#include <pcl/features/normal_3d.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> // 可视化

typedef pcl::PointXYZ PointT;

int main(int argc, char **argv)
{
    // All the objects needed
    pcl::PCDReader reader;                                    //PCD文件读取对象
    pcl::PassThrough<PointT> pass;                            //直通滤波对象
    pcl::NormalEstimation<PointT, pcl::Normal> ne;            //法线估计对象
    pcl::SACSegmentationFromNormals<PointT, pcl::Normal> seg; //分割对象
    pcl::PCDWriter writer;                                    //PCD文件读取对象
    pcl::ExtractIndices<PointT> extract;                      //点提取对象
    pcl::ExtractIndices<pcl::Normal> extract_normals;         ///点提取对象
    pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>());

    // Datasets
    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);
    pcl::PointCloud<PointT>::Ptr cloud_filtered(new pcl::PointCloud<PointT>);
    pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>);
    pcl::PointCloud<PointT>::Ptr cloud_filtered2(new pcl::PointCloud<PointT>);
    pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2(new pcl::PointCloud<pcl::Normal>);
    pcl::ModelCoefficients::Ptr coefficients_plane(new pcl::ModelCoefficients), coefficients_cylinder(new pcl::ModelCoefficients);
    pcl::PointIndices::Ptr inliers_plane(new pcl::PointIndices), inliers_cylinder(new pcl::PointIndices);

    // Read in the cloud data
    reader.read("../table_scene_mug_stereo_textured.pcd", *cloud);
    std::cerr << "PointCloud has: " << cloud->points.size() << " data points." << std::endl;

    // 直通滤波,将Z轴不在(0,1.5)范围的点过滤掉,将剩余的点存储到cloud_filtered对象中
    pass.setInputCloud(cloud);
    pass.setFilterFieldName("z");
    pass.setFilterLimits(0, 1.5);
    pass.filter(*cloud_filtered);
    std::cerr << "PointCloud after filtering has: " << cloud_filtered->points.size() << " data points." << std::endl;

    // 过滤后的点云进行法线估计,为后续进行基于法线的分割准备数据
    ne.setSearchMethod(tree);
    ne.setInputCloud(cloud_filtered);
    ne.setKSearch(50);
    ne.compute(*cloud_normals);

    // Create the segmentation object for the planar model and set all the parameters
    seg.setOptimizeCoefficients(true);
    seg.setModelType(pcl::SACMODEL_NORMAL_PLANE);
    seg.setNormalDistanceWeight(0.1);
    seg.setMethodType(pcl::SAC_RANSAC);
    seg.setMaxIterations(100);
    seg.setDistanceThreshold(0.03);
    seg.setInputCloud(cloud_filtered);
    seg.setInputNormals(cloud_normals);
    //获取平面模型的系数和处在平面的内点
    seg.segment(*inliers_plane, *coefficients_plane);
    std::cerr << "Plane coefficients: " << *coefficients_plane << std::endl;

    // 从点云中抽取分割的处在平面上的点集
    extract.setInputCloud(cloud_filtered);
    extract.setIndices(inliers_plane);
    extract.setNegative(false);

    // 存储分割得到的平面上的点到点云文件
    pcl::PointCloud<PointT>::Ptr cloud_plane(new pcl::PointCloud<PointT>());
    extract.filter(*cloud_plane);
    std::cerr << "PointCloud representing the planar component: " << cloud_plane->points.size() << " data points." << std::endl;
    writer.write("table_scene_mug_stereo_textured_plane.pcd", *cloud_plane, false); // 分割得到的平面

    // Remove the planar inliers, extract the rest
    extract.setNegative(true);
    extract.filter(*cloud_filtered2);
    extract_normals.setNegative(true);
    extract_normals.setInputCloud(cloud_normals);
    extract_normals.setIndices(inliers_plane);
    extract_normals.filter(*cloud_normals2);

    // Create the segmentation object for cylinder segmentation and set all the parameters
    seg.setOptimizeCoefficients(true);        //设置对估计模型优化
    seg.setModelType(pcl::SACMODEL_CYLINDER); //设置分割模型为圆柱形
    seg.setMethodType(pcl::SAC_RANSAC);       //参数估计方法
    seg.setNormalDistanceWeight(0.1);         //设置表面法线权重系数
    seg.setMaxIterations(10000);              //设置迭代的最大次数10000
    seg.setDistanceThreshold(0.05);           //设置内点到模型的距离允许最大值
    seg.setRadiusLimits(0, 0.1);              //设置估计出的圆柱模型的半径的范围
    seg.setInputCloud(cloud_filtered2);
    seg.setInputNormals(cloud_normals2);

    // Obtain the cylinder inliers and coefficients
    seg.segment(*inliers_cylinder, *coefficients_cylinder);
    std::cerr << "Cylinder coefficients: " << *coefficients_cylinder << std::endl;

    // Write the cylinder inliers to disk
    extract.setInputCloud(cloud_filtered2);
    extract.setIndices(inliers_cylinder);
    extract.setNegative(false);
    pcl::PointCloud<PointT>::Ptr cloud_cylinder(new pcl::PointCloud<PointT>());
    extract.filter(*cloud_cylinder);
    if (cloud_cylinder->points.empty())
        std::cerr << "Can't find the cylindrical component." << std::endl;
    else
    {
        std::cerr << "PointCloud representing the cylindrical component: " << cloud_cylinder->points.size() << " data points." << std::endl;
        writer.write("table_scene_mug_stereo_textured_cylinder.pcd", *cloud_cylinder, false); // 分割得到的平面
    }
    // 可视化
    pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("three 三窗口 "));
    int v1(0); //设置左右窗口
    int v2(1);
    int v3(2);
    viewer->createViewPort(0.0, 0.0, 0.5,1.0, v1); //(Xmin,Ymin,Xmax,Ymax)设置窗口坐标
    viewer->createViewPort(0.5, 0.0, 1.0, 0.5, v2);
    viewer->createViewPort(0.5, 0.5, 1.0, 1.0, v3);

    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_red(cloud, 255, 0, 0); // 显示红色点云
    viewer->addPointCloud(cloud, cloud_out_red, "cloud_out1", v1);

    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_green(cloud, 0, 255, 0); // 显示绿色点云
    viewer->addPointCloud(cloud_plane, cloud_out_green, "cloud_out2", v2);  // 平面

    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_out_blue(cloud, 0, 0, 255); // 显示蓝色点云
    viewer->addPointCloud(cloud_cylinder, cloud_out_blue, "cloud_out3", v3); // 圆柱

    // 1. 阻塞式
    viewer->spin();
    // 2. 非阻塞式
    // while (!viewer->wasStopped())
    // {
    //     viewer->spinOnce();
    // }
    return (0);
}

输出结果

image.png

实现效果


image.png

3 Euclidean Cluster Extraction 欧几里得簇提取

(3)PCL中实现欧式聚类提取。对三维点云组成的场景进行分割
为了更切合实际的应用我会在这些基本的程序的基础上,进行与实际结合的实例,因为这些都是官方给的实例,我是首先学习一下,至少过一面,这样在后期结合实际应用的过程中会更加容易一点。(因为我也是一边学习,然后回头再在基础上进行更修)

pcl::VoxelGrid (filters)

https://pointclouds.org/documentation/classpcl_1_1_voxel_grid_3_01pcl_1_1_p_c_l_point_cloud2_01_4.html

class pcl::VoxelGrid< PointT >
VoxelGrid assembles a local 3D grid over a given PointCloud, and downsamples + filters the data. More…
VoxelGrid在给定的PointCloud上组装本地3D网格,并对数据进行下采样+过滤。更多…

VoxelGrid类在输入点云数据上创建3D体素网格(将体素网格视为一组空间中的微小3D框

pcl::SACSegmentation seg; (segmentation)

class pcl::SACSegmentation< PointT >
SACSegmentation represents the Nodelet segmentation class for Sample Consensus methods and models, in the sense that it just creates a Nodelet wrapper for generic-purpose SAC-based segmentation. More…
SACSegmentation代表样本共识方法和模型的Nodelet细分类,因为它只是为基于通用SAC的细分创建了Nodelet包装器。更多…
class pcl::SACSegmentationFromNormals< PointT, PointNT >
SACSegmentationFromNormals represents the PCL nodelet segmentation class for Sample Consensus methods and models that require the use of surface normals for estimation. More…

pcl::ExtractIndices extract;(filters)

class ExtractIndices
ExtractIndices extracts a set of indices from a point cloud. More…
ExtractIndices从点云中提取一组索引。更多…
class ExtractIndices< pcl::PCLPointCloud2 >
ExtractIndices extracts a set of indices from a point cloud. More…

pcl::EuclideanClusterExtraction ec; //欧式聚类对象 (segmentation)

class pcl::EuclideanClusterExtraction< PointT >
EuclideanClusterExtraction represents a segmentation class for cluster extraction in an Euclidean sense. More…EuclideanClusterExtraction代表欧几里得意义上的群集提取的细分类别。更多 …

代码实现

创建文件:octree_change_detection.cpp
准备资源:
编译执行:./octree_change_detection

个人代码:12segmentation分割

/*
 * @Description: PCL中实现欧式聚类提取。对三维点云组成的场景进行分割。:https://www.cnblogs.com/li-yao7758258/p/6496664.html
 * @Author: HCQ
 * @Company(School): UCAS
 * @Date: 2020-10-13 16:33:43
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-10-18 11:48:23
 */


#include <pcl/ModelCoefficients.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/features/normal_3d.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_clusters.h>

/******************************************************************************
 打开点云数据,并对点云进行滤波重采样预处理,然后采用平面分割模型对点云进行分割处理
 提取出点云中所有在平面上的点集,并将其存盘
******************************************************************************/
int 
main (int argc, char** argv)
{
  // Read in the cloud data
  pcl::PCDReader reader;
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>), cloud_f (new pcl::PointCloud<pcl::PointXYZ>);
  reader.read ("../table_scene_lms400.pcd", *cloud); // 点云文件
  std::cout << "PointCloud before filtering has: " << cloud->points.size () << " data points." << std::endl; //*

  // Create the filtering object: downsample the dataset using a leaf size of 1cm
  pcl::VoxelGrid<pcl::PointXYZ> vg; // VoxelGrid类在输入点云数据上创建3D体素网格(将体素网格视为一组空间中的微小3D框
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>);
  vg.setInputCloud (cloud); //输入
  vg.setLeafSize (0.01f, 0.01f, 0.01f);  // setLeafSize (float lx, float ly, float lz)
  vg.filter (*cloud_filtered); //输出
  std::cout << "PointCloud after filtering has: " << cloud_filtered->points.size ()  << " data points." << std::endl; //*滤波后
   //创建平面模型分割的对象并设置参数
  pcl::SACSegmentation<pcl::PointXYZ> seg;
  pcl::PointIndices::Ptr inliers (new pcl::PointIndices);
  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZ> ());

  pcl::PCDWriter writer;
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_PLANE);    //分割模型
  seg.setMethodType (pcl::SAC_RANSAC);       //随机参数估计方法
  seg.setMaxIterations (100);                //最大的迭代的次数
  seg.setDistanceThreshold (0.02);           //设置阀值

  int i=0, nr_points = (int) cloud_filtered->points.size ();
  while (cloud_filtered->points.size () > 0.3 * nr_points) // 滤波停止条件
  {
    // Segment the largest planar component from the remaining cloud
    seg.setInputCloud (cloud_filtered); // 输入
    seg.segment (*inliers, *coefficients);
    if (inliers->indices.size () == 0)
    {
      std::cout << "Could not estimate a planar model for the given dataset." << std::endl;
      break;
    }


    pcl::ExtractIndices<pcl::PointXYZ> extract;
    extract.setInputCloud (cloud_filtered);
    extract.setIndices (inliers);
    extract.setNegative (false);

    // Get the points associated with the planar surface
    extract.filter (*cloud_plane);// [平面
    std::cout << "PointCloud representing the planar component: " << cloud_plane->points.size () << " data points." << std::endl;

    //  // 移去平面局内点,提取剩余点云
    extract.setNegative (true);
    extract.filter (*cloud_f);
    *cloud_filtered = *cloud_f;
  }

  // Creating the KdTree object for the search method of the extraction
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
  tree->setInputCloud (cloud_filtered);

  std::vector<pcl::PointIndices> cluster_indices;
  pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec;   //欧式聚类对象
  ec.setClusterTolerance (0.02);                     // 设置近邻搜索的搜索半径为2cm
  ec.setMinClusterSize (100);                 //设置一个聚类需要的最少的点数目为100
  ec.setMaxClusterSize (25000);               //设置一个聚类需要的最大点数目为25000
  ec.setSearchMethod (tree);                    //设置点云的搜索机制
  ec.setInputCloud (cloud_filtered);
  ec.extract (cluster_indices);           //从点云中提取聚类,并将点云索引保存在cluster_indices中
  //迭代访问点云索引cluster_indices,直到分割出所有聚类
  int j = 0;
  for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)
  {
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZ>);
    for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit)

    cloud_cluster->points.push_back (cloud_filtered->points[*pit]); //*
    cloud_cluster->width = cloud_cluster->points.size ();
    cloud_cluster->height = 1;
    cloud_cluster->is_dense = true;

    std::cout << "PointCloud representing the Cluster: " << cloud_cluster->points.size () << " data points." << std::endl;
    std::stringstream ss;
    ss << "../cloud_cluster_" << j << ".pcd";
    writer.write<pcl::PointXYZ> (ss.str (), *cloud_cluster, false); // 保存文件
    j++;
  }

  return (0);
}

输出结果


image.png

实现效果

结果:分割成5部分

image.pngimage.png

image.png

4 Region growing segmentation 区域增长细分

5 Color-based region growing segmentation 基于颜色的区域增长分割

6 Min-Cut Based Segmentation基于最小剪切的分割

7 Conditional Euclidean Clustering 条件欧几里得聚类

8 Difference of Normals Based Segmentation 基于法线的分割差异

9 Clustering of Pointclouds into Supervoxels - Theoretical primer 点云聚集成超级体素-理论底漆

10 Identifying ground returns using ProgressiveMorphologicalFilter segmentation 使用ProgressiveMorphologicalFilter细分识别地面收益

11 Filtering a PointCloud using ModelOutlierRemoval 使用ModelOutlierRemoval过滤PointCloud