matchers.cpp 44.8 KB
Newer Older
Maria Dimashova's avatar
Maria Dimashova committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

#ifdef HAVE_EIGEN2
#include <Eigen/Array>
#endif

using namespace std;

namespace cv
{

Mat windowedMatchingMask( const vector<KeyPoint>& keypoints1, const vector<KeyPoint>& keypoints2,
                          float maxDeltaX, float maxDeltaY )
{
    if( keypoints1.empty() || keypoints2.empty() )
        return Mat();

    Mat mask( keypoints1.size(), keypoints2.size(), CV_8UC1 );
    for( size_t i = 0; i < keypoints1.size(); i++ )
    {
        for( size_t j = 0; j < keypoints2.size(); j++ )
        {
            Point2f diff = keypoints2[j].pt - keypoints1[i].pt;
            mask.at<uchar>(i, j) = std::abs(diff.x) < maxDeltaX && std::abs(diff.y) < maxDeltaY;
        }
    }
    return mask;
}

/****************************************************************************************\
*                                      DescriptorMatcher                                 *
\****************************************************************************************/
74 75 76 77 78 79 80 81 82 83 84 85 86
DescriptorMatcher::DescriptorCollection::DescriptorCollection()
{}

DescriptorMatcher::DescriptorCollection::DescriptorCollection( const DescriptorCollection& collection )
{
    mergedDescriptors = collection.mergedDescriptors.clone();
    copy( collection.startIdxs.begin(), collection.startIdxs.begin(), startIdxs.begin() );
}

DescriptorMatcher::DescriptorCollection::~DescriptorCollection()
{}

void DescriptorMatcher::DescriptorCollection::set( const vector<Mat>& descriptors )
Maria Dimashova's avatar
Maria Dimashova committed
87
{
88 89
    clear();

90
    size_t imageCount = descriptors.size();
91 92 93 94 95 96 97 98
    CV_Assert( imageCount > 0 );

    startIdxs.resize( imageCount );

    int dim = -1;
    int type = -1;
    startIdxs[0] = 0;
    for( size_t i = 1; i < imageCount; i++ )
Maria Dimashova's avatar
Maria Dimashova committed
99
    {
100
        int s = 0;
101
        if( !descriptors[i-1].empty() )
102
        {
103 104 105
            dim = descriptors[i-1].cols;
            type = descriptors[i-1].type();
            s = descriptors[i-1].rows;
106 107
        }
        startIdxs[i] = startIdxs[i-1] + s;
Maria Dimashova's avatar
Maria Dimashova committed
108
    }
109
    if( imageCount == 1 )
Maria Dimashova's avatar
Maria Dimashova committed
110
    {
111
        if( descriptors[0].empty() ) return;
112

113 114
        dim = descriptors[0].cols;
        type = descriptors[0].type();
115 116 117
    }
    assert( dim > 0 );

118
    int count = startIdxs[imageCount-1] + descriptors[imageCount-1].rows;
119 120 121

    if( count > 0 )
    {
122
        mergedDescriptors.create( count, dim, type );
123 124
        for( size_t i = 0; i < imageCount; i++ )
        {
125
            if( !descriptors[i].empty() )
126
            {
127 128 129
                CV_Assert( descriptors[i].cols == dim && descriptors[i].type() == type );
                Mat m = mergedDescriptors.rowRange( startIdxs[i], startIdxs[i] + descriptors[i].rows );
                descriptors[i].copyTo(m);
130 131
            }
        }
Maria Dimashova's avatar
Maria Dimashova committed
132 133 134
    }
}

135
void DescriptorMatcher::DescriptorCollection::clear()
Maria Dimashova's avatar
Maria Dimashova committed
136
{
137
    startIdxs.clear();
138
    mergedDescriptors.release();
Maria Dimashova's avatar
Maria Dimashova committed
139 140
}

141
const Mat DescriptorMatcher::DescriptorCollection::getDescriptor( int imgIdx, int localDescIdx ) const
Maria Dimashova's avatar
Maria Dimashova committed
142
{
143 144 145 146 147
    CV_Assert( imgIdx < (int)startIdxs.size() );
    int globalIdx = startIdxs[imgIdx] + localDescIdx;
    CV_Assert( globalIdx < (int)size() );

    return getDescriptor( globalIdx );
Maria Dimashova's avatar
Maria Dimashova committed
148 149
}

150 151 152 153 154
const Mat& DescriptorMatcher::DescriptorCollection::getDescriptors() const
{
    return mergedDescriptors;
}

155
const Mat DescriptorMatcher::DescriptorCollection::getDescriptor( int globalDescIdx ) const
Maria Dimashova's avatar
Maria Dimashova committed
156
{
157
    CV_Assert( globalDescIdx < size() );
158
    return mergedDescriptors.row( globalDescIdx );
Maria Dimashova's avatar
Maria Dimashova committed
159 160
}

161
void DescriptorMatcher::DescriptorCollection::getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const
Maria Dimashova's avatar
Maria Dimashova committed
162
{
163 164 165 166 167 168 169 170 171 172 173 174 175 176
    imgIdx = -1;
    CV_Assert( globalDescIdx < size() );
    for( size_t i = 1; i < startIdxs.size(); i++ )
    {
        if( globalDescIdx < startIdxs[i] )
        {
            imgIdx = i - 1;
            break;
        }
    }
    imgIdx = imgIdx == -1 ? startIdxs.size() -1 : imgIdx;
    localDescIdx = globalDescIdx - startIdxs[imgIdx];
}

177 178 179 180 181
int DescriptorMatcher::DescriptorCollection::size() const
{
    return mergedDescriptors.rows;
}

182 183 184 185 186 187 188 189 190 191 192 193 194
/*
 * DescriptorMatcher
 */
void convertMatches( const vector<vector<DMatch> >& knnMatches, vector<DMatch>& matches )
{
    matches.clear();
    matches.reserve( knnMatches.size() );
    for( size_t i = 0; i < knnMatches.size(); i++ )
    {
        CV_Assert( knnMatches[i].size() <= 1 );
        if( !knnMatches[i].empty() )
            matches.push_back( knnMatches[i][0] );
    }
Maria Dimashova's avatar
Maria Dimashova committed
195 196
}

197 198 199 200 201 202 203 204 205
DescriptorMatcher::~DescriptorMatcher()
{}

void DescriptorMatcher::add( const vector<Mat>& descriptors )
{
    trainDescCollection.insert( trainDescCollection.end(), descriptors.begin(), descriptors.end() );
}

const vector<Mat>& DescriptorMatcher::getTrainDescriptors() const
Maria Dimashova's avatar
Maria Dimashova committed
206
{
207
    return trainDescCollection;
Maria Dimashova's avatar
Maria Dimashova committed
208 209
}

210
void DescriptorMatcher::clear()
Maria Dimashova's avatar
Maria Dimashova committed
211
{
212
    trainDescCollection.clear();
Maria Dimashova's avatar
Maria Dimashova committed
213 214
}

215 216 217 218 219 220 221 222 223
bool DescriptorMatcher::empty() const
{
	return trainDescCollection.size() == 0;
}

void DescriptorMatcher::train()
{}

void DescriptorMatcher::match( const Mat& queryDescriptors, const Mat& trainDescriptors, vector<DMatch>& matches, const Mat& mask ) const
Maria Dimashova's avatar
Maria Dimashova committed
224
{
225 226 227
    Ptr<DescriptorMatcher> tempMatcher = clone(true);
    tempMatcher->add( vector<Mat>(1, trainDescriptors) );
    tempMatcher->match( queryDescriptors, matches, vector<Mat>(1, mask) );
Maria Dimashova's avatar
Maria Dimashova committed
228 229
}

230
void DescriptorMatcher::knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, vector<vector<DMatch> >& matches, int knn,
231
                                  const Mat& mask, bool compactResult ) const
