PCL点云聚类:以指定点为中心的C++代码示例
PCL点云聚类:以指定点为中心的C++代码示例
本文提供了一个使用PCL 1.8.1版本库进行点云聚类的C++代码示例。与传统的聚类算法不同,该算法以用户指定的点作为聚类中心,方便对特定区域进行分析。
代码示例cpp#include #include <pcl/point_types.h>#include <pcl/segmentation/extract_clusters.h>
int main(){ pcl::PointCloudpcl::PointXYZ::Ptr cloud(new pcl::PointCloudpcl::PointXYZ); // 假设cloud为输入点云数据
// 设置点云数据 cloud->width = 8; cloud->height = 1; cloud->points.resize(cloud->width * cloud->height);
for (size_t i = 0; i < cloud->points.size(); ++i) { cloud->points[i].x = static_cast<float>(1024 * rand() / (RAND_MAX + 1.0)); cloud->points[i].y = static_cast<float>(1024 * rand() / (RAND_MAX + 1.0)); cloud->points[i].z = static_cast<float>(1024 * rand() / (RAND_MAX + 1.0)); }
// **指定聚类中心点** pcl::PointXYZ center_point; center_point.x = 0.5; // 设置您想要的中心点x坐标 center_point.y = 0.8; // 设置您想要的中心点y坐标 center_point.z = 1.2; // 设置您想要的中心点z坐标
// 计算点云中每个点到中心点的距离 std::vector<double> distances(cloud->points.size()); for (size_t i = 0; i < cloud->points.size(); ++i) { distances[i] = pcl::euclideanDistance(cloud->points[i], center_point); }
// 设置聚类算法的参数 pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud(cloud);
std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; ec.setClusterTolerance(0.02); // 设置聚类的容差 ec.setMinClusterSize(100); // 设置聚类的最小尺寸 ec.setMaxClusterSize(25000); // 设置聚类的最大尺寸 ec.setSearchMethod(tree); ec.setInputCloud(cloud);
// 根据距离进行过滤,只保留距离中心点小于阈值的点进行聚类 double distance_threshold = 0.5; // 设置距离阈值 pcl::PointIndices::Ptr inliers(new pcl::PointIndices()); for (size_t i = 0; i < distances.size(); ++i) { if (distances[i] <= distance_threshold) { inliers->indices.push_back(i); } }
ec.setIndices(inliers); // 将过滤后的点索引传递给聚类算法 ec.extract(cluster_indices);
// 输出聚类结果 std::cout << 'Number of clusters: ' << cluster_indices.size() << std::endl; for (const auto &indices : cluster_indices) { std::cout << 'Cluster size: ' << indices.indices.size() << std::endl; for (const auto &index : indices.indices) { std::cout << cloud->points[index].x << ' ' << cloud->points[index].y << ' ' << cloud->points[index].z << std::endl; } std::cout << std::endl; }
return 0;}
代码解读
- 引入头文件: 引入必要的PCL头文件,包括
pcl/point_types.h和pcl/segmentation/extract_clusters.h。2. 创建点云: 创建pcl::PointCloud<pcl::PointXYZ>::Ptr类型的点云指针,并使用随机数填充点云数据。3. 指定聚类中心点: 定义pcl::PointXYZ类型的center_point变量,并设置其x、y、z坐标作为聚类中心点。4. 计算距离: 使用pcl::euclideanDistance函数计算点云中每个点到中心点的距离,并将结果存储在distances向量中。5. 设置聚类参数: 创建pcl::search::KdTree对象,并设置聚类算法pcl::EuclideanClusterExtraction的参数,包括容差、最小/最大簇大小等。6. 根据距离过滤: 设置距离阈值distance_threshold,并将距离中心点小于该阈值的点的索引存储在inliers中。7. 执行聚类: 将过滤后的点索引传递给pcl::EuclideanClusterExtraction对象,并调用extract函数执行聚类。8. 输出结果: 遍历聚类结果,输出每个簇的大小和点云坐标。
总结
此代码示例展示了如何使用PCL库实现以指定点为中心的点云聚类。通过修改中心点坐标和距离阈值,您可以根据实际需求对点云进行灵活的分割和分析。
原文地址: https://www.cveoy.top/t/topic/fDOP 著作权归作者所有。请勿转载和采集!