代码如下,其实就是照着教程自己敲进去,不过就这样,也会出不少错,当然只有这样才能进步,各位小伙伴最好别直接复制粘贴,有时间还是敲代码比较好!
#include<pcl\kdtree\kdtree_flann.h>
#include<pcl\point_cloud.h>
#include<pcl\point_types.h> //用来定义点云类型
#include<pcl\io\io.h>
#include<iostream>
#include<ctime>
#include<vector>
using namespace std;
int main()
{
srand(time(NULL));
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);//初始点云对象
cloud->width = 100;
cloud->height = 1;
cloud->resize(cloud->width*cloud->height);
for (int i = 0; i < cloud->width*cloud->height; i++) //随机数填充点云数据
{
cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
cloud->points[i].z = 1024 * rand() / (RAND_MAX + 1.0f);
}
pcl::KdTreeFLANN<pcl::PointXYZ>kdtree; //创建kdtree搜索对象
kdtree.setInputCloud(cloud); //载入点云
pcl::PointXYZ searchPoint; //设置查询点并赋随机值
searchPoint.x = 1024.0f* rand() / (RAND_MAX + 1.0f);
searchPoint.y = 1024.0f* rand() / (RAND_MAX + 1.0f);
searchPoint.z = 1024.0f* rand() / (RAND_MAX + 1.0f);
int K = 10; //搜索最近邻的点数
vector<int>pointIdxNKNSearch(K); //存放最近邻点的索引
vector<float>pointNKNSquaredDistance(K);//对应的距离平方
cout << "K nearest neighbor search at (" << searchPoint.x
<< " " << searchPoint.y
<< " " << searchPoint.z
<< ") with K=" << K << std::endl;
if (kdtree.nearestKSearch(searchPoint, K, pointIdxNKNSearch, pointNKNSquaredDistance)>0)
{
for (int i=0; i < pointIdxNKNSearch.size(); ++i)
{
cout << " " << cloud->points[pointIdxNKNSearch[i]].x
<< " " << cloud->points[pointIdxNKNSearch[i]].y
<< " " << cloud->points[pointIdxNKNSearch[i]].z
<< " (squared distance: " << pointNKNSquaredDistance[i] << ")" << endl;
}
}
// 在半径r内搜索近邻
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
float radius = 256.0f* rand() / (RAND_MAX + 1.0f); //定义搜索半径
std::cout << "Neighbors within radius search at (" << searchPoint.x
<< " " << searchPoint.y
<< " " << searchPoint.z
<< ") with radius=" << radius << std::endl;
if (kdtree.radiusSearch(searchPoint, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance) >0)
{
for (size_t i = 0; i<pointIdxRadiusSearch.size(); ++i)
std::cout << " " << cloud->points[pointIdxRadiusSearch[i]].x
<< " " << cloud->points[pointIdxRadiusSearch[i]].y
<< " " << cloud->points[pointIdxRadiusSearch[i]].z
<< " (squared distance: " << pointRadiusSquaredDistance[i] << ")" << std::endl;
}
system("pause");
return 0;
}
说几点自己在敲代码过程中遇到的问题:生成解决文件失败:
error C2079: “pcl::KdTreeFLANN::param_radius_”使用未定义的 struct“flann::SearchParams”
解决方法:
PCL版本为1.8.1
我的问题出在了包含目录设置上。具体解决方案是在 属性->C++目录->包含目录 中。
一开始包含目录的路径为D:\PCL 1.8.1\3rdParty\FLANN\include\flann
请把它改为:D:\PCL 1.8.1\3rdParty\FLANN\include,如下图所示: