基于PCL 1.8.1 的欧式聚类算法:以已知点为起点并可视化结果

本文介绍如何使用 PCL (Point Cloud Library) 1.8.1 版本实现以已知点为起点的欧式聚类算法,并将聚类结果可视化。

C++ 代码示例

以下是完整的 C++ 代码:cpp#include #include <pcl/io/pcd_io.h>#include <pcl/point_types.h>#include <pcl/visualization/pcl_visualizer.h>#include <pcl/segmentation/extract_clusters.h>

typedef pcl::PointXYZ PointT;

int main(int argc, char** argv){ // 读取点云数据 pcl::PointCloud::Ptr cloud(new pcl::PointCloud); pcl::io::loadPCDFile('input.pcd', *cloud);

// 创建欧式聚类对象    pcl::EuclideanClusterExtraction<PointT> ec;    ec.setClusterTolerance(0.02); // 设置聚类的容差    ec.setMinClusterSize(100); // 设置聚类的最小尺寸    ec.setMaxClusterSize(25000); // 设置聚类的最大尺寸

// 设置要聚类的点云数据    ec.setInputCloud(cloud);

// 设置聚类的起始点    pcl::PointXYZ seed_point;    seed_point.x = 1.0;    seed_point.y = 2.0;    seed_point.z = 3.0;    std::vector<pcl::PointIndices> cluster_indices;    // 注意:这里设置索引为点云最后一个点,仅为示例,实际使用需根据 seed_point 找到最近点索引    ec.setIndices(std::vector<int>(1, cloud->points.size() - 1)); 

// 执行聚类    ec.extract(cluster_indices);

// 可视化聚类结果    pcl::visualization::PCLVisualizer viewer('Cluster viewer');    viewer.setBackgroundColor(0, 0, 0);    viewer.addPointCloud(cloud, 'cloud');

int cluster_color = 1;    for (const auto& indices : cluster_indices)    {        pcl::PointCloud<PointT>::Ptr cluster(new pcl::PointCloud<PointT>);        for (const auto& index : indices.indices)        {            cluster->points.push_back(cloud->points[index]);        }        cluster->width = cluster->size();        cluster->height = 1;        cluster->is_dense = true;

    std::string cluster_name = 'cluster_' + std::to_string(cluster_color);        pcl::visualization::PointCloudColorHandlerCustom<PointT> cluster_color_handler(cluster, 255, 255, 255);        viewer.addPointCloud(cluster, cluster_color_handler, cluster_name);        viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, cluster_name);

    cluster_color++;    }

while (!viewer.wasStopped())    {        viewer.spinOnce();    }

return 0;}

代码说明

  1. 包含头文件: 代码首先包含了必要的 PCL 头文件。2. 读取点云数据: 使用 pcl::io::loadPCDFile 函数读取名为 'input.pcd' 的点云文件。3. 创建欧式聚类对象: 创建 pcl::EuclideanClusterExtraction 对象,并设置聚类参数,例如 setClusterTolerance (聚类容差), setMinClusterSize (最小尺寸) 和 setMaxClusterSize (最大尺寸)。4. 设置聚类起始点: 设置 seed_point 的坐标作为聚类的起点,并通过 setIndices 函数将起始点索引传递给聚类对象。 注意: 示例代码中使用了点云最后一个点作为起始点,实际应用中需要根据 seed_point 找到最近的点。5. 执行聚类: 调用 extract 函数执行欧式聚类算法。6. 可视化聚类结果: 使用 pcl::visualization::PCLVisualizer 创建可视化窗口,并将聚类结果以不同颜色显示。

总结

本代码演示了如何使用 PCL 库实现以已知点为起点的欧式聚类算法,并使用可视化工具展示结果。您可以根据自己的需要修改代码,例如更改聚类参数、读取不同的点云数据或自定义可视化效果。

基于PCL 1.8.1 的欧式聚类算法:以已知点为起点并可视化结果

原文地址: https://www.cveoy.top/t/topic/fDMh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录