Maria Dimashova's avatar
Maria Dimashova committed
232
{
233 234 235
    Ptr<DescriptorMatcher> tempMatcher = clone(true);
    tempMatcher->add( vector<Mat>(1, trainDescriptors) );
    tempMatcher->knnMatch( queryDescriptors, matches, knn, vector<Mat>(1, mask), compactResult );
236 237
}

238
void DescriptorMatcher::radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, vector<vector<DMatch> >& matches, float maxDistance,
239 240
                                     const Mat& mask, bool compactResult ) const
{
241 242 243
    Ptr<DescriptorMatcher> tempMatcher = clone(true);
    tempMatcher->add( vector<Mat>(1, trainDescriptors) );
    tempMatcher->radiusMatch( queryDescriptors, matches, maxDistance, vector<Mat>(1, mask), compactResult );
244 245
}

246
void DescriptorMatcher::match( const Mat& queryDescriptors, vector<DMatch>& matches, const vector<Mat>& masks )
247 248
{
    vector<vector<DMatch> > knnMatches;
249
    knnMatch( queryDescriptors, knnMatches, 1, masks, true /*compactResult*/ );
250 251 252
    convertMatches( knnMatches, matches );
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
void DescriptorMatcher::checkMasks( const vector<Mat>& masks, int queryDescriptorsCount ) const
{
	if( isMaskSupported() && !masks.empty() )
	{
		// Check masks
		size_t imageCount = trainDescCollection.size();
		CV_Assert( masks.size() == imageCount );
		for( size_t i = 0; i < imageCount; i++ )
		{
			if( !masks[i].empty() && !trainDescCollection[i].empty() )
			{
				CV_Assert( masks[i].rows == queryDescriptorsCount && 
					       masks[i].cols == trainDescCollection[i].rows &&
						   masks[i].type() == CV_8UC1 );
			}
		}
	}
}

void DescriptorMatcher::knnMatch( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, int knn,
273 274
                                  const vector<Mat>& masks, bool compactResult )
{
275 276 277 278 279 280 281 282
	matches.empty();
	if( empty() || queryDescriptors.empty() )
		return;

	CV_Assert( knn > 0 );
	
	checkMasks( masks, queryDescriptors.rows );

283
    train();
284
    knnMatchImpl( queryDescriptors, matches, knn, masks, compactResult );
285 286
}

287
void DescriptorMatcher::radiusMatch( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, float maxDistance,
288 289
                                     const vector<Mat>& masks, bool compactResult )
{
290 291 292 293 294 295 296 297
	matches.empty();
	if( empty() || queryDescriptors.empty() )
		return;

	CV_Assert( maxDistance > std::numeric_limits<float>::epsilon() );
	
	checkMasks( masks, queryDescriptors.rows );

298
    train();
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    radiusMatchImpl( queryDescriptors, matches, maxDistance, masks, compactResult );
}

void DescriptorMatcher::read( const FileNode& )
{}

void DescriptorMatcher::write( FileStorage& ) const
{}

bool DescriptorMatcher::isPossibleMatch( const Mat& mask, int queryIdx, int trainIdx )
{
    return mask.empty() || mask.at<uchar>(queryIdx, trainIdx);
}

bool DescriptorMatcher::isMaskedOut( const vector<Mat>& masks, int queryIdx )
{
    size_t outCount = 0;
    for( size_t i = 0; i < masks.size(); i++ )
    {
        if( !masks[i].empty() && (countNonZero(masks[i].row(queryIdx)) == 0) )
            outCount++;
    }

    return !masks.empty() && outCount == masks.size() ;
Maria Dimashova's avatar
Maria Dimashova committed
323 324
}

325

Maria Dimashova's avatar
Maria Dimashova committed
326
template<>
327 328
void BruteForceMatcher<L2<float> >::knnMatchImpl( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, int knn,
                                              const vector<Mat>& masks, bool compactResult )
Maria Dimashova's avatar
Maria Dimashova committed
329
{
330
#ifndef HAVE_EIGEN2
331
    commonKnnMatchImpl( *this, queryDescriptors, matches, knn, masks, compactResult );
332
#else
333
    CV_Assert( queryDescriptors.type() == CV_32FC1 ||  queryDescriptors.empty() );
334
    CV_Assert( masks.empty() || masks.size() == trainDescCollection.size() );
Maria Dimashova's avatar
Maria Dimashova committed
335

336
    matches.reserve(queryDescriptors.rows);
337 338 339 340 341
    size_t imgCount = trainDescCollection.size();

    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> e_query_t;
    vector<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> > e_trainCollection(trainDescCollection.size());
    vector<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> > e_trainNorms2(trainDescCollection.size());
342
    cv2eigen( queryDescriptors.t(), e_query_t);
343 344 345 346 347 348 349 350
    for( size_t i = 0; i < trainDescCollection.size(); i++ )
    {
        cv2eigen( trainDescCollection[i], e_trainCollection[i] );
        e_trainNorms2[i] = e_trainCollection[i].rowwise().squaredNorm() / 2;
    }

    vector<Eigen::Matrix<float, Eigen::Dynamic, 1> > e_allDists( imgCount ); // distances between one query descriptor and all train descriptors

351
    for( int qIdx = 0; qIdx < queryDescriptors.rows; qIdx++ )
352
    {
353
        if( isMaskedOut( masks, qIdx ) )
Maria Dimashova's avatar
Maria Dimashova committed
354
        {
355 356
            if( !compactResult ) // push empty vector
                matches.push_back( vector<DMatch>() );
Maria Dimashova's avatar
Maria Dimashova committed
357 358 359
        }
        else
        {
360 361 362 363 364
            float queryNorm2 = e_query_t.col(qIdx).squaredNorm();
            // 1. compute distances between i-th query descriptor and all train descriptors
            for( size_t iIdx = 0; iIdx < imgCount; iIdx++ )
            {
                CV_Assert( masks.empty() || masks[iIdx].empty() ||
365
                           ( masks[iIdx].rows == queryDescriptors.rows && masks[iIdx].cols == trainDescCollection[iIdx].rows &&
366 367
                             masks[iIdx].type() == CV_8UC1 ) );
                CV_Assert( trainDescCollection[iIdx].type() == CV_32FC1 ||  trainDescCollection[iIdx].empty() );
368
                CV_Assert( queryDescriptors.cols == trainDescCollection[iIdx].cols );
Maria Dimashova's avatar
Maria Dimashova committed
369

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
                e_allDists[iIdx] = e_trainCollection[iIdx] *e_query_t.col(qIdx);
                e_allDists[iIdx] -= e_trainNorms2[iIdx];

                if( !masks.empty() && !masks[iIdx].empty() )
                {
                    const uchar* maskPtr = (uchar*)masks[iIdx].ptr(qIdx);
                    for( int c = 0; c < masks[iIdx].cols; c++ )
                    {
                        if( maskPtr[c] == 0 )
                            e_allDists[iIdx](c) = std::numeric_limits<float>::min();
                    }
                }
            }

            // 2. choose knn nearest matches for query[i]
            matches.push_back( vector<DMatch>() );
            vector<vector<DMatch> >::reverse_iterator curMatches = matches.rbegin();
            for( int k = 0; k < knn; k++ )
            {
                float totalMaxCoeff = std::numeric_limits<float>::min();
                int bestTrainIdx = -1, bestImgIdx = -1;
                for( size_t iIdx = 0; iIdx < imgCount; iIdx++ )
                {
                    int loc;
                    float curMaxCoeff = e_allDists[iIdx].maxCoeff( &loc );
                    if( curMaxCoeff > totalMaxCoeff )
                    {
                        totalMaxCoeff = curMaxCoeff;
                        bestTrainIdx = loc;
                        bestImgIdx = iIdx;
                    }
                }
                if( bestTrainIdx == -1 )
                    break;

                e_allDists[bestImgIdx](bestTrainIdx) = std::numeric_limits<float>::min();
                curMatches->push_back( DMatch(qIdx, bestTrainIdx, bestImgIdx, sqrt((-2)*totalMaxCoeff + queryNorm2)) );
            }
            std::sort( curMatches->begin(), curMatches->end() );
Maria Dimashova's avatar
Maria Dimashova committed
409 410
        }
    }
411 412
#endif
}
Maria Dimashova's avatar
Maria Dimashova committed
413

414
template<>
415
void BruteForceMatcher<L2<float> >::radiusMatchImpl( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, float maxDistance,
416 417 418
                                                     const vector<Mat>& masks, bool compactResult )
{
#ifndef HAVE_EIGEN2
419
    commonRadiusMatchImpl( *this, queryDescriptors, matches, maxDistance, masks, compactResult );
Maria Dimashova's avatar
Maria Dimashova committed
420
#else
421
    CV_Assert( queryDescriptors.type() == CV_32FC1 ||  queryDescriptors.empty() );
422
    CV_Assert( masks.empty() || masks.size() == trainDescCollection.size() );
Maria Dimashova's avatar
Maria Dimashova committed
423

424
    matches.reserve(queryDescriptors.rows);
425
    size_t imgCount = trainDescCollection.size();
Maria Dimashova's avatar
Maria Dimashova committed
426

427 428 429
    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> e_query_t;
    vector<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> > e_trainCollection(trainDescCollection.size());
    vector<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> > e_trainNorms2(trainDescCollection.size());
430
    cv2eigen( queryDescriptors.t(), e_query_t);
431
    for( size_t i = 0; i < trainDescCollection.size(); i++ )
Maria Dimashova's avatar
Maria Dimashova committed
432
    {
433 434
        cv2eigen( trainDescCollection[i], e_trainCollection[i] );
        e_trainNorms2[i] = e_trainCollection[i].rowwise().squaredNorm() / 2;
Maria Dimashova's avatar
Maria Dimashova committed
435
    }
436 437 438

    vector<Eigen::Matrix<float, Eigen::Dynamic, 1> > e_allDists( imgCount ); // distances between one query descriptor and all train descriptors

439
    for( int qIdx = 0; qIdx < queryDescriptors.rows; qIdx++ )
Maria Dimashova's avatar
Maria Dimashova committed
440
    {
441
        if( isMaskedOut( masks, qIdx ) )
Maria Dimashova's avatar
Maria Dimashova committed
442
        {
443 444 445 446 447 448 449 450 451 452
            if( !compactResult ) // push empty vector
                matches.push_back( vector<DMatch>() );
        }
        else
        {
            float queryNorm2 = e_query_t.col(qIdx).squaredNorm();
            // 1. compute distances between i-th query descriptor and all train descriptors
            for( size_t iIdx = 0; iIdx < imgCount; iIdx++ )
            {
                CV_Assert( masks.empty() || masks[iIdx].empty() ||
453
                           ( masks[iIdx].rows == queryDescriptors.rows && masks[iIdx].cols == trainDescCollection[iIdx].rows &&
454 455
                             masks[iIdx].type() == CV_8UC1 ) );
                CV_Assert( trainDescCollection[iIdx].type() == CV_32FC1 ||  trainDescCollection[iIdx].empty() );
456
                CV_Assert( queryDescriptors.cols == trainDescCollection[iIdx].cols );
457 458 459 460

                e_allDists[iIdx] = e_trainCollection[iIdx] *e_query_t.col(qIdx);
                e_allDists[iIdx] -= e_trainNorms2[iIdx];
            }
Maria Dimashova's avatar
Maria Dimashova committed
461

462 463 464
            matches.push_back( vector<DMatch>() );
            vector<vector<DMatch> >::reverse_iterator curMatches = matches.rbegin();
            for( size_t iIdx = 0; iIdx < imgCount; iIdx++ )
Maria Dimashova's avatar
Maria Dimashova committed
465
            {
466 467
                assert( e_allDists[iIdx].rows() == trainDescCollection[iIdx].rows );
                for( int tIdx = 0; tIdx < e_allDists[iIdx].rows(); tIdx++ )
Maria Dimashova's avatar
Maria Dimashova committed
468
                {
469
                    if( masks.empty() || isPossibleMatch(masks[iIdx], qIdx, tIdx) )
470 471 472 473 474
                    {
                        float d =  sqrt((-2)*e_allDists[iIdx](tIdx) + queryNorm2);
                        if( d < maxDistance )
                            curMatches->push_back( DMatch( qIdx, tIdx, iIdx, d ) );
                    }
Maria Dimashova's avatar
Maria Dimashova committed
475 476
                }
            }
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            std::sort( curMatches->begin(), curMatches->end() );
        }
    }
#endif
}

/*
 * Flann based matcher
 */
FlannBasedMatcher::FlannBasedMatcher( const Ptr<flann::IndexParams>& _indexParams, const Ptr<flann::SearchParams>& _searchParams )
    : indexParams(_indexParams), searchParams(_searchParams), addedDescCount(0)
{
    CV_Assert( !_indexParams.empty() );
    CV_Assert( !_searchParams.empty() );
}

493
void FlannBasedMatcher::add( const vector<Mat>& descriptors )
494
{
495 496
    DescriptorMatcher::add( descriptors );
    for( size_t i = 0; i < descriptors.size(); i++ )
497
    {
498
        addedDescCount += descriptors[i].rows;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    }
}

void FlannBasedMatcher::clear()
{
    DescriptorMatcher::clear();

    mergedDescriptors.clear();
    flannIndex.release();

    addedDescCount = 0;
}

void FlannBasedMatcher::train()
{
    if( flannIndex.empty() || mergedDescriptors.size() < addedDescCount )
    {
        mergedDescriptors.set( trainDescCollection );
        flannIndex = new flann::Index( mergedDescriptors.getDescriptors(), *indexParams );
    }
}
Maria Dimashova's avatar
Maria Dimashova committed
520

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
bool FlannBasedMatcher::isMaskSupported() const
{
    return false;
}

Ptr<DescriptorMatcher> FlannBasedMatcher::clone( bool emptyTrainData ) const
{
    FlannBasedMatcher* matcher = new FlannBasedMatcher(indexParams, searchParams);
    if( !emptyTrainData )
    {
        CV_Error( CV_StsNotImplemented, "deep clone functionality is not implemented, because "
                  "Flann::Index has not copy constructor or clone method ");
        //matcher->flannIndex;
        matcher->addedDescCount = addedDescCount;
        matcher->mergedDescriptors = DescriptorCollection( mergedDescriptors );
        transform( trainDescCollection.begin(), trainDescCollection.end(),
                   matcher->trainDescCollection.begin(), clone_op );
    }
    return matcher;
}

542 543 544 545 546 547 548 549 550 551
void FlannBasedMatcher::convertToDMatches( const DescriptorCollection& collection, const Mat& indices, const Mat& dists,
                                           vector<vector<DMatch> >& matches )
{
    matches.resize( indices.rows );
    for( int i = 0; i < indices.rows; i++ )
    {
        for( int j = 0; j < indices.cols; j++ )
        {
            int idx = indices.at<int>(i, j);
            if( idx >= 0 )
Maria Dimashova's avatar
Maria Dimashova committed
552
            {
553 554 555
                int imgIdx, trainIdx;
                collection.getLocalIdx( idx, imgIdx, trainIdx );
                matches[i].push_back( DMatch( i, trainIdx, imgIdx, std::sqrt(dists.at<float>(i,j))) );
Maria Dimashova's avatar
Maria Dimashova committed
556 557 558 559 560
            }
        }
    }
}

561
void FlannBasedMatcher::knnMatchImpl( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, int knn,
562 563
                                      const vector<Mat>& /*masks*/, bool /*compactResult*/ )
{
564 565 566
    Mat indices( queryDescriptors.rows, knn, CV_32SC1 );
    Mat dists( queryDescriptors.rows, knn, CV_32FC1);
    flannIndex->knnSearch( queryDescriptors, indices, dists, knn, *searchParams );
567 568 569 570

    convertToDMatches( mergedDescriptors, indices, dists, matches );
}

571
void FlannBasedMatcher::radiusMatchImpl( const Mat& queryDescriptors, vector<vector<DMatch> >& matches, float maxDistance,
572 573 574
                                         const vector<Mat>& /*masks*/, bool /*compactResult*/ )
{
    const int count = mergedDescriptors.size(); // TODO do count as param?
575 576 577
    Mat indices( queryDescriptors.rows, count, CV_32SC1, Scalar::all(-1) );
    Mat dists( queryDescriptors.rows, count, CV_32FC1, Scalar::all(-1) );
    for( int qIdx = 0; qIdx < queryDescriptors.rows; qIdx++ )
578
    {
579
        Mat queryDescriptorsRow = queryDescriptors.row(qIdx);
580 581
        Mat indicesRow = indices.row(qIdx);
        Mat distsRow = dists.row(qIdx);
582
        flannIndex->radiusSearch( queryDescriptorsRow, indicesRow, distsRow, maxDistance*maxDistance, *searchParams );
583 584 585 586 587 588 589 590
    }

    convertToDMatches( mergedDescriptors, indices, dists, matches );
}

/*
 * Factory function for DescriptorMatcher creating
 */
Maria Dimashova's avatar
Maria Dimashova committed
591 592 593
Ptr<DescriptorMatcher> createDescriptorMatcher( const string& descriptorMatcherType )
{
    DescriptorMatcher* dm = 0;
594 595 596 597 598
    if( !descriptorMatcherType.compare( "FlannBased" ) )
    {
        dm = new FlannBasedMatcher();
    }
    else if( !descriptorMatcherType.compare( "BruteForce" ) ) // L2
Maria Dimashova's avatar
Maria Dimashova committed
599 600 601 602 603 604 605
    {
        dm = new BruteForceMatcher<L2<float> >();
    }
    else if( !descriptorMatcherType.compare( "BruteForce-L1" ) )
    {
        dm = new BruteForceMatcher<L1<float> >();
    }
606
    else if( !descriptorMatcherType.compare("BruteForce-Hamming") )
607
    {
608
        dm = new BruteForceMatcher<Hamming>();
609
    }
610
    else if( !descriptorMatcherType.compare( "BruteForce-HammingLUT") )
611
    {
612
        dm = new BruteForceMatcher<HammingLUT>();
613
    }
Maria Dimashova's avatar
Maria Dimashova committed
614 615 616 617 618

    return dm;
}

/****************************************************************************************\
619
*                                GenericDescriptorMatcher                                *
Maria Dimashova's avatar
Maria Dimashova committed
620 621 622 623
\****************************************************************************************/
/*
 * KeyPointCollection
 */
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
GenericDescriptorMatcher::KeyPointCollection::KeyPointCollection() : pointCount(0)
{}

GenericDescriptorMatcher::KeyPointCollection::KeyPointCollection( const KeyPointCollection& collection )
{
    pointCount = collection.pointCount;

    transform( collection.images.begin(), collection.images.end(), images.begin(), clone_op );

    keypoints.resize( collection.keypoints.size() );
    for( size_t i = 0; i < keypoints.size(); i++ )
        copy( collection.keypoints[i].begin(), collection.keypoints[i].end(), keypoints[i].begin() );

    copy( collection.startIndices.begin(), collection.startIndices.end(), startIndices.begin() );
}

640 641
void GenericDescriptorMatcher::KeyPointCollection::add( const vector<Mat>& _images,
                                                        const vector<vector<KeyPoint> >& _points )
Maria Dimashova's avatar
Maria Dimashova committed
642
{
643 644 645 646
    CV_Assert( !_images.empty() );
    CV_Assert( _images.size() == _points.size() );

    images.insert( images.end(), _images.begin(), _images.end() );
647
    keypoints.insert( keypoints.end(), _points.begin(), _points.end() );
648
    for( size_t i = 0; i < _points.size(); i++ )
649
        pointCount += _points[i].size();
650 651 652 653 654 655

    size_t prevSize = startIndices.size(), addSize = _images.size();
    startIndices.resize( prevSize + addSize );

    if( prevSize == 0 )
        startIndices[prevSize] = 0; //first
Maria Dimashova's avatar
Maria Dimashova committed
656
    else
657
        startIndices[prevSize] = startIndices[prevSize-1] + keypoints[prevSize-1].size();
Maria Dimashova's avatar
Maria Dimashova committed
658

659 660
    for( size_t i = prevSize + 1; i < prevSize + addSize; i++ )
    {
661
        startIndices[i] = startIndices[i - 1] + keypoints[i - 1].size();
662
    }
Maria Dimashova's avatar
Maria Dimashova committed
663 664
}

665
void GenericDescriptorMatcher::KeyPointCollection::clear()
Maria Dimashova's avatar
Maria Dimashova committed
666
{
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    keypoints.clear();
}

size_t GenericDescriptorMatcher::KeyPointCollection::keypointCount() const
{
    return pointCount;
}

size_t GenericDescriptorMatcher::KeyPointCollection::imageCount() const
{
    return images.size();
}

const vector<vector<KeyPoint> >& GenericDescriptorMatcher::KeyPointCollection::getKeypoints() const
{
    return keypoints;
}

const vector<KeyPoint>& GenericDescriptorMatcher::KeyPointCollection::getKeypoints( int imgIdx ) const
{
    CV_Assert( imgIdx < (int)imageCount() );
    return keypoints[imgIdx];
689
}
Maria Dimashova's avatar
Maria Dimashova committed
690

691 692 693
const KeyPoint& GenericDescriptorMatcher::KeyPointCollection::getKeyPoint( int imgIdx, int localPointIdx ) const
{
    CV_Assert( imgIdx < (int)images.size() );
694 695
    CV_Assert( localPointIdx < (int)keypoints[imgIdx].size() );
    return keypoints[imgIdx][localPointIdx];
Maria Dimashova's avatar
Maria Dimashova committed
696 697
}

698
const KeyPoint& GenericDescriptorMatcher::KeyPointCollection::getKeyPoint( int globalPointIdx ) const
Maria Dimashova's avatar
Maria Dimashova committed
699
{
700 701
    int imgIdx, localPointIdx;
    getLocalIdx( globalPointIdx, imgIdx, localPointIdx );
702
    return keypoints[imgIdx][localPointIdx];
Maria Dimashova's avatar
Maria Dimashova committed
703 704
}

705
void GenericDescriptorMatcher::KeyPointCollection::getLocalIdx( int globalPointIdx, int& imgIdx, int& localPointIdx ) const
Maria Dimashova's avatar
Maria Dimashova committed
706
{
707
    imgIdx = -1;
708
    CV_Assert( globalPointIdx < (int)keypointCount() );
709 710 711 712 713 714 715 716 717 718
    for( size_t i = 1; i < startIndices.size(); i++ )
    {
        if( globalPointIdx < startIndices[i] )
        {
            imgIdx = i - 1;
            break;
        }
    }
    imgIdx = imgIdx == -1 ? startIndices.size() -1 : imgIdx;
    localPointIdx = globalPointIdx - startIndices[imgIdx];
Maria Dimashova's avatar
Maria Dimashova committed
719 720
}

721 722 723 724 725 726 727 728 729 730 731
const vector<Mat>& GenericDescriptorMatcher::KeyPointCollection::getImages() const
{
    return images;
}

const Mat& GenericDescriptorMatcher::KeyPointCollection::getImage( int imgIdx ) const
{
    CV_Assert( imgIdx < (int)imageCount() );
    return images[imgIdx];
}

Maria Dimashova's avatar
Maria Dimashova committed
732
/*
733
 * GenericDescriptorMatcher
Maria Dimashova's avatar
Maria Dimashova committed
734
 */
735 736 737 738 739 740
GenericDescriptorMatcher::GenericDescriptorMatcher()
{}

GenericDescriptorMatcher::~GenericDescriptorMatcher()
{}

741 742
void GenericDescriptorMatcher::add( const vector<Mat>& imgCollection,
                                    vector<vector<KeyPoint> >& pointCollection )
Maria Dimashova's avatar
Maria Dimashova committed
743
{
744
    trainPointCollection.add( imgCollection, pointCollection );
Maria Dimashova's avatar
Maria Dimashova committed
745 746
}

747 748 749 750 751 752 753 754 755 756
const vector<Mat>& GenericDescriptorMatcher::getTrainImages() const
{
    return trainPointCollection.getImages();
}

const vector<vector<KeyPoint> >& GenericDescriptorMatcher::getTrainKeypoints() const
{
    return trainPointCollection.getKeypoints();
}

757
void GenericDescriptorMatcher::clear()
Maria Dimashova's avatar
Maria Dimashova committed
758
{
759
    trainPointCollection.clear();
Maria Dimashova's avatar
Maria Dimashova committed
760 761
}

762 763 764
void GenericDescriptorMatcher::train()
{}

765 766
void GenericDescriptorMatcher::classify( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                         const Mat& trainImage, vector<KeyPoint>& trainKeypoints ) const
Maria Dimashova's avatar
Maria Dimashova committed
767
{
768
    vector<DMatch> matches;
769
    match( queryImage, queryKeypoints, trainImage, trainKeypoints, matches );
770 771 772

    // remap keypoint indices to descriptors
    for( size_t i = 0; i < matches.size(); i++ )
773
        queryKeypoints[matches[i].queryIdx].class_id = trainKeypoints[matches[i].trainIdx].class_id;
Maria Dimashova's avatar
Maria Dimashova committed
774 775
}

776
void GenericDescriptorMatcher::classify( const Mat& queryImage, vector<KeyPoint>& queryKeypoints )
Maria Dimashova's avatar
Maria Dimashova committed
777
{
778
    vector<DMatch> matches;
779
    match( queryImage, queryKeypoints, matches );
Maria Dimashova's avatar
Maria Dimashova committed
780 781

    // remap keypoint indices to descriptors
782
    for( size_t i = 0; i < matches.size(); i++ )
783
        queryKeypoints[matches[i].queryIdx].class_id = trainPointCollection.getKeyPoint( matches[i].trainIdx, matches[i].trainIdx ).class_id;
784 785
}

786 787
void GenericDescriptorMatcher::match( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                      const Mat& trainImage, vector<KeyPoint>& trainKeypoints,
788 789
                                      vector<DMatch>& matches, const Mat& mask ) const
{
790
    Ptr<GenericDescriptorMatcher> tempMatcher = clone( true );
791 792 793 794
    vector<vector<KeyPoint> > vecTrainPoints(1, trainKeypoints);
    tempMatcher->add( vector<Mat>(1, trainImage), vecTrainPoints );
    tempMatcher->match( queryImage, queryKeypoints, matches, vector<Mat>(1, mask) );
    vecTrainPoints[0].swap( trainKeypoints );
795 796
}

797 798
void GenericDescriptorMatcher::knnMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                         const Mat& trainImage, vector<KeyPoint>& trainKeypoints,
799 800
                                         vector<vector<DMatch> >& matches, int knn, const Mat& mask, bool compactResult ) const
{
801
    Ptr<GenericDescriptorMatcher> tempMatcher = clone( true );
802 803 804 805
    vector<vector<KeyPoint> > vecTrainPoints(1, trainKeypoints);
    tempMatcher->add( vector<Mat>(1, trainImage), vecTrainPoints );
    tempMatcher->knnMatch( queryImage, queryKeypoints, matches, knn, vector<Mat>(1, mask), compactResult );
    vecTrainPoints[0].swap( trainKeypoints );
806
}
Maria Dimashova's avatar
Maria Dimashova committed
807

