Bootstrap

PCL RANSAC拟合直线、平面

PCL RANSAC拟合直线、平面

头文件

#include <pcl/sample_consensus/ransac.h>
#include <pcl/sample_consensus/sac_model_line.h> // 拟合直线
#include <pcl/sample_consensus/sac_model_plane.h> // 拟合平面

代码

拟合直线

//待拟合直线的点云(如果需要拟合XY 2D直线,则cloud中的z值都一样)
pcl::PointCloudpcl::PointXYZ::Ptr cloud(new pcl::PointCloudpcl::PointXYZ);

//ransac相关
pcl::SampleConsensusModelLine<pcl::PointXYZ>::Ptr modelLine(new pcl::SampleConsensusModelLine<pcl::PointXYZ>(cloud));	  // 指定拟合点云与几何模型
pcl::RandomSampleConsensus<pcl::PointXYZ> ransac(modelLine);  // 创建随机采样一致性对象
ransac.setDistanceThreshold(0.01);	// 内点到模型的最大距离
ransac.setMaxIterations(1000);		// 最大迭代次数
ransac.computeModel();				// 执行RANSAC空间直线拟合

//内点相关
std::vector<int> inliers;// 存储内点在cloud中的索引
ransac.getInliers(inliers);	

// 模型参数
//前三个coef[0]、coef[1]、coef[2]表示直线上一点
//后三个coef[3]、coef[4]、coef[5]表示直线的方向向量
Eigen::VectorXf coefficient;
ransac.getModelCoefficients(coefficient);

拟合平面

//待拟合平面的点云
pcl::PointCloudpcl::PointXYZ::Ptr cloud(new pcl::PointCloudpcl::PointXYZ);

//ransac相关
pcl::SampleConsensusModelPlane<pcl::PointXYZ>::Ptr model_plane(new pcl::SampleConsensusModelPlane<pcl::PointXYZ>(cloud)); // 指定拟合点云与几何模型
pcl::RandomSampleConsensus<pcl::PointXYZ> ransac(model_plane);// 创建随机采样一致性对象
ransac.setDistanceThreshold(0.01);	// 内点到模型的最大距离
ransac.computeModel();				// 执行RANSAC空间平面拟合

//内点相关
vector<int> inliers;// 存储内点在cloud中的索引
ransac.getInliers(inliers);	

// 模型参数 coefficient[0]*x+coefficient[1]*y+coefficient[2]*z+coefficient[3]=0
Eigen::VectorXf coefficient;
ransac.getModelCoefficients(coefficient);
;