C++ PCL 库点云直线拟合: 通过已知两点实现
"#include
int main() { pcl::PointCloudpcl::PointXYZ::Ptr cloud(new pcl::PointCloudpcl::PointXYZ); if (pcl::io::loadPLYFilepcl::PointXYZ("input.ply", *cloud) == -1) // 加载PLY文件 { PCL_ERROR("Couldn't read input file!\n"); return -1; }
pcl::PointXYZ point1(1.0, 2.0, 3.0); // 已知点1
pcl::PointXYZ point2(4.0, 5.0, 6.0); // 已知点2
pcl::SampleConsensusModelLine<pcl::PointXYZ>::Ptr model(new pcl::SampleConsensusModelLine<pcl::PointXYZ>(cloud));
model->setInputCloud(cloud);
model->setIndices(boost::make_shared<std::vector<int>>()); // 不使用索引
model->addSample(point1);
model->addSample(point2);
pcl::RandomSampleConsensus<pcl::PointXYZ> ransac(model);
ransac.setDistanceThreshold(0.01);
ransac.computeModel();
std::vector<int> inliers;
ransac.getInliers(inliers);
pcl::PointXYZ pointOnLine, lineDirection;
ransac.getModelCoefficients()[0]; // 直线上的一点
ransac.getModelCoefficients()[1]; // 直线的方向向量
pcl::visualization::PCLVisualizer viewer("PLY Viewer");
viewer.setBackgroundColor(0.0, 0.0, 0.0);
viewer.addPointCloud<pcl::PointXYZ>(cloud, "cloud");
viewer.addLine<pcl::PointXYZ>(pointOnLine, lineDirection, "line");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cloud");
viewer.spin();
return 0;
}
"请替换input.ply为你的PLY文件路径,point1和point2为已知的两个点的坐标。这段代码使用了SampleConsensus和RANSAC算法来拟合一条直线,并通过可视化查看结果。"
原文地址: https://www.cveoy.top/t/topic/pun6 著作权归作者所有。请勿转载和采集!