{ "title": "PCL 2-Means 聚类:点云数据聚类与可视化", "description": "使用 PCL 库实现 2-Means 聚类算法,将点云数据划分为不同的类别,并利用不同的颜色进行可视化展示。", "keywords": "PCL, 2-Means 聚类, 点云数据, 聚类算法, 可视化, C++", "content": "#include "iostream" #include "pcl/io/ply_io.h" #include "pcl/point_types.h" #include "pcl/features/normal_3d.h" #include "pcl/kdtree/kdtree_flann.h" #include "pcl/segmentation/extract_clusters.h" #include "pcl/visualization/pcl_visualizer.h"

typedef pcl::PointXYZ PointT; typedef pcl::PointCloud PointCloudT;

// 计算两个点之间的欧氏距离 float distance(PointT p1, PointT p2) { float dx = p1.x - p2.x; float dy = p1.y - p2.y; float dz = p1.z - p2.z; return sqrt(dx*dx + dy * dy + dz * dz); }

// 2-均值聚类 void kMeansClustering(PointCloudT::Ptr cloud, std::vectorpcl::PointIndices& cluster_indices) { pcl::search::KdTree::Ptr tree(new pcl::search::KdTree); tree->setInputCloud(cloud);

pcl::EuclideanClusterExtraction<PointT> ec;
ec.setClusterTolerance(0.5); // 聚类的距离阈值
ec.setMinClusterSize(10); // 最小聚类大小
ec.setMaxClusterSize(250); // 最大聚类大小
ec.setSearchMethod(tree);
ec.setInputCloud(cloud);
ec.extract(cluster_indices);

}

int main() { std::string input_path = "D:\DIANYUNWENJIANJIA\kruskal_ply.ply"; std::string output_path = "D:\DIANYUNWENJIANJIA\2MEANS_ply.ply";

// 加载点云数据
PointCloudT::Ptr cloud(new PointCloudT);
pcl::io::loadPLYFile(input_path, *cloud);

// 计算法线
pcl::NormalEstimation<PointT, pcl::Normal> ne;
pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);
ne.setSearchMethod(tree);
ne.setInputCloud(cloud);
ne.setKSearch(50);
ne.compute(*normals);

// 聚类
std::vector<pcl::PointIndices> cluster_indices;
kMeansClustering(cloud, cluster_indices);

// 可视化
pcl::visualization::PCLVisualizer viewer("2-Means Clustering");
viewer.setBackgroundColor(0, 0, 0);
int cluster_color = 1;
for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it) {
	pcl::PointCloud<PointT>::Ptr cluster(new pcl::PointCloud<PointT>);
	for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit)
		cluster->points.push_back(cloud->points[*pit]);
	cluster->width = cluster->points.size();
	cluster->height = 1;
	cluster->is_dense = true;

	pcl::visualization::PointCloudColorHandlerCustom<PointT> color_handler(cluster, cluster_color * 50, cluster_color * 50, cluster_color * 50);
	viewer.addPointCloud(cluster, color_handler, "cluster_" + std::to_string(cluster_color));
	viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cluster_" + std::to_string(cluster_color));
	cluster_color++;
}

// 保存输出点云
pcl::io::savePLYFile(output_path, *cloud);

// 显示可视化窗口
while (!viewer.wasStopped()) {
	viewer.spinOnce();
}

return 0;

}

PCL 2-Means 聚类:点云数据聚类与可视化

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

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