我有两组二维点,分别是A和B。在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,这表示第一个点。

最佳答案

您忘记初始化ClusterMembers和ClusterCenter。还有其他一些错误,因此这是您的简单测试的有效版本:

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

鲍勃·戴维斯

10-08 08:23