为什么OpenCV KdTree总是在c++中返回相同的最近邻

Why OpenCV KdTree always returns same nearest neighbour in c++?

本文关键字:返回 近邻 最近 c++ KdTree OpenCV 为什么      更新时间:2023-10-16

我有两组二维点,集合A &在集合A中,我有100个点,集合B有5000个点。对于集合A中的每个点,我想找到集合B的最近邻居或最接近它的点。我在集合B上构建了一个OpenCV kd-Tree,并使用集合A中的点作为查询点。

问题是对于集合A中的所有点,Kd-tree总是返回第一个点作为最近的点。通过观察点,我可以看到还有其他点比集合b的第一个点更近。

下面是一些代码:
Mat matches; //This mat will contain the index of nearest neighbour as returned by Kd-tree
Mat distances; //In this mat Kd-Tree return the distances for each nearest neighbour
Mat ClusterMemebers; //This Set A
Mat ClusterCenters;  //This set B
const cvflann::SearchParams params(32); //How many leaves to search in a tree
cv::flann::GenericIndex< cvflann::L2<int> > *kdtrees; // The flann searching tree
// Create matrices
ClusterCenters.create(cvSize(2,5000), CV_32S); // The set B
matches.create(cvSize(1,100), CV_32SC1);
distances.create(cvSize(1,100), CV_32FC1);
ClusterMembers.create(cvSize(2,100), CV_32S); // The set A
// After filling points in ClusterMembers (set A) and ClusterCenters (Set B)
// I create K-D tree
kdtrees =  new flann::GenericIndex< cvflann::L2<int> >(ClusterCenters, vflann::KDTreeIndexParams(4)); // a 4 k-d tree
// Search KdTree
kdtrees->knnSearch(ClusterMembers, matches, distances, 1,  cvflann::SearchParams(8));
int NN_index;
for(int l = 0; l < 100; l++)
{
    NN_index = matches.at<float>(cvPoint(l, 0));
    dist = distances.at<float>(cvPoint(l, 0));
}

NN_index始终为0,表示第1点

您忘记初始化ClusterMembers和ClusterCenters了。还有一些其他的错误,所以这里是一个简单测试的工作版本:

Mat matches; //This mat will contain the index of nearest neighbour as returned by Kd-tree
Mat distances; //In this mat Kd-Tree return the distances for each nearest neighbour
Mat ClusterMembers; //This Set A
Mat ClusterCenters;  //This set B
const cvflann::SearchParams params(32); //How many leaves to search in a tree
cv::flann::GenericIndex< cvflann::L2<int> > *kdtrees; // The flann searching tree
// Create matrices
ClusterMembers.create(cvSize(2,100), CV_32S); // The set A
randu(ClusterMembers, Scalar::all(0), Scalar::all(1000));
ClusterCenters.create(cvSize(2,5000), CV_32S); // The set B
randu(ClusterCenters, Scalar::all(0), Scalar::all(1000));
matches.create(cvSize(1,100), CV_32SC1);
distances.create(cvSize(1,100), CV_32FC1);
kdtrees =  new flann::GenericIndex< cvflann::L2<int> >(ClusterCenters, cvflann::KDTreeIndexParams(4)); // a 4 k-d tree
// Search KdTree
kdtrees->knnSearch(ClusterMembers, matches, distances, 1,  cvflann::SearchParams(8));
int NN_index;
float dist;
for(int i = 0; i < 100; i++) {
    NN_index = matches.at<int>(i,0);
    dist = distances.at<float>(i, 0);
}
鲍勃戴维斯