使用pcl库编写kruskal最小生成树检测点云ply文件内点的最短路径并将其可视化且创建一个条件判断如果最小生成树跑出来的路径上点的个数小于3就将该条路径删除的c++代码
下面是使用pcl库编写Kruskal最小生成树算法,检测点云PLY文件内点的最短路径,并可视化的C++代码。同时,添加了一个条件判断,如果最小生成树中路径上的点的个数小于3,则将该路径删除。
#include <iostream>
#include <pcl/point_types.h>
#include <pcl/io/ply_io.h>
#include <pcl/visualization/pcl_visualizer.h>
struct Edge {
int src;
int tgt;
float weight;
Edge(int s, int t, float w) : src(s), tgt(t), weight(w) {}
};
struct Point {
float x;
float y;
float z;
Point(float x, float y, float z) : x(x), y(y), z(z) {}
};
bool compareEdges(const Edge& e1, const Edge& e2) {
return e1.weight < e2.weight;
}
int findParent(int* parent, int i) {
if (parent[i] == -1)
return i;
return findParent(parent, parent[i]);
}
void unionSet(int* parent, int x, int y) {
int xset = findParent(parent, x);
int yset = findParent(parent, y);
parent[xset] = yset;
}
void kruskalMST(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, std::vector<Edge>& edges, std::vector<int>& mstIndices) {
int numPoints = cloud->size();
int* parent = new int[numPoints];
memset(parent, -1, numPoints * sizeof(int));
std::sort(edges.begin(), edges.end(), compareEdges);
int count = 0;
for (const auto& edge : edges) {
int srcParent = findParent(parent, edge.src);
int tgtParent = findParent(parent, edge.tgt);
if (srcParent != tgtParent) {
mstIndices.push_back(count);
unionSet(parent, srcParent, tgtParent);
}
count++;
}
delete[] parent;
}
void visualizePointCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, std::vector<int>& mstIndices) {
pcl::visualization::PCLVisualizer viewer("Point Cloud Visualization");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_color(cloud, 0, 255, 0);
viewer.addPointCloud(cloud, cloud_color, "cloud");
pcl::PointXYZ p1, p2;
for (const auto& idx : mstIndices) {
p1 = cloud->at(idx);
p2 = cloud->at(idx + 1);
std::stringstream ss;
ss << "edge_" << idx;
viewer.addLine<pcl::PointXYZ>(p1, p2, ss.str());
}
viewer.spin();
}
int main() {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PLYReader reader;
reader.read("input.ply", *cloud);
std::vector<Edge> edges;
for (int i = 0; i < cloud->size(); i++) {
for (int j = i + 1; j < cloud->size(); j++) {
float x1 = cloud->at(i).x;
float y1 = cloud->at(i).y;
float z1 = cloud->at(i).z;
float x2 = cloud->at(j).x;
float y2 = cloud->at(j).y;
float z2 = cloud->at(j).z;
float distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2));
edges.emplace_back(i, j, distance);
}
}
std::vector<int> mstIndices;
kruskalMST(cloud, edges, mstIndices);
if (mstIndices.size() < 3) {
mstIndices.clear();
}
visualizePointCloud(cloud, mstIndices);
return 0;
}
请将代码中的input.ply替换为您实际的PLY文件路径。注意,此代码假定PLY文件包含pcl::PointXYZ类型的点云数据
原文地址: https://www.cveoy.top/t/topic/hDhI 著作权归作者所有。请勿转载和采集!