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

Nig*_*Fox 2 c++ opencv kdtree nearest-neighbor

我有两组2维点,设置A和B.在集合A中,我有100个点,而集合B包含5000个点.对于集合A中的每个点,我想找到一个最近的邻居或从集合B中最接近它的点.我在集合B上构建了一个OpenCV kd-Tree,并使用集合A点作为查询点.

问题是对于集合A中的所有点,Kd树总是返回第一个点作为最近点.通过观察点我可以看到还有其他点比集合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));
}
Run Code Online (Sandbox Code Playgroud)

NN_index始终为0,这意味着第一点.

小智 5

您忘记初始化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);
}
Run Code Online (Sandbox Code Playgroud)

鲍勃戴维斯