808 809
void GenericDescriptorMatcher::radiusMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                            const Mat& trainImage, vector<KeyPoint>& trainKeypoints,
810 811
                                            vector<vector<DMatch> >& matches, float maxDistance,
                                            const Mat& mask, bool compactResult ) const
Maria Dimashova's avatar
Maria Dimashova committed
812
{
813
    Ptr<GenericDescriptorMatcher> tempMatcher = clone( true );
814 815 816 817
    vector<vector<KeyPoint> > vecTrainPoints(1, trainKeypoints);
    tempMatcher->add( vector<Mat>(1, trainImage), vecTrainPoints );
    tempMatcher->radiusMatch( queryImage, queryKeypoints, matches, maxDistance, vector<Mat>(1, mask), compactResult );
    vecTrainPoints[0].swap( trainKeypoints );
818 819
}

820
void GenericDescriptorMatcher::match( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
821 822 823
                                      vector<DMatch>& matches, const vector<Mat>& masks )
{
    vector<vector<DMatch> > knnMatches;
824
    knnMatch( queryImage, queryKeypoints, knnMatches, 1, masks, false );
825 826 827
    convertMatches( knnMatches, matches );
}

828
void GenericDescriptorMatcher::knnMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
829 830 831 832
                                         vector<vector<DMatch> >& matches, int knn,
                                         const vector<Mat>& masks, bool compactResult )
{
    train();
833
    knnMatchImpl( queryImage, queryKeypoints, matches, knn, masks, compactResult );
834 835
}

