PCL点云聚类:以指定点为中心、指定半径聚类(C++)
PCL点云聚类:以指定点为中心、指定半径聚类(C++)
本篇博客将介绍如何使用PCL库(版本1.8.1)编写C++代码,实现以预先指定的点为中心、指定半径进行点云聚类。
代码示例
#include <iostream>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/segmentation/extract_clusters.h>
int main()
{
// 加载点云数据
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile<pcl::PointXYZ>('input_cloud.pcd', *cloud);
// 指定聚类中心点p和半径r
pcl::PointXYZ p;
p.x = 0.0; // 例如,将x坐标设为0.0
p.y = 0.0; // 例如,将y坐标设为0.0
p.z = 0.0; // 例如,将z坐标设为0.0
double r = 0.5; // 例如,将半径设为0.5米
// 创建KdTree用于搜索
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud(cloud);
// 执行半径搜索
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
tree->radiusSearch(p, r, pointIdxRadiusSearch, pointRadiusSquaredDistance);
// 创建点云索引对象,存储聚类结果
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
inliers->indices = pointIdxRadiusSearch;
// 从点云中提取聚类
pcl::PointCloud<pcl::PointXYZ>::Ptr cluster(new pcl::PointCloud<pcl::PointXYZ>);
pcl::ExtractIndices<pcl::PointXYZ> extract;
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(false); // 设置为false以提取聚类点云
extract.filter(*cluster);
// 可视化聚类结果
pcl::visualization::PCLVisualizer viewer('Cluster viewer');
int cluster_id = 0;
// 生成随机颜色
unsigned char r = rand() % 256;
unsigned char g = rand() % 256;
unsigned char b = rand() % 256;
// 可视化聚类
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cluster_color(cluster, r, g, b);
viewer.addPointCloud<pcl::PointXYZ>(cluster, cluster_color, 'cluster_' + std::to_string(cluster_id));
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, 'cluster_' + std::to_string(cluster_id));
cluster_id++;
// 可视化原始点云
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_color(cloud, 255, 255, 255);
viewer.addPointCloud<pcl::PointXYZ>(cloud, cloud_color, 'cloud');
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, 'cloud');
// 显示可视化窗口
while (!viewer.wasStopped())
{
viewer.spinOnce();
}
return 0;
}
代码说明
- 加载点云数据: 首先,使用
pcl::io::loadPCDFile函数加载名为'input_cloud.pcd'的点云数据文件。 - 指定聚类中心点和半径: 定义一个
pcl::PointXYZ类型的变量p作为聚类中心点,并设置其x,y,z坐标。定义一个double类型的变量r作为聚类半径。 - 创建KdTree并执行半径搜索: 使用
pcl::search::KdTree创建KdTree结构,并使用radiusSearch函数搜索在指定半径r内,以p为中心的点云数据。 - 提取聚类结果: 将搜索到的点云索引存储在
pcl::PointIndices对象中,并使用pcl::ExtractIndices过滤器提取对应点云数据。 - 可视化: 使用
pcl::visualization::PCLVisualizer类创建可视化窗口,并将原始点云和聚类结果分别使用不同的颜色进行渲染显示。
注意事项
- 请确保将代码中的'input_cloud.pcd'替换为您自己的点云数据文件路径。
- 您需要安装PCL库才能编译和运行此代码。
希望这篇博客能够帮助您理解如何使用PCL库实现以指定点为中心、指定半径的点云聚类。如果您有任何问题,请随时在下方留言。
原文地址: http://www.cveoy.top/t/topic/fCA9 著作权归作者所有。请勿转载和采集!