pcl点云聚类方法

本节记录下点云聚类方法

1.欧式聚类分割方法

//为提取点云时使用的搜素对象利用输入点云cloud_filtered创建Kd树对象tree。

pcl::search::KdTree::Ptr tree (new pcl::search::KdTree);
tree->setInputCloud (cloud_filtered);//创建点云索引向量,用于存储实际的点云信息

首先创建一个Kd树对象作为提取点云时所用的搜索方法,再创建一个点云索引向量cluster_indices,用于存储实际的点云索引信息,每个检测到的点云聚类被保存在这里。请注意: cluster_indices是一个向量,对每个检测到的聚类,它都包含一个索引点的实例,如cluster_indices[0]包含点云中第一个聚类包含的点集的所有索引。

std::vector<pcl::PointIndices> cluster_indices;
pcl::EuclideanClusterExtraction 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中

因为点云是PointXYZ类型的,所以这里用点云类型PointXYZ创建一个欧氏聚类对象,并设置提取的参数和变量。注意:设置一个合适的聚类搜索半径ClusterTolerance,如果搜索半径取一个非常小的值,那么一个实际的对象就会被分割为多个聚类;如果将值设置得太高,那么多个对象就会被分割为一个聚类,所以需要进行测试找出最适合的ClusterTolerance。本例用两个参数来限制找到的聚类:用setMinClusterSize()来限制一个聚类最少需要的点数目,用setMaXClusterSize()来限制最多需要的点数目。接下来我们从点云中提取聚类,并将点云索引保存在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>);
    //创建新的点云数据集cloud_cluster,将所有当前聚类写入到点云数据集中
    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; 
    }
    pcl::visualization::CloudViewer viewer("Cloud Viewer");
    viewer.showCloud(cloud_cluster);
    pause();
    }
保存每个cloud_cluster为单独的.pcd文件,一个文件就是一个聚类
}
}

猜你喜欢

转载自blog.csdn.net/weixin_41038905/article/details/80976948