836
void GenericDescriptorMatcher::radiusMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
837 838 839 840
                                            vector<vector<DMatch> >& matches, float maxDistance,
                                            const vector<Mat>& masks, bool compactResult )
{
    train();
841
    radiusMatchImpl( queryImage, queryKeypoints, matches, maxDistance, masks, compactResult );
Maria Dimashova's avatar
Maria Dimashova committed
842 843
}

844 845 846 847 848 849
void GenericDescriptorMatcher::read( const FileNode& )
{}

void GenericDescriptorMatcher::write( FileStorage& ) const
{}

Maria Dimashova's avatar
Maria Dimashova committed
850
/****************************************************************************************\
851
*                                OneWayDescriptorMatcher                                  *
Maria Dimashova's avatar
Maria Dimashova committed
852
\****************************************************************************************/
853 854 855 856 857 858 859 860 861 862

OneWayDescriptorMatcher::Params::Params( int _poseCount, Size _patchSize, string _pcaFilename,
                                         string _trainPath, string _trainImagesList,
                                         float _minScale, float _maxScale, float _stepScale ) :
                poseCount(_poseCount), patchSize(_patchSize), pcaFilename(_pcaFilename),
                trainPath(_trainPath), trainImagesList(_trainImagesList),
                minScale(_minScale), maxScale(_maxScale), stepScale(_stepScale)
{}


