问题
The following code is in C++ and I am using OpenCV for my experiment. Suppose I am using kd-tree (FlannBasedMatcher) in the following way:
//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);
In the above code it seems that training takes place (i.e. kd-tree is built) on calling the train() function. But here is the catch, if we look inside the train() function:
void FlannBasedMatcher::train()
{
if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount )
{
mergedDescriptors.set( trainDescCollection );
flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams );
}
}
Both of these operations (setting training descriptors and flann index, I have already done before calling train()). So when exactly is the kd-tree built?
回答1:
When the code calls FlannBasedMatcher::train(),the index of FlannBasedMatcher will be built by
flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams );
The code
if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount )
is to check whether the index of FlannBasedMatcher has already been built before.If index has been built before,the train() function will skip the process of building index to save time.
回答2:
From the documentation, the training (i.e., in your cae builidng the kd-tree) is done every time before matching.
The cv::DescriptorMatcher
class calls the training method automaticall when needed.
来源:https://stackoverflow.com/questions/15047259/at-what-stage-the-training-exactly-takes-place-in-flannbasedmatcher-in-opencv