2

我有两组二维点,集合 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,表示第 1 点。

4

1 回答 1

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

鲍勃戴维斯

于 2013-08-29T00:57:52.837 回答