863
OneWayDescriptorMatcher::OneWayDescriptorMatcher( const Params& _params)
Maria Dimashova's avatar
Maria Dimashova committed
864 865 866 867
{
    initialize(_params);
}

868
OneWayDescriptorMatcher::~OneWayDescriptorMatcher()
Maria Dimashova's avatar
Maria Dimashova committed
869 870
{}

871
void OneWayDescriptorMatcher::initialize( const Params& _params, const Ptr<OneWayDescriptorBase>& _base )
Maria Dimashova's avatar
Maria Dimashova committed
872
{
873 874 875
    clear();

    if( _base.empty() )
Maria Dimashova's avatar
Maria Dimashova committed
876
        base = _base;
877

Maria Dimashova's avatar
Maria Dimashova committed
878 879 880
    params = _params;
}

881
void OneWayDescriptorMatcher::clear()
Maria Dimashova's avatar
Maria Dimashova committed
882
{
883
    GenericDescriptorMatcher::clear();
Maria Dimashova's avatar
Maria Dimashova committed
884

885 886
    prevTrainCount = 0;
    base->clear();
Maria Dimashova's avatar
Maria Dimashova committed
887 888
}

889
void OneWayDescriptorMatcher::train()
Maria Dimashova's avatar
Maria Dimashova committed
890
{
891
    if( base.empty() || prevTrainCount < (int)trainPointCollection.keypointCount() )
892
    {
Maria Dimashova's avatar
Maria Dimashova committed
893
        base = new OneWayDescriptorObject( params.patchSize, params.poseCount, params.pcaFilename,
894
                                           params.trainPath, params.trainImagesList, params.minScale, params.maxScale, params.stepScale );
Maria Dimashova's avatar
Maria Dimashova committed
895

896 897
        base->Allocate( trainPointCollection.keypointCount() );
        prevTrainCount = trainPointCollection.keypointCount();
Maria Dimashova's avatar
Maria Dimashova committed
898

899 900 901
        const vector<vector<KeyPoint> >& points = trainPointCollection.getKeypoints();
        int count = 0;
        for( size_t i = 0; i < points.size(); i++ )
Maria Dimashova's avatar
Maria Dimashova committed
902
        {
903 904 905
            IplImage _image = trainPointCollection.getImage(i);
            for( size_t j = 0; j < points[i].size(); j++ )
                base->InitializeDescriptor( count++, &_image, points[i][j], "" );
Maria Dimashova's avatar
Maria Dimashova committed
906 907 908
        }

#if defined(_KDTREE)
909
        base->ConvertDescriptorsArrayToTree();
Maria Dimashova's avatar
Maria Dimashova committed
910
#endif
911
    }
Maria Dimashova's avatar
Maria Dimashova committed
912 913
}

