平面模型分割
平面模型分割是采用随機采樣一緻性對點雲拟合出一個平面,将點到該平面的距離小于“距離門檻值”的點都作為内點,大于“距離門檻值”的點都作為外點。可以通過設定參數選擇保留内點還是外點。
//****平面模型分割****//
#include <pcl/io/pcd_io.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/visualization/cloud_viewer.h>
int
main(int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_segmented(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
// 填入點雲資料
pcl::io::loadPCDFile("milk_cartoon_all_small_clorox.pcd", *cloud);
pcl::SACSegmentation<pcl::PointXYZ> seg; //建立分割對象
seg.setOptimizeCoefficients(true); //可設定是否優化系數
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setMaxIterations(100);
seg.setDistanceThreshold(0.01);//距離門檻值
seg.setInputCloud(cloud);
seg.segment(*inliers, *coefficients);
//分割提取
pcl::ExtractIndices<pcl::PointXYZ> extract;
extract.setInputCloud(cloud);
extract.setIndices(inliers);
pcl::PointCloud<pcl::PointXYZ>::Ptr temp_in(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointCloud<pcl::PointXYZ>::Ptr temp_out(new pcl::PointCloud<pcl::PointXYZ>());
extract.setNegative(false); //參數為false時輸出為平面點雲,為true時輸出為除平面之外的點雲
extract.filter(*temp_in);
extract.setNegative(true);
extract.filter(*temp_out);
cloud_segmented = temp_in; //切換temp_in與temp_out,選擇平面内或外的點雲
if (inliers->indices.size() == 0)
{
PCL_ERROR("Could not estimate a planar model for the given dataset.");
return (-1);
}
std::cerr << "Model coefficients: " << coefficients->values[0] << " "
<< coefficients->values[1] << " "
<< coefficients->values[2] << " "
<< coefficients->values[3] << std::endl; //列印平面模型的參數(以ax+by+cz+d=0的形式),四個參數分别為a、b、c、d
//可視化
pcl::visualization::PCLVisualizer viewer("PCLVisualizer");
viewer.initCameraParameters();
int v1(0);
viewer.createViewPort(0.0, 0.0, 0.5, 1.0, v1);
viewer.setBackgroundColor(128.0 / 255.0, 138.0 / 255.0, 135.0 / 255.0, v1);
viewer.addText("Cloud before segmenting", 10, 10, "v1 test", v1);
viewer.addPointCloud<pcl::PointXYZ>(cloud, "cloud", v1);
int v2(0);
viewer.createViewPort(0.5, 0.0, 1.0, 1.0, v2);
viewer.setBackgroundColor(128.0 / 255.0, 138.0 / 255.0, 135.0 / 255.0, v2);
viewer.addText("Cloud after segmenting", 10, 10, "v2 test", v2);
viewer.addPointCloud<pcl::PointXYZ>(cloud_segmented, "cloud_segmented", v2);
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud_segmented");
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
boost::this_thread::sleep(boost::posix_time::microseconds(100000));
}
return (0);
}