以下代码使用 C++ 编写,我正在使用 OpenCV 进行实验。假设我以下列方式使用 kd-tree (FlannBasedMatcher):
//these are inputs to the code snippet below.
//They are filled with suitable values
Mat& queryDescriptors;
vector<Training> &trainCollection;
vector< vector<DMatch> >& matches;
int knn;
//setting flann parameters
const Ptr<flann::IndexParams>& indexParams=new flann::KDTreeIndexParams(4);
const Ptr<flann::SearchParams>& searchParams=new flann::SearchParams(64);
FlannBasedMatcher matcher(indexParams, searchParams);
for (int i = 0; i < trainCollection.size();i++){
Training train = trainCollection.at(i);
Mat trainDescriptors(train.trainDescriptors);
trainDescriptorCollection.push_back(trainDescriptors);
}
matcher.add(trainDescriptorCollection);
matcher.train();
//Now, we may do knnMatch (or anyother matching)
matcher.knnMatch(queryDescriptors,matches,knn);
在上面的代码中,训练似乎是在调用 train() 函数时进行的(即构建了 kd-tree)。但是,如果我们查看 train() 函数的内部,这就是问题所在:
void FlannBasedMatcher::train()
{
if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount )
{
mergedDescriptors.set( trainDescCollection );
flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams );
}
}
这两个操作(设置训练描述符和 flann 索引,我在调用 train() 之前已经完成)。那么kd-tree究竟是什么时候建立的呢?