914 915 916 917 918
bool OneWayDescriptorMatcher::isMaskSupported()
{
    return false;
}

919
void OneWayDescriptorMatcher::knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
920 921
                                            vector<vector<DMatch> >& matches, int knn,
                                            const vector<Mat>& /*masks*/, bool /*compactResult*/ )
Maria Dimashova's avatar
Maria Dimashova committed
922
{
923
    train();
Maria Dimashova's avatar
Maria Dimashova committed
924

925
    CV_Assert( knn == 1 ); // knn > 1 unsupported because of bug in OneWayDescriptorBase for this case
Maria Dimashova's avatar
Maria Dimashova committed
926

927 928 929
    matches.resize( queryKeypoints.size() );
    IplImage _qimage = queryImage;
    for( size_t i = 0; i < queryKeypoints.size(); i++ )
Maria Dimashova's avatar
Maria Dimashova committed
930
    {
931 932
        int descIdx = -1, poseIdx = -1;
        float distance;
933
        base->FindDescriptor( &_qimage, queryKeypoints[i].pt, descIdx, poseIdx, distance );
934
        matches[i].push_back( DMatch(i, descIdx, distance) );
Maria Dimashova's avatar
Maria Dimashova committed
935 936 937
    }
}

938
void OneWayDescriptorMatcher::radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
939 940
                                               vector<vector<DMatch> >& matches, float maxDistance,
                                               const vector<Mat>& /*masks*/, bool /*compactResult*/ )
Maria Dimashova's avatar
Maria Dimashova committed
941
{
942
    train();
Maria Dimashova's avatar
Maria Dimashova committed
943

944 945 946
    matches.resize( queryKeypoints.size() );
    IplImage _qimage = queryImage;
    for( size_t i = 0; i < queryKeypoints.size(); i++ )
Maria Dimashova's avatar
Maria Dimashova committed
947
    {
948 949
        int descIdx = -1, poseIdx = -1;
        float distance;
950
        base->FindDescriptor( &_qimage, queryKeypoints[i].pt, descIdx, poseIdx, distance );
951 952
        if( distance < maxDistance )
            matches[i].push_back( DMatch(i, descIdx, distance) );
Maria Dimashova's avatar
Maria Dimashova committed
953 954 955
    }
}

956
void OneWayDescriptorMatcher::read( const FileNode &fn )
Maria Dimashova's avatar
Maria Dimashova committed
957 958 959 960 961 962
{
    base = new OneWayDescriptorObject( params.patchSize, params.poseCount, string (), string (), string (),
                                       params.minScale, params.maxScale, params.stepScale );
    base->Read (fn);
}

963
void OneWayDescriptorMatcher::write( FileStorage& fs ) const
Maria Dimashova's avatar
Maria Dimashova committed
964 965 966 967
{
    base->Write (fs);
}

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
Ptr<GenericDescriptorMatcher> OneWayDescriptorMatcher::clone( bool emptyTrainData ) const
{
    OneWayDescriptorMatcher* matcher = new OneWayDescriptorMatcher( params );

    if( !emptyTrainData )
    {
        CV_Error( CV_StsNotImplemented, "deep clone dunctionality is not implemented, because "
              "OneWayDescriptorBase has not copy constructor or clone method ");

        //matcher->base;
        matcher->params = params;
        matcher->prevTrainCount = prevTrainCount;
        matcher->trainPointCollection = trainPointCollection;
    }
    return matcher;
}

Maria Dimashova's avatar
Maria Dimashova committed
985
/****************************************************************************************\
986
*                                  FernDescriptorMatcher                                 *
Maria Dimashova's avatar
Maria Dimashova committed
987
\****************************************************************************************/
988
FernDescriptorMatcher::Params::Params( int _nclasses, int _patchSize, int _signatureSize,
Maria Dimashova's avatar
Maria Dimashova committed
989 990 991 992 993 994 995
                                     int _nstructs, int _structSize, int _nviews, int _compressionMethod,
                                     const PatchGenerator& _patchGenerator ) :
    nclasses(_nclasses), patchSize(_patchSize), signatureSize(_signatureSize),
    nstructs(_nstructs), structSize(_structSize), nviews(_nviews),
    compressionMethod(_compressionMethod), patchGenerator(_patchGenerator)
{}

996
FernDescriptorMatcher::Params::Params( const string& _filename )
Maria Dimashova's avatar
Maria Dimashova committed
997 998 999 1000
{
    filename = _filename;
}

1001
FernDescriptorMatcher::FernDescriptorMatcher( const Params& _params )
Maria Dimashova's avatar
Maria Dimashova committed
1002
{
1003
    prevTrainCount = 0;
Maria Dimashova's avatar
Maria Dimashova committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    params = _params;
    if( !params.filename.empty() )
    {
        classifier = new FernClassifier;
        FileStorage fs(params.filename, FileStorage::READ);
        if( fs.isOpened() )
            classifier->read( fs.getFirstTopLevelNode() );
    }
}

1014 1015 1016 1017
FernDescriptorMatcher::~FernDescriptorMatcher()
{}

void FernDescriptorMatcher::clear()
Maria Dimashova's avatar
Maria Dimashova committed
1018
{
1019 1020 1021 1022
    GenericDescriptorMatcher::clear();

    classifier.release();
    prevTrainCount = 0;
Maria Dimashova's avatar
Maria Dimashova committed
1023 1024
}

1025
void FernDescriptorMatcher::train()
Maria Dimashova's avatar
Maria Dimashova committed
1026
{
1027
    if( classifier.empty() || prevTrainCount < (int)trainPointCollection.keypointCount() )
Maria Dimashova's avatar
Maria Dimashova committed
1028 1029 1030
    {
        assert( params.filename.empty() );

1031 1032 1033
        vector<vector<Point2f> > points( trainPointCollection.imageCount() );
        for( size_t imgIdx = 0; imgIdx < trainPointCollection.imageCount(); imgIdx++ )
            KeyPoint::convert( trainPointCollection.getKeypoints(imgIdx), points[imgIdx] );
Maria Dimashova's avatar
Maria Dimashova committed
1034

1035
        classifier = new FernClassifier( points, trainPointCollection.getImages(), vector<vector<int> >(), 0, // each points is a class
Maria Dimashova's avatar
Maria Dimashova committed
1036 1037 1038 1039 1040
                                         params.patchSize, params.signatureSize, params.nstructs, params.structSize,
                                         params.nviews, params.compressionMethod, params.patchGenerator );
    }
}

1041 1042 1043 1044 1045
bool FernDescriptorMatcher::isMaskSupported()
{
    return false;
}

1046 1047
void FernDescriptorMatcher::calcBestProbAndMatchIdx( const Mat& image, const Point2f& pt,
                                                     float& bestProb, int& bestMatchIdx, vector<float>& signature )
Maria Dimashova's avatar
Maria Dimashova committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
{
    (*classifier)( image, pt, signature);

    bestProb = -FLT_MAX;
    bestMatchIdx = -1;
    for( int ci = 0; ci < classifier->getClassCount(); ci++ )
    {
        if( signature[ci] > bestProb )
        {
            bestProb = signature[ci];
            bestMatchIdx = ci;
        }
    }
}

1063
void FernDescriptorMatcher::knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
1064 1065
                                          vector<vector<DMatch> >& matches, int knn,
                                          const vector<Mat>& /*masks*/, bool /*compactResult*/ )
Maria Dimashova's avatar
Maria Dimashova committed
1066
{
1067
    train();
Maria Dimashova's avatar
Maria Dimashova committed
1068

1069
    matches.resize( queryKeypoints.size() );
Maria Dimashova's avatar
Maria Dimashova committed
1070 1071
    vector<float> signature( (size_t)classifier->getClassCount() );

1072
    for( size_t queryIdx = 0; queryIdx < queryKeypoints.size(); queryIdx++ )
Maria Dimashova's avatar
Maria Dimashova committed
1073
    {
1074
        (*classifier)( queryImage, queryKeypoints[queryIdx].pt, signature);
Maria Dimashova's avatar
Maria Dimashova committed
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        for( int k = 0; k < knn; k++ )
        {
            DMatch bestMatch;
            size_t ci = 0;
            for( ; ci < signature.size(); ci++ )
            {
                if( -signature[ci] < bestMatch.distance )
                {
                    int imgIdx = -1, trainIdx = -1;
                    trainPointCollection.getLocalIdx( ci , imgIdx, trainIdx );
                    bestMatch = DMatch( queryIdx, trainIdx, imgIdx, -signature[ci] );
                }
            }
Maria Dimashova's avatar
Maria Dimashova committed
1089

1090 1091 1092 1093 1094
            if( bestMatch.trainIdx == -1 )
                break;
            signature[ci] = std::numeric_limits<float>::min();
            matches[queryIdx].push_back( bestMatch );
        }
Maria Dimashova's avatar
Maria Dimashova committed
1095 1096 1097
    }
}

1098
void FernDescriptorMatcher::radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
1099 1100
                                             vector<vector<DMatch> >& matches, float maxDistance,
                                             const vector<Mat>& /*masks*/, bool /*compactResult*/ )
Maria Dimashova's avatar
Maria Dimashova committed
1101
{
1102
    train();
1103
    matches.resize( queryKeypoints.size() );
Maria Dimashova's avatar
Maria Dimashova committed
1104 1105
    vector<float> signature( (size_t)classifier->getClassCount() );

1106
    for( size_t i = 0; i < queryKeypoints.size(); i++ )
Maria Dimashova's avatar
Maria Dimashova committed
1107
    {
1108
        (*classifier)( queryImage, queryKeypoints[i].pt, signature);
Maria Dimashova's avatar
Maria Dimashova committed
1109 1110 1111

        for( int ci = 0; ci < classifier->getClassCount(); ci++ )
        {
1112
            if( -signature[ci] < maxDistance )
Maria Dimashova's avatar
Maria Dimashova committed
1113
            {
1114 1115 1116
                int imgIdx = -1, trainIdx = -1;
                trainPointCollection.getLocalIdx( ci , imgIdx, trainIdx );
                matches[i].push_back( DMatch( i, trainIdx, imgIdx, -signature[ci] ) );
Maria Dimashova's avatar
Maria Dimashova committed
1117 1118 1119 1120 1121
            }
        }
    }
}

1122
void FernDescriptorMatcher::read( const FileNode &fn )
Maria Dimashova's avatar
Maria Dimashova committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
{
    params.nclasses = fn["nclasses"];
    params.patchSize = fn["patchSize"];
    params.signatureSize = fn["signatureSize"];
    params.nstructs = fn["nstructs"];
    params.structSize = fn["structSize"];
    params.nviews = fn["nviews"];
    params.compressionMethod = fn["compressionMethod"];

    //classifier->read(fn);
}

1135
void FernDescriptorMatcher::write( FileStorage& fs ) const
Maria Dimashova's avatar
Maria Dimashova committed
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
{
    fs << "nclasses" << params.nclasses;
    fs << "patchSize" << params.patchSize;
    fs << "signatureSize" << params.signatureSize;
    fs << "nstructs" << params.nstructs;
    fs << "structSize" << params.structSize;
    fs << "nviews" << params.nviews;
    fs << "compressionMethod" << params.compressionMethod;

//    classifier->write(fs);
}

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
Ptr<GenericDescriptorMatcher> FernDescriptorMatcher::clone( bool emptyTrainData ) const
{
    FernDescriptorMatcher* matcher = new FernDescriptorMatcher( params );
    if( !emptyTrainData )
    {
        CV_Error( CV_StsNotImplemented, "deep clone dunctionality is not implemented, because "
              "FernClassifier has not copy constructor or clone method ");

        //matcher->classifier;
        matcher->params = params;
        matcher->prevTrainCount = prevTrainCount;
        matcher->trainPointCollection = trainPointCollection;
    }
    return matcher;
}

Maria Dimashova's avatar
Maria Dimashova committed
1164
/****************************************************************************************\
1165
*                                  VectorDescriptorMatcher                               *
Maria Dimashova's avatar
Maria Dimashova committed
1166
\****************************************************************************************/
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
VectorDescriptorMatcher::VectorDescriptorMatcher( const Ptr<DescriptorExtractor>& _extractor,
                                                  const Ptr<DescriptorMatcher>& _matcher )
                                : extractor( _extractor ), matcher( _matcher )
{
    CV_Assert( !extractor.empty() && !matcher.empty() );
}

VectorDescriptorMatcher::~VectorDescriptorMatcher()
{}

1177 1178
void VectorDescriptorMatcher::add( const vector<Mat>& imgCollection,
                                   vector<vector<KeyPoint> >& pointCollection )
Maria Dimashova's avatar
Maria Dimashova committed
1179
{
1180 1181
    vector<Mat> descriptors;
    extractor->compute( imgCollection, pointCollection, descriptors );
Maria Dimashova's avatar
Maria Dimashova committed
1182

1183
    matcher->add( descriptors );
Maria Dimashova's avatar
Maria Dimashova committed
1184

1185 1186
    trainPointCollection.add( imgCollection, pointCollection );
}
Maria Dimashova's avatar
Maria Dimashova committed
1187

1188
void VectorDescriptorMatcher::clear()
Maria Dimashova's avatar
Maria Dimashova committed
1189
{
1190 1191 1192
    //extractor->clear();
    matcher->clear();
    GenericDescriptorMatcher::clear();
Maria Dimashova's avatar
Maria Dimashova committed
1193 1194
}

1195
void VectorDescriptorMatcher::train()
Maria Dimashova's avatar
Maria Dimashova committed
1196
{
1197 1198
    matcher->train();
}
Maria Dimashova's avatar
Maria Dimashova committed
1199

1200 1201 1202 1203 1204
bool VectorDescriptorMatcher::isMaskSupported()
{
    return matcher->isMaskSupported();
}

1205
void VectorDescriptorMatcher::knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
1206 1207 1208
                                            vector<vector<DMatch> >& matches, int knn,
                                            const vector<Mat>& masks, bool compactResult )
{
1209
    Mat queryDescriptors;
1210
    extractor->compute( queryImage, queryKeypoints, queryDescriptors );
1211
    matcher->knnMatch( queryDescriptors, matches, knn, masks, compactResult );
Maria Dimashova's avatar
Maria Dimashova committed
1212 1213
}

1214
void VectorDescriptorMatcher::radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
1215 1216
                                               vector<vector<DMatch> >& matches, float maxDistance,
                                               const vector<Mat>& masks, bool compactResult )
Maria Dimashova's avatar
Maria Dimashova committed
1217
{
1218
    Mat queryDescriptors;
1219
    extractor->compute( queryImage, queryKeypoints, queryDescriptors );
1220
    matcher->radiusMatch( queryDescriptors, matches, maxDistance, masks, compactResult );
Maria Dimashova's avatar
Maria Dimashova committed
1221 1222
}

1223
void VectorDescriptorMatcher::read( const FileNode& fn )
Maria Dimashova's avatar
Maria Dimashova committed
1224
{
1225
    GenericDescriptorMatcher::read(fn);
1226
    extractor->read(fn);
Maria Dimashova's avatar
Maria Dimashova committed
1227 1228
}

1229
void VectorDescriptorMatcher::write (FileStorage& fs) const
Maria Dimashova's avatar
Maria Dimashova committed
1230
{
1231
    GenericDescriptorMatcher::write(fs);
Maria Dimashova's avatar
Maria Dimashova committed
1232 1233 1234
    extractor->write (fs);
}

1235 1236 1237 1238 1239 1240
Ptr<GenericDescriptorMatcher> VectorDescriptorMatcher::clone( bool emptyTrainData ) const
{
    // TODO clone extractor
    return new VectorDescriptorMatcher( extractor, matcher->clone(emptyTrainData) );
}

1241 1242 1243
/*
 * Factory function for GenericDescriptorMatch creating
 */
1244 1245
Ptr<GenericDescriptorMatcher> createGenericDescriptorMatcher( const string& genericDescritptorMatcherType,
                                                              const string &paramsFilename )
Maria Dimashova's avatar
Maria Dimashova committed
1246
{
1247
    Ptr<GenericDescriptorMatcher> descriptorMatcher;
1248
    if( ! genericDescritptorMatcherType.compare("ONEWAY") )
Maria Dimashova's avatar
Maria Dimashova committed
1249
    {
1250
        descriptorMatcher = new OneWayDescriptorMatcher();
Maria Dimashova's avatar
Maria Dimashova committed
1251
    }
1252
    else if( ! genericDescritptorMatcherType.compare("FERN") )
Maria Dimashova's avatar
Maria Dimashova committed
1253
    {
1254
        descriptorMatcher = new FernDescriptorMatcher();
Maria Dimashova's avatar
Maria Dimashova committed
1255 1256
    }

1257
    if( !paramsFilename.empty() && !descriptorMatcher.empty() )
Maria Dimashova's avatar
Maria Dimashova committed
1258 1259 1260 1261
    {
        FileStorage fs = FileStorage( paramsFilename, FileStorage::READ );
        if( fs.isOpened() )
        {
1262
            descriptorMatcher->read( fs.root() );
Maria Dimashova's avatar
Maria Dimashova committed
1263 1264 1265
            fs.release();
        }
    }
1266
    return descriptorMatcher;
Maria Dimashova's avatar
Maria Dimashova committed
1267 1268 1269
}

}