代码实现:
void euclideanclusters(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>& clusters,
float threshold, int min_cluster_size, int max_cluster_size)
{
pcl::KdTreeFLANN<pcl::PointXYZ> tree;
tree.setInputCloud(cloud);
std::vector<pcl::PointIndices> cluster_indices; //定义储存聚类点云的索引
std::vector<bool> processed(cloud->points.size(), false); //定义点云的点是否被处理过的标记
std::vector<int> nn_indices; //kdtree搜索到的点的索引
std::vector<float> nn_distances; //kdtree搜索到的点的距离
for (int i = 0; i < cloud->points.size(); ++i) //遍历点云中的每一个点
{
if (processed[i]) continue; //如果该点已经处理则跳过
std::vector<int> seed_queue; //定义一个种子点队列
int sq_idx = 0; //记录已经处理种子点队列中的种子点的个数
seed_queue.push_back(i); //加入一个种子点
processed[i] = true; //标记这个种子点已经被搜索过了
while (sq_idx < seed_queue.size()) //遍历每一个种子点
{
//kdtree近邻搜索
if (!tree.radiusSearch(seed_queue[sq_idx], threshold, nn_indices, nn_distances))
{
++sq_idx;
continue; //没找到近邻点就继续
}
for (size_t j = 0; j < nn_indices.size(); ++j) //遍历搜索到的种子点的邻近点
{
if (processed[nn_indices[j]]) continue; //种子点的近邻点中如果已经处理则跳出循环
seed_queue.push_back(nn_indices[j]); //将此种子点的临近点作为新的种子点,入队操作
processed[nn_indices[j]] = true; //该点已经处理,打标签
}
++sq_idx;
}
//过滤满足最大点数和最小点数的类
if (seed_queue.size() >= min_cluster_size && seed_queue.size() <= max_cluster_size)
{
pcl::PointIndices r;
r.indices = seed_queue;
cluster_indices.push_back(r);
}
}
//存储每个聚类
for (int i = 0; i < cluster_indices.size(); ++i)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cluster_temp(new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*cloud, cluster_indices[i].indices, *cluster_temp);
clusters.push_back(cluster_temp);
}
}
参考:PCL 的欧式距离聚类
代码传送门:https://github.com/taifyang/PCL-algorithm