以下代码是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树?

最佳答案

当代码调用FlannBasedMatcher::train()时,FlannBasedMatcher的索引将由

flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams );

编码
if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount )

用于检查FlannBasedMatcher的索引是否之前已建立。如果之前已建立索引,train()函数将跳过建立索引的过程以节省时间。

09-12 22:17