这是官方给的源码,我稍微改动了一些可视化的部分,使我的点云能够使用。
下面我进行了对自己点云的分割试验,调试了参数,但是由于理解不够等原因,结果不是特别理想。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/features/normal_3d.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/passthrough.h>
#include <pcl/segmentation/region_growing.h> //分割
int
main(int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
if (pcl::io::loadPCDFile <pcl::PointXYZ>("C:\\Users\\jinzh\\Desktop\\omygod.pcd", *cloud) == -1)
{
std::cout << "Cloud reading failed." << std::endl;
return (-1);
}
pcl::search::Search<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
pcl::PointCloud <pcl::Normal>::Ptr normals(new pcl::PointCloud <pcl::Normal>);
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;
normal_estimator.setSearchMethod(tree);
normal_estimator.setInputCloud(cloud);
normal_estimator.setKSearch(50);
normal_estimator.compute(*normals);
pcl::IndicesPtr indices(new std::vector <int>);
pcl::PassThrough<pcl::PointXYZ> pass;
pass.setInputCloud(cloud);
pass.setFilterFieldName("z");
pass.setFilterLimits(0.0, 1.0);
pass.filter(*indices);
pcl::RegionGrowing<pcl::PointXYZ, pcl::Normal> reg;
reg.setMinClusterSize(50);
reg.setMaxClusterSize(1000000); //点云集最大点数
reg.setSearchMethod(tree);
reg.setNumberOfNeighbours(30); //参考邻接点个数
reg.setInputCloud(cloud);
//reg.setIndices (indices);
reg.setInputNormals(normals);
reg.setSmoothnessThreshold(3.0/ 180.0 * M_PI); //平滑阈值
reg.setCurvatureThreshold(1.0); //曲率阈值
std::vector <pcl::PointIndices> clusters;
reg.extract(clusters);
std::cout << "点云集的个数为: " << clusters.size() << std::endl;
std::cout << "第一个点云集有 " << clusters[1].indices.size() << " 个点" << endl;
std::cout << "These are the indices of the points of the initial" << std::endl << "cloud that belong to the first cluster:" << std::endl;
int counter = 0;
while (counter < clusters[1].indices.size())
{
std::cout << clusters[1].indices[counter] << ", ";
counter++;
if (counter % 10 == 0)
std::cout << std::endl;
}
std::cout << std::endl;
pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud();
pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("显示窗口")); //窗口显示点云
viewer->addPointCloud(colored_cloud, "*colored_cloud");
viewer->resetCamera(); //相机点重置
viewer->spin();
return (0);
}