查找最近的邻居-OpenCV

Find Closest Neighbors - OpenCV

本文关键字:-OpenCV 邻居 最近 查找      更新时间:2023-10-16

我确实有一组openCV Point2f类型的图像点(坐标)。我想找到该集合中每个点的4个最近邻居。openCV中是否有任何特定的内置函数可以做到这一点,或者我应该测量每个点之间的距离并决定四个最接近的点吗?

以下代码将有助于从一组点中找到所选点的最近邻居。

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);

index给出了所选邻居的索引,dists给出了所选择邻居的距离。

本教程可能会有所帮助。

它提供了一个训练(据我所知,使用KNearest构造函数或train()方法;查看文档)和识别项目(如@sietschie提到的find_nearest()方法)的例子。

find_nearest()取一个int k值,表示分类所需的邻居数量,k个邻居的标签可以通过参数neighborResponses选择性返回,如前面链接的find_nearest()文档所示:

neighborResponses–相应的可选输出值邻居。

其中,作为文档的一部分,neighbors是:

邻居–指向邻居矢量的可选输出指针他们自己

我对这些参数没有经验,但如果我理解正确,邻居提供实际邻居的值,而相邻响应则提供它们的标签。

以下是如何找到与(370464)最接近的3个点的小示例:

#include "opencv2/flann/miniflann.hpp"
vector<Point2f> cloud2d;
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,可能会出现这种情况。

您可以使用k近邻分类器CvKNearest。在用所有的点训练分类器之后,可以通过调用函数CvKNearest::find_nearest来获得k的最近邻居。