PCL中利用ExtractIndices按点云索引提取点云子集

点云操作过程中经常会需要提取点云子集,包括一些点云滤波算法也会经常得到点云的索引,然后根据这些点云索引来提取点云子集,下面代码示例了如何利用索引向量来构建点云索引并提取点云子集。

/*======================================================================
* Author   : Haiming Zhang
* Email    : [email protected]
* Version  : 2018年10月29日
* Copyright    :
* Descriptoin  :
* References   :
======================================================================*/

#include 
#include 
#include 
#include 
#include 
#include 
using std::cout; using std::endl;
int main()
{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_p(new pcl::PointCloud<pcl::PointXYZ>);
  cloud->width = 5;
  cloud->height = 1;
  cloud->points.resize (cloud->width * cloud->height);

  for (size_t i = 0; i < cloud->points.size (); ++i)
  {
    cloud->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f);
    cloud->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f);
    cloud->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f);
  }
  std::cerr << "Cloud before extract: " << std::endl;
  for (size_t i = 0; i < cloud->points.size (); ++i)
    std::cerr << "    " << cloud->points[i].x << " "
    << cloud->points[i].y << " "
    << cloud->points[i].z << std::endl;

  std::vector<int> index = {1,3,4};//提取1,3,4位置处点云
  boost::shared_ptr<std::vector<int>> index_ptr = boost::make_shared<std::vector<int>>(index);
  // Create the filtering object
  pcl::ExtractIndices<pcl::PointXYZ> extract;
  // Extract the inliers
  extract.setInputCloud (cloud);
  extract.setIndices (index_ptr);
  extract.setNegative (false);//如果设为true,可以提取指定index之外的点云
  extract.filter (*cloud_p);

  cout<<"----------------"<<endl;
  for (size_t i = 0; i < cloud_p->points.size (); ++i)
      std::cerr << "    " << cloud_p->points[i].x << " "
      << cloud_p->points[i].y << " "
      << cloud_p->points[i].z << std::endl;
}

输出结果:

Cloud before extract: 
    0.352222 -0.151883 -0.106395
    -0.397406 -0.473106 0.292602
    -0.731898 0.667105 0.441304
    -0.734766 0.854581 -0.0361733
    -0.4607 -0.277468 -0.916762
----------------
    -0.397406 -0.473106 0.292602
    -0.734766 0.854581 -0.0361733
    -0.4607 -0.277468 -0.916762

ExtractIndices类可以提供多种功能的点云子集提取,如果只是提取指定索引的点云组成一个新的点云,还可以用pcl::copyPointCloud函数:

std::vector<int > indexs = { 1, 2, 5 };//声明索引值
pcl::copyPointCloud(*cloud, indexs, *cloud_p);//将对应索引的点存储

你可能感兴趣的:(#,PCL)