Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

When does the training exactly takes place in FlannBasedMatcher in OpenCV?

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?