2012-03-22 174 views
5

我確實有一組openCV Point2f類型的圖像點(座標)。我想找到那個集合中每個點的最近的四個鄰居。 openCV中是否有特定的內置函數來執行此操作,還是應該測量每個點之間的距離並確定最接近的四個?查找最近的鄰居 - OpenCV

回答

1

您可以使用k最近鄰分類器CvKNearest。當您與您的所有點訓練分類您可以調用該函數CvKNearest::find_nearest得到k最近的鄰居。

2

This教程可能會有所幫助。

它提供的培訓爲例(據我所知,無論是使用KNearest構造函數或方法train();檢查documentation)及識別產品的(利用,如@sietschie提到find_nearest()方法)。

find_nearest()接受表示鄰居的所需量的int k值在其分類是基於,第k鄰居的標籤可被任選地通過參數neighborResponses返回,如從find_nearest()文檔採取較早地連接:

neighborResponses - 相應的 鄰居的可選輸出值。

這裏,再次作爲文檔的一部分,neighbors是:

鄰居 - 可選輸出指針指向鄰近矢量 自己。

我不會和這些參數經驗豐富,但提供我的理解正確,鄰居提供實際的鄰居的值,而neighborResponses提供它們的標籤。

+1

在此服務器上未找到請求的URL/2010/10/k-nearest-neighbors-in-opencv /。 – 2015-09-22 08:14:19

+1

Thanks @JürgenK.;該博客似乎已經改版 - 我更新了網址。 – 2015-09-28 18:01:26

+0

我得到一個超時的文檔 – 2015-09-28 18:26:16

8

以下代碼將有助於從一組點中找出所選點的最近鄰居。

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給出了選定鄰居的距離。

1

下面是小例子如何找到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分這可能是這種情況某處之前。

+0

你如何設置cloud2d。我有一個std :: vector的 raaj 2018-03-02 00:01:23

+0

嘗試矢量 2018-03-02 08:54:37