查找最近的邻居 - OpenCV
我确实有一组openCV Point2f类型的图像点(坐标)。我想找到那个集合中每个点的最近的四个邻居。 openCV中是否有特定的内置函数来执行此操作,还是应该测量每个点之间的距离并确定最接近的四个?查找最近的邻居 - OpenCV
您可以使用k最近邻分类器CvKNearest
。当您与您的所有点训练分类您可以调用该函数CvKNearest::find_nearest
得到k
最近的邻居。
This教程可能会有所帮助。
它提供的培训为例(据我所知,无论是使用KNearest
构造函数或方法train()
;检查documentation)及识别产品的(利用,如@sietschie提到find_nearest()
方法)。
find_nearest()
接受表示邻居的所需量的int k
值在其分类是基于,第k邻居的标签可被任选地通过参数neighborResponses
返回,如从find_nearest()
文档采取较早地连接:
neighborResponses - 相应的 邻居的可选输出值。
这里,再次作为文档的一部分,neighbors
是:
邻居 - 可选输出指针指向邻近矢量 自己。
我不会和这些参数经验丰富,但提供我的理解正确,邻居提供实际的邻居的值,而neighborResponses提供它们的标签。
以下代码将有助于从一组点中找出所选点的最近邻居。
vector<Point2f> pointsForSearch; //Insert all 2D points to this vector
flann::KDTreeIndexParams indexParams;
flann::Index kdtree(Mat(pointsForSearch).reshape(1), indexParams);
vector<float> query;
query.push_back(pnt.x); //Insert the 2D point we need to find neighbours to the query
query.push_back(pnt.y); //Insert the 2D point we need to find neighbours to the query
vector<int> indices;
vector<float> dists;
kdtree.radiusSearch(query, indices, dists, range, numOfPoints);
索引给出了选定邻居的索引,dists给出了选定邻居的距离。
下面是小例子如何找到3个最接近点(370464):
#include "opencv2/flann/miniflann.hpp"
flann::KDTreeIndexParams indexParams;
flann::Index kdtree(Mat(cloud2d).reshape(1), indexParams);
vector<float> query;
query.push_back(370);
query.push_back(464);
vector<int> indices;
vector<float> dists;
kdtree.knnSearch(query, indices, dists, 3);
// cloud2d[indices[0]] -- is your first point now
// cloud2d[indices[1]] and cloud2d[indices[2]] -- is your 2nd and 3rd point
请注意,函数的行为疯了,如果某些点有NAN坐标,如果按0.0分这可能是这种情况某处之前。
你如何设置cloud2d。我有一个std :: vector的<:point> – raaj 2018-03-02 00:01:23
尝试矢量
在此服务器上未找到请求的URL/2010/10/k-nearest-neighbors-in-opencv /。 – 2015-09-22 08:14:19
Thanks @JürgenK.;该博客似乎已经改版 - 我更新了网址。 – 2015-09-28 18:01:26
我得到一个超时的文档 – 2015-09-28 18:26:16