test_features2d.cpp 49.5 KB
Newer Older
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
/*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 "test_precomp.hpp"
#include "opencv2/calib3d.hpp"

using namespace std;
using namespace cv;
using namespace cv::xfeatures2d;

const string FEATURES2D_DIR = "features2d";
const string DETECTOR_DIR = FEATURES2D_DIR + "/feature_detectors";
const string DESCRIPTOR_DIR = FEATURES2D_DIR + "/descriptor_extractors";
const string IMAGE_FILENAME = "tsukuba.png";

/****************************************************************************************\
*            Regression tests for feature detectors comparing keypoints.                 *
\****************************************************************************************/

class CV_FeatureDetectorTest : public cvtest::BaseTest
{
public:
    CV_FeatureDetectorTest( const string& _name, const Ptr<FeatureDetector>& _fdetector ) :
        name(_name), fdetector(_fdetector) {}

protected:
    bool isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 );
    void compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints );

    void emptyDataTest();
    void regressionTest(); // TODO test of detect() with mask

    virtual void run( int );

    string name;
    Ptr<FeatureDetector> fdetector;
};

void CV_FeatureDetectorTest::emptyDataTest()
{
    // One image.
    Mat image;
    vector<KeyPoint> keypoints;
    try
    {
        fdetector->detect( image, keypoints );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "detect() on empty image must not generate exception (1).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    if( !keypoints.empty() )
    {
        ts->printf( cvtest::TS::LOG, "detect() on empty image must return empty keypoints vector (1).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        return;
    }

    // Several images.
    vector<Mat> images;
    vector<vector<KeyPoint> > keypointCollection;
    try
    {
        fdetector->detect( images, keypointCollection );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "detect() on empty image vector must not generate exception (2).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }
}

bool CV_FeatureDetectorTest::isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 )
{
    const float maxPtDif = 1.f;
    const float maxSizeDif = 1.f;
    const float maxAngleDif = 2.f;
    const float maxResponseDif = 0.1f;

    float dist = (float)norm( p1.pt - p2.pt );
    return (dist < maxPtDif &&
            fabs(p1.size - p2.size) < maxSizeDif &&
            abs(p1.angle - p2.angle) < maxAngleDif &&
            abs(p1.response - p2.response) < maxResponseDif &&
            p1.octave == p2.octave &&
            p1.class_id == p2.class_id );
}

void CV_FeatureDetectorTest::compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints )
{
    const float maxCountRatioDif = 0.01f;

    // Compare counts of validation and calculated keypoints.
    float countRatio = (float)validKeypoints.size() / (float)calcKeypoints.size();
    if( countRatio < 1 - maxCountRatioDif || countRatio > 1.f + maxCountRatioDif )
    {
        ts->printf( cvtest::TS::LOG, "Bad keypoints count ratio (validCount = %d, calcCount = %d).\n",
                    validKeypoints.size(), calcKeypoints.size() );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        return;
    }

    int progress = 0, progressCount = (int)(validKeypoints.size() * calcKeypoints.size());
    int badPointCount = 0, commonPointCount = max((int)validKeypoints.size(), (int)calcKeypoints.size());
    for( size_t v = 0; v < validKeypoints.size(); v++ )
    {
        int nearestIdx = -1;
        float minDist = std::numeric_limits<float>::max();

        for( size_t c = 0; c < calcKeypoints.size(); c++ )
        {
            progress = update_progress( progress, (int)(v*calcKeypoints.size() + c), progressCount, 0 );
            float curDist = (float)norm( calcKeypoints[c].pt - validKeypoints[v].pt );
            if( curDist < minDist )
            {
                minDist = curDist;
                nearestIdx = (int)c;
            }
        }

        assert( minDist >= 0 );
        if( !isSimilarKeypoints( validKeypoints[v], calcKeypoints[nearestIdx] ) )
            badPointCount++;
    }
    ts->printf( cvtest::TS::LOG, "badPointCount = %d; validPointCount = %d; calcPointCount = %d\n",
                badPointCount, validKeypoints.size(), calcKeypoints.size() );
    if( badPointCount > 0.9 * commonPointCount )
    {
        ts->printf( cvtest::TS::LOG, " - Bad accuracy!\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
        return;
    }
    ts->printf( cvtest::TS::LOG, " - OK\n" );
}

void CV_FeatureDetectorTest::regressionTest()
{
    assert( !fdetector.empty() );
    string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
    string resFilename = string(ts->get_data_path()) + DETECTOR_DIR + "/" + string(name) + ".xml.gz";

    // Read the test image.
    Mat image = imread( imgFilename );
    if( image.empty() )
    {
        ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
        return;
    }

    FileStorage fs( resFilename, FileStorage::READ );

    // Compute keypoints.
    vector<KeyPoint> calcKeypoints;
    fdetector->detect( image, calcKeypoints );

    if( fs.isOpened() ) // Compare computed and valid keypoints.
    {
        // TODO compare saved feature detector params with current ones

        // Read validation keypoints set.
        vector<KeyPoint> validKeypoints;
        read( fs["keypoints"], validKeypoints );
        if( validKeypoints.empty() )
        {
            ts->printf( cvtest::TS::LOG, "Keypoints can not be read.\n" );
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }

        compareKeypointSets( validKeypoints, calcKeypoints );
    }
    else // Write detector parameters and computed keypoints as validation data.
    {
        fs.open( resFilename, FileStorage::WRITE );
        if( !fs.isOpened() )
        {
            ts->printf( cvtest::TS::LOG, "File %s can not be opened to write.\n", resFilename.c_str() );
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }
        else
        {
            fs << "detector_params" << "{";
            fdetector->write( fs );
            fs << "}";

            write( fs, "keypoints", calcKeypoints );
        }
    }
}

void CV_FeatureDetectorTest::run( int /*start_from*/ )
{
    if( !fdetector )
    {
        ts->printf( cvtest::TS::LOG, "Feature detector is empty.\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
        return;
    }

    emptyDataTest();
    regressionTest();

    ts->set_failed_test_info( cvtest::TS::OK );
}

/****************************************************************************************\
*                     Regression tests for descriptor extractors.                        *
\****************************************************************************************/
static void writeMatInBin( const Mat& mat, const string& filename )
{
    FILE* f = fopen( filename.c_str(), "wb");
    if( f )
    {
        int type = mat.type();
        fwrite( (void*)&mat.rows, sizeof(int), 1, f );
        fwrite( (void*)&mat.cols, sizeof(int), 1, f );
        fwrite( (void*)&type, sizeof(int), 1, f );
        int dataSize = (int)(mat.step * mat.rows * mat.channels());
        fwrite( (void*)&dataSize, sizeof(int), 1, f );
        fwrite( (void*)mat.data, 1, dataSize, f );
        fclose(f);
    }
}

static Mat readMatFromBin( const string& filename )
{
    FILE* f = fopen( filename.c_str(), "rb" );
    if( f )
    {
        int rows, cols, type, dataSize;
        size_t elements_read1 = fread( (void*)&rows, sizeof(int), 1, f );
        size_t elements_read2 = fread( (void*)&cols, sizeof(int), 1, f );
        size_t elements_read3 = fread( (void*)&type, sizeof(int), 1, f );
        size_t elements_read4 = fread( (void*)&dataSize, sizeof(int), 1, f );
        CV_Assert(elements_read1 == 1 && elements_read2 == 1 && elements_read3 == 1 && elements_read4 == 1);

        int step = dataSize / rows / CV_ELEM_SIZE(type);
        CV_Assert(step >= cols);

        Mat m = Mat( rows, step, type).colRange(0, cols);

        size_t elements_read = fread( m.ptr(), 1, dataSize, f );
        CV_Assert(elements_read == (size_t)(dataSize));
        fclose(f);

        return m;
    }
    return Mat();
}

template<class Distance>
class CV_DescriptorExtractorTest : public cvtest::BaseTest
{
public:
    typedef typename Distance::ValueType ValueType;
    typedef typename Distance::ResultType DistanceType;

    CV_DescriptorExtractorTest( const string _name, DistanceType _maxDist, const Ptr<DescriptorExtractor>& _dextractor,
301 302
                                int imgMode = IMREAD_COLOR, Distance d = Distance()):
            name(_name), maxDist(_maxDist), dextractor(_dextractor), imgLoadMode(imgMode), distance(d) {}
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
protected:
    virtual void createDescriptorExtractor() {}

    void compareDescriptors( const Mat& validDescriptors, const Mat& calcDescriptors )
    {
        if( validDescriptors.size != calcDescriptors.size || validDescriptors.type() != calcDescriptors.type() )
        {
            ts->printf(cvtest::TS::LOG, "Valid and computed descriptors matrices must have the same size and type.\n");
            ts->printf(cvtest::TS::LOG, "Valid size is (%d x %d) actual size is (%d x %d).\n", validDescriptors.rows, validDescriptors.cols, calcDescriptors.rows, calcDescriptors.cols);
            ts->printf(cvtest::TS::LOG, "Valid type is %d  actual type is %d.\n", validDescriptors.type(), calcDescriptors.type());
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }

        CV_Assert( DataType<ValueType>::type == validDescriptors.type() );

        int dimension = validDescriptors.cols;
        DistanceType curMaxDist = std::numeric_limits<DistanceType>::min();
        for( int y = 0; y < validDescriptors.rows; y++ )
        {
            DistanceType dist = distance( validDescriptors.ptr<ValueType>(y), calcDescriptors.ptr<ValueType>(y), dimension );
            if( dist > curMaxDist )
                curMaxDist = dist;
        }

        stringstream ss;
        ss << "Max distance between valid and computed descriptors " << curMaxDist;
330
        if( curMaxDist <= maxDist )
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            ss << "." << endl;
        else
        {
            ss << ">" << maxDist  << " - bad accuracy!"<< endl;
            ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
        }
        ts->printf(cvtest::TS::LOG,  ss.str().c_str() );
    }

    void emptyDataTest()
    {
        assert( !dextractor.empty() );

        // One image.
        Mat image;
        vector<KeyPoint> keypoints;
        Mat descriptors;

        try
        {
            dextractor->compute( image, keypoints, descriptors );
        }
        catch(...)
        {
            ts->printf( cvtest::TS::LOG, "compute() on empty image and empty keypoints must not generate exception (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
        }

359 360 361 362
        if(imgLoadMode == IMREAD_GRAYSCALE)
            image.create( 50, 50, CV_8UC1 );
        else
            image.create( 50, 50, CV_8UC3 );
363 364 365 366 367 368 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
        try
        {
            dextractor->compute( image, keypoints, descriptors );
        }
        catch(...)
        {
            ts->printf( cvtest::TS::LOG, "compute() on nonempty image and empty keypoints must not generate exception (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
        }

        // Several images.
        vector<Mat> images;
        vector<vector<KeyPoint> > keypointsCollection;
        vector<Mat> descriptorsCollection;
        try
        {
            dextractor->compute( images, keypointsCollection, descriptorsCollection );
        }
        catch(...)
        {
            ts->printf( cvtest::TS::LOG, "compute() on empty images and empty keypoints collection must not generate exception (2).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
        }
    }

    void regressionTest()
    {
        assert( !dextractor.empty() );

        // Read the test image.
        string imgFilename =  string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;

395
        Mat img = imread( imgFilename, imgLoadMode );
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        if( img.empty() )
        {
            ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }

        vector<KeyPoint> keypoints;
        FileStorage fs( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::READ );
        if( fs.isOpened() )
        {
            read( fs.getFirstTopLevelNode(), keypoints );

            Mat calcDescriptors;
            double t = (double)getTickCount();
            dextractor->compute( img, keypoints, calcDescriptors );
            t = getTickCount() - t;
            ts->printf(cvtest::TS::LOG, "\nAverage time of computing one descriptor = %g ms.\n", t/((double)getTickFrequency()*1000.)/calcDescriptors.rows );

            if( calcDescriptors.rows != (int)keypoints.size() )
            {
                ts->printf( cvtest::TS::LOG, "Count of computed descriptors and keypoints count must be equal.\n" );
                ts->printf( cvtest::TS::LOG, "Count of keypoints is            %d.\n", (int)keypoints.size() );
                ts->printf( cvtest::TS::LOG, "Count of computed descriptors is %d.\n", calcDescriptors.rows );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            if( calcDescriptors.cols != dextractor->descriptorSize() || calcDescriptors.type() != dextractor->descriptorType() )
            {
                ts->printf( cvtest::TS::LOG, "Incorrect descriptor size or descriptor type.\n" );
                ts->printf( cvtest::TS::LOG, "Expected size is   %d.\n", dextractor->descriptorSize() );
                ts->printf( cvtest::TS::LOG, "Calculated size is %d.\n", calcDescriptors.cols );
                ts->printf( cvtest::TS::LOG, "Expected type is   %d.\n", dextractor->descriptorType() );
                ts->printf( cvtest::TS::LOG, "Calculated type is %d.\n", calcDescriptors.type() );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            // TODO read and write descriptor extractor parameters and check them
            Mat validDescriptors = readDescriptors();
            if( !validDescriptors.empty() )
                compareDescriptors( validDescriptors, calcDescriptors );
            else
            {
                if( !writeDescriptors( calcDescriptors ) )
                {
                    ts->printf( cvtest::TS::LOG, "Descriptors can not be written.\n" );
                    ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
                    return;
                }
            }
        }
        else
        {
            ts->printf( cvtest::TS::LOG, "Compute and write keypoints.\n" );
            fs.open( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::WRITE );
            if( fs.isOpened() )
            {
455 456
                Ptr<SURF> fd = SURF::create();
                fd->detect(img, keypoints);
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
                write( fs, "keypoints", keypoints );
            }
            else
            {
                ts->printf(cvtest::TS::LOG, "File for writting keypoints can not be opened.\n");
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
                return;
            }
        }
    }

    void run(int)
    {
        createDescriptorExtractor();
        if( !dextractor )
        {
            ts->printf(cvtest::TS::LOG, "Descriptor extractor is empty.\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }

        emptyDataTest();
        regressionTest();

        ts->set_failed_test_info( cvtest::TS::OK );
    }

    virtual Mat readDescriptors()
    {
        Mat res = readMatFromBin( string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
        return res;
    }

    virtual bool writeDescriptors( Mat& descs )
    {
        writeMatInBin( descs,  string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
        return true;
    }

    string name;
    const DistanceType maxDist;
    Ptr<DescriptorExtractor> dextractor;
499
    int imgLoadMode;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    Distance distance;

private:
    CV_DescriptorExtractorTest& operator=(const CV_DescriptorExtractorTest&) { return *this; }
};

/*template<typename T, typename Distance>
class CV_CalonderDescriptorExtractorTest : public CV_DescriptorExtractorTest<Distance>
{
public:
    CV_CalonderDescriptorExtractorTest( const char* testName, float _normDif, float _prevTime ) :
            CV_DescriptorExtractorTest<Distance>( testName, _normDif, Ptr<DescriptorExtractor>(), _prevTime )
    {}

protected:
    virtual void createDescriptorExtractor()
    {
        CV_DescriptorExtractorTest<Distance>::dextractor =
                new CalonderDescriptorExtractor<T>( string(CV_DescriptorExtractorTest<Distance>::ts->get_data_path()) +
                                                    FEATURES2D_DIR + "/calonder_classifier.rtc");
    }
};*/

/****************************************************************************************\
*                       Algorithmic tests for descriptor matchers                        *
\****************************************************************************************/
class CV_DescriptorMatcherTest : public cvtest::BaseTest
{
public:
    CV_DescriptorMatcherTest( const string& _name, const Ptr<DescriptorMatcher>& _dmatcher, float _badPart ) :
        badPart(_badPart), name(_name), dmatcher(_dmatcher)
        {}
protected:
    static const int dim = 500;
    static const int queryDescCount = 300; // must be even number because we split train data in some cases in two
    static const int countFactor = 4; // do not change it
    const float badPart;

    virtual void run( int );
    void generateData( Mat& query, Mat& train );

    void emptyDataTest();
    void matchTest( const Mat& query, const Mat& train );
    void knnMatchTest( const Mat& query, const Mat& train );
    void radiusMatchTest( const Mat& query, const Mat& train );

    string name;
    Ptr<DescriptorMatcher> dmatcher;

private:
    CV_DescriptorMatcherTest& operator=(const CV_DescriptorMatcherTest&) { return *this; }
};

void CV_DescriptorMatcherTest::emptyDataTest()
{
    assert( !dmatcher.empty() );
    Mat queryDescriptors, trainDescriptors, mask;
    vector<Mat> trainDescriptorCollection, masks;
    vector<DMatch> matches;
    vector<vector<DMatch> > vmatches;

    try
    {
        dmatcher->match( queryDescriptors, trainDescriptors, matches, mask );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (1).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->knnMatch( queryDescriptors, trainDescriptors, vmatches, 2, mask );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (1).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->radiusMatch( queryDescriptors, trainDescriptors, vmatches, 10.f, mask );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (1).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->add( trainDescriptorCollection );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "add() on empty descriptors must not generate exception.\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->match( queryDescriptors, matches, masks );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (2).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->knnMatch( queryDescriptors, vmatches, 2, masks );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (2).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

    try
    {
        dmatcher->radiusMatch( queryDescriptors, vmatches, 10.f, masks );
    }
    catch(...)
    {
        ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (2).\n" );
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
    }

}

void CV_DescriptorMatcherTest::generateData( Mat& query, Mat& train )
{
    RNG& rng = theRNG();

    // Generate query descriptors randomly.
    // Descriptor vector elements are integer values.
    Mat buf( queryDescCount, dim, CV_32SC1 );
    rng.fill( buf, RNG::UNIFORM, Scalar::all(0), Scalar(3) );
    buf.convertTo( query, CV_32FC1 );

    // Generate train decriptors as follows:
    // copy each query descriptor to train set countFactor times
    // and perturb some one element of the copied descriptors in
    // in ascending order. General boundaries of the perturbation
    // are (0.f, 1.f).
    train.create( query.rows*countFactor, query.cols, CV_32FC1 );
    float step = 1.f / countFactor;
    for( int qIdx = 0; qIdx < query.rows; qIdx++ )
    {
        Mat queryDescriptor = query.row(qIdx);
        for( int c = 0; c < countFactor; c++ )
        {
            int tIdx = qIdx * countFactor + c;
            Mat trainDescriptor = train.row(tIdx);
            queryDescriptor.copyTo( trainDescriptor );
            int elem = rng(dim);
            float diff = rng.uniform( step*c, step*(c+1) );
            trainDescriptor.at<float>(0, elem) += diff;
        }
    }
}

void CV_DescriptorMatcherTest::matchTest( const Mat& query, const Mat& train )
{
    dmatcher->clear();

    // test const version of match()
    {
        vector<DMatch> matches;
        dmatcher->match( query, train, matches );

        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }
        else
        {
            int badCount = 0;
            for( size_t i = 0; i < matches.size(); i++ )
            {
                DMatch match = matches[i];
                if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
                    badCount++;
            }
            if( (float)badCount > (float)queryDescCount*badPart )
            {
                ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (1).\n",
                            (float)badCount/(float)queryDescCount );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
            }
        }
    }

    // test version of match() with add()
    {
        vector<DMatch> matches;
        // make add() twice to test such case
        dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
        dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
        // prepare masks (make first nearest match illegal)
        vector<Mat> masks(2);
        for(int mi = 0; mi < 2; mi++ )
        {
            masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
            for( int di = 0; di < queryDescCount/2; di++ )
                masks[mi].col(di*countFactor).setTo(Scalar::all(0));
        }

        dmatcher->match( query, matches, masks );

        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (2).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }
        else
        {
            int badCount = 0;
            for( size_t i = 0; i < matches.size(); i++ )
            {
                DMatch match = matches[i];
                int shift = dmatcher->isMaskSupported() ? 1 : 0;
                {
                    if( i < queryDescCount/2 )
                    {
                        if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + shift) || (match.imgIdx != 0) )
                            badCount++;
                    }
                    else
                    {
                        if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + shift) || (match.imgIdx != 1) )
                            badCount++;
                    }
                }
            }
            if( (float)badCount > (float)queryDescCount*badPart )
            {
                ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (2).\n",
                            (float)badCount/(float)queryDescCount );
                ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
            }
        }
    }
}

void CV_DescriptorMatcherTest::knnMatchTest( const Mat& query, const Mat& train )
{
    dmatcher->clear();

    // test const version of knnMatch()
    {
        const int knn = 3;

        vector<vector<DMatch> > matches;
        dmatcher->knnMatch( query, train, matches, knn );

        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }
        else
        {
            int badCount = 0;
            for( size_t i = 0; i < matches.size(); i++ )
            {
                if( (int)matches[i].size() != knn )
                    badCount++;
                else
                {
                    int localBadCount = 0;
                    for( int k = 0; k < knn; k++ )
                    {
                        DMatch match = matches[i][k];
                        if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor+k) || (match.imgIdx != 0) )
                            localBadCount++;
                    }
                    badCount += localBadCount > 0 ? 1 : 0;
                }
            }
            if( (float)badCount > (float)queryDescCount*badPart )
            {
                ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (1).\n",
                            (float)badCount/(float)queryDescCount );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
            }
        }
    }

    // test version of knnMatch() with add()
    {
        const int knn = 2;
        vector<vector<DMatch> > matches;
        // make add() twice to test such case
        dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
        dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
        // prepare masks (make first nearest match illegal)
        vector<Mat> masks(2);
        for(int mi = 0; mi < 2; mi++ )
        {
            masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
            for( int di = 0; di < queryDescCount/2; di++ )
                masks[mi].col(di*countFactor).setTo(Scalar::all(0));
        }

        dmatcher->knnMatch( query, matches, knn, masks );

        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (2).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }
        else
        {
            int badCount = 0;
            int shift = dmatcher->isMaskSupported() ? 1 : 0;
            for( size_t i = 0; i < matches.size(); i++ )
            {
                if( (int)matches[i].size() != knn )
                    badCount++;
                else
                {
                    int localBadCount = 0;
                    for( int k = 0; k < knn; k++ )
                    {
                        DMatch match = matches[i][k];
                        {
                            if( i < queryDescCount/2 )
                            {
                                if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
                                    (match.imgIdx != 0) )
                                    localBadCount++;
                            }
                            else
                            {
                                if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
                                    (match.imgIdx != 1) )
                                    localBadCount++;
                            }
                        }
                    }
                    badCount += localBadCount > 0 ? 1 : 0;
                }
            }
            if( (float)badCount > (float)queryDescCount*badPart )
            {
                ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (2).\n",
                            (float)badCount/(float)queryDescCount );
                ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
            }
        }
    }
}

void CV_DescriptorMatcherTest::radiusMatchTest( const Mat& query, const Mat& train )
{
    dmatcher->clear();
    // test const version of match()
    {
        const float radius = 1.f/countFactor;
        vector<vector<DMatch> > matches;
        dmatcher->radiusMatch( query, train, matches, radius );

        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }
        else
        {
            int badCount = 0;
            for( size_t i = 0; i < matches.size(); i++ )
            {
                if( (int)matches[i].size() != 1 )
                    badCount++;
                else
                {
                    DMatch match = matches[i][0];
                    if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
                        badCount++;
                }
            }
            if( (float)badCount > (float)queryDescCount*badPart )
            {
                ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (1).\n",
                            (float)badCount/(float)queryDescCount );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
            }
        }
    }

    // test version of match() with add()
    {
        int n = 3;
        const float radius = 1.f/countFactor * n;
        vector<vector<DMatch> > matches;
        // make add() twice to test such case
        dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
        dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
        // prepare masks (make first nearest match illegal)
        vector<Mat> masks(2);
        for(int mi = 0; mi < 2; mi++ )
        {
            masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
            for( int di = 0; di < queryDescCount/2; di++ )
                masks[mi].col(di*countFactor).setTo(Scalar::all(0));
        }

        dmatcher->radiusMatch( query, matches, radius, masks );

        //int curRes = cvtest::TS::OK;
        if( (int)matches.size() != queryDescCount )
        {
            ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        }

        int badCount = 0;
        int shift = dmatcher->isMaskSupported() ? 1 : 0;
        int needMatchCount = dmatcher->isMaskSupported() ? n-1 : n;
        for( size_t i = 0; i < matches.size(); i++ )
        {
            if( (int)matches[i].size() != needMatchCount )
                badCount++;
            else
            {
                int localBadCount = 0;
                for( int k = 0; k < needMatchCount; k++ )
                {
                    DMatch match = matches[i][k];
                    {
                        if( i < queryDescCount/2 )
                        {
                            if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
                                (match.imgIdx != 0) )
                                localBadCount++;
                        }
                        else
                        {
                            if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
                                (match.imgIdx != 1) )
                                localBadCount++;
                        }
                    }
                }
                badCount += localBadCount > 0 ? 1 : 0;
            }
        }
        if( (float)badCount > (float)queryDescCount*badPart )
        {
            ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (2).\n",
                        (float)badCount/(float)queryDescCount );
            ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
        }
    }
}

void CV_DescriptorMatcherTest::run( int )
{
    Mat query, train;
    generateData( query, train );

    matchTest( query, train );

    knnMatchTest( query, train );

    radiusMatchTest( query, train );
}

/****************************************************************************************\
*                                Tests registrations                                     *
\****************************************************************************************/

/*
 * Detectors
 */


TEST( Features2d_Detector_SIFT, regression )
{
984
    CV_FeatureDetectorTest test( "detector-sift", SIFT::create() );
985 986 987 988 989
    test.safe_run();
}

TEST( Features2d_Detector_SURF, regression )
{
990
    CV_FeatureDetectorTest test( "detector-surf", SURF::create() );
991 992 993
    test.safe_run();
}

994 995
TEST( Features2d_Detector_STAR, regression )
{
996
    CV_FeatureDetectorTest test( "detector-star", StarDetector::create() );
997 998 999
    test.safe_run();
}

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
TEST( Features2d_Detector_Harris_Laplace, regression )
{
    CV_FeatureDetectorTest test( "detector-harris-laplace", HarrisLaplaceFeatureDetector::create() );
    test.safe_run();
}

TEST( Features2d_Detector_Harris_Laplace_Affine_Keypoint_Invariance, regression )
{
    CV_FeatureDetectorTest test( "detector-harris-laplace", AffineFeature2D::create(HarrisLaplaceFeatureDetector::create()));
    test.safe_run();
}

TEST( Features2d_Detector_Harris_Laplace_Affine, regression )
{
    CV_FeatureDetectorTest test( "detector-harris-laplace-affine", AffineFeature2D::create(HarrisLaplaceFeatureDetector::create()));
    test.safe_run();
}

1018 1019 1020 1021 1022
/*
 * Descriptors
 */
TEST( Features2d_DescriptorExtractor_SIFT, regression )
{
1023
    CV_DescriptorExtractorTest<L1<float> > test( "descriptor-sift", 1.0f,
1024
                                                SIFT::create() );
1025 1026 1027 1028 1029 1030
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_SURF, regression )
{
    CV_DescriptorExtractorTest<L2<float> > test( "descriptor-surf",  0.05f,
1031
                                                SURF::create() );
1032 1033 1034
    test.safe_run();
}

1035 1036 1037 1038 1039 1040 1041
TEST( Features2d_DescriptorExtractor_DAISY, regression )
{
    CV_DescriptorExtractorTest<L2<float> > test( "descriptor-daisy",  0.05f,
                                                DAISY::create() );
    test.safe_run();
}

1042
TEST( Features2d_DescriptorExtractor_FREAK, regression )
1043
{
1044 1045
    // TODO adjust the parameters below
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-freak",  (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
1046
                                             FREAK::create(), IMREAD_GRAYSCALE );
1047 1048 1049
    test.safe_run();
}

1050
TEST( Features2d_DescriptorExtractor_BRIEF, regression )
1051
{
1052
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-brief",  1,
1053
                                             BriefDescriptorExtractor::create() );
1054 1055 1056
    test.safe_run();
}

Alexander Alekhin's avatar
Alexander Alekhin committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
template <int threshold = 0>
struct LUCIDEqualityDistance
{
    typedef unsigned char ValueType;
    typedef int ResultType;

    ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
    {
        int res = 0;
        for (int i = 0; i < size; i++)
        {
            if (threshold == 0)
                res += (a[i] != b[i]) ? 1 : 0;
            else
                res += abs(a[i] - b[i]) > threshold ? 1 : 0;
        }
        return res;
    }
};

Str3iber's avatar
Str3iber committed
1077 1078
TEST( Features2d_DescriptorExtractor_LUCID, regression )
{
Alexander Alekhin's avatar
Alexander Alekhin committed
1079 1080 1081 1082
    CV_DescriptorExtractorTest< LUCIDEqualityDistance<1/*used blur is not bit-exact*/> > test(
            "descriptor-lucid", 2,
            LUCID::create(1, 2)
    );
Str3iber's avatar
Str3iber committed
1083 1084 1085
    test.safe_run();
}

1086 1087 1088 1089 1090 1091 1092
TEST( Features2d_DescriptorExtractor_LATCH, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-latch",  1,
                                             LATCH::create() );
    test.safe_run();
}

Balint Cristian's avatar
Balint Cristian committed
1093 1094 1095 1096 1097 1098
TEST( Features2d_DescriptorExtractor_VGG, regression )
{
    CV_DescriptorExtractorTest<L2<float> > test( "descriptor-vgg",  0.03f,
                                             VGG::create() );
    test.safe_run();
}
Str3iber's avatar
Str3iber committed
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
TEST( Features2d_DescriptorExtractor_BGM, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-bgm",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
                                            BoostDesc::create(BoostDesc::BGM) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_BGM_HARD, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-bgm_hard",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
                                            BoostDesc::create(BoostDesc::BGM_HARD) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_BGM_BILINEAR, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-bgm_bilinear",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)15.f,
                                            BoostDesc::create(BoostDesc::BGM_BILINEAR) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_LBGM, regression )
{
    CV_DescriptorExtractorTest<L2<float> > test( "descriptor-boostdesc-lbgm",
                                           1.0f,
                                           BoostDesc::create(BoostDesc::LBGM) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_BINBOOST_64, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-binboost_64",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
                                            BoostDesc::create(BoostDesc::BINBOOST_64) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_BINBOOST_128, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-binboost_128",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
                                            BoostDesc::create(BoostDesc::BINBOOST_128) );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_BINBOOST_256, regression )
{
    CV_DescriptorExtractorTest<Hamming> test( "descriptor-boostdesc-binboost_256",
                                            (CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
                                            BoostDesc::create(BoostDesc::BINBOOST_256) );
    test.safe_run();
}

1156

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
/*#if CV_SSE2
TEST( Features2d_DescriptorExtractor_Calonder_uchar, regression )
{
    CV_CalonderDescriptorExtractorTest<uchar, L2<uchar> > test( "descriptor-calonder-uchar",
                                                                std::numeric_limits<float>::epsilon() + 1,
                                                                0.0132175f );
    test.safe_run();
}

TEST( Features2d_DescriptorExtractor_Calonder_float, regression )
{
    CV_CalonderDescriptorExtractorTest<float, L2<float> > test( "descriptor-calonder-float",
                                                                std::numeric_limits<float>::epsilon(),
                                                                0.0221308f );
    test.safe_run();
}
#endif*/ // CV_SSE2

TEST(Features2d_BruteForceDescriptorMatcher_knnMatch, regression)
{
    const int sz = 100;
    const int k = 3;

1180
    Ptr<DescriptorExtractor> ext = SURF::create();
1181 1182
    ASSERT_TRUE(ext != NULL);

1183
    Ptr<FeatureDetector> det = SURF::create();
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    //"%YAML:1.0\nhessianThreshold: 8000.\noctaves: 3\noctaveLayers: 4\nupright: 0\n"
    ASSERT_TRUE(det != NULL);

    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce");
    ASSERT_TRUE(matcher != NULL);

    Mat imgT(sz, sz, CV_8U, Scalar(255));
    line(imgT, Point(20, sz/2), Point(sz-21, sz/2), Scalar(100), 2);
    line(imgT, Point(sz/2, 20), Point(sz/2, sz-21), Scalar(100), 2);
    vector<KeyPoint> kpT;
    kpT.push_back( KeyPoint(50, 50, 16, 0, 20000, 1, -1) );
    kpT.push_back( KeyPoint(42, 42, 16, 160, 10000, 1, -1) );
    Mat descT;
    ext->compute(imgT, kpT, descT);

    Mat imgQ(sz, sz, CV_8U, Scalar(255));
    line(imgQ, Point(30, sz/2), Point(sz-31, sz/2), Scalar(100), 3);
    line(imgQ, Point(sz/2, 30), Point(sz/2, sz-31), Scalar(100), 3);
    vector<KeyPoint> kpQ;
    det->detect(imgQ, kpQ);
    Mat descQ;
    ext->compute(imgQ, kpQ, descQ);

    vector<vector<DMatch> > matches;

    matcher->knnMatch(descQ, descT, matches, k);

    //cout << "\nBest " << k << " matches to " << descT.rows << " train desc-s." << endl;
    ASSERT_EQ(descQ.rows, static_cast<int>(matches.size()));
    for(size_t i = 0; i<matches.size(); i++)
    {
        //cout << "\nmatches[" << i << "].size()==" << matches[i].size() << endl;
        ASSERT_GE(min(k, descT.rows), static_cast<int>(matches[i].size()));
        for(size_t j = 0; j<matches[i].size(); j++)
        {
            //cout << "\t" << matches[i][j].queryIdx << " -> " << matches[i][j].trainIdx << endl;
            ASSERT_EQ(matches[i][j].queryIdx, static_cast<int>(i));
        }
    }
}

/*TEST(Features2d_DescriptorExtractorParamTest, regression)
{
    Ptr<DescriptorExtractor> s = DescriptorExtractor::create("SURF");
    ASSERT_STREQ(s->paramHelp("extended").c_str(), "");
}
*/

class CV_DetectPlanarTest : public cvtest::BaseTest
{
public:
1235 1236
    CV_DetectPlanarTest(const string& _fname, int _min_ninliers, const Ptr<Feature2D>& _f2d)
    : fname(_fname), min_ninliers(_min_ninliers), f2d(_f2d) {}
1237 1238 1239 1240

protected:
    void run(int)
    {
1241
        if(f2d.empty())
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
            return;
        string path = string(ts->get_data_path()) + "detectors_descriptors_evaluation/planar/";
        string imgname1 = path + "box.png";
        string imgname2 = path + "box_in_scene.png";
        Mat img1 = imread(imgname1, 0);
        Mat img2 = imread(imgname2, 0);
        if( img1.empty() || img2.empty() )
        {
            ts->printf( cvtest::TS::LOG, "missing %s and/or %s\n", imgname1.c_str(), imgname2.c_str());
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }
        vector<KeyPoint> kpt1, kpt2;
        Mat d1, d2;
1256 1257
        f2d->detectAndCompute(img1, Mat(), kpt1, d1);
        f2d->detectAndCompute(img1, Mat(), kpt2, d2);
1258 1259 1260 1261 1262 1263
        for( size_t i = 0; i < kpt1.size(); i++ )
            CV_Assert(kpt1[i].response > 0 );
        for( size_t i = 0; i < kpt2.size(); i++ )
            CV_Assert(kpt2[i].response > 0 );

        vector<DMatch> matches;
1264
        BFMatcher(f2d->defaultNorm(), true).match(d1, d2, matches);
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

        vector<Point2f> pt1, pt2;
        for( size_t i = 0; i < matches.size(); i++ ) {
            pt1.push_back(kpt1[matches[i].queryIdx].pt);
            pt2.push_back(kpt2[matches[i].trainIdx].pt);
        }

        Mat inliers, H = findHomography(pt1, pt2, RANSAC, 10, inliers);
        int ninliers = countNonZero(inliers);

        if( ninliers < min_ninliers )
        {
            ts->printf( cvtest::TS::LOG, "too little inliers (%d) vs expected %d\n", ninliers, min_ninliers);
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }
    }

    string fname;
    int min_ninliers;
1285
    Ptr<Feature2D> f2d;
1286 1287
};

1288 1289
TEST(Features2d_SIFTHomographyTest, regression) { CV_DetectPlanarTest test("SIFT", 80, SIFT::create()); test.safe_run(); }
TEST(Features2d_SURFHomographyTest, regression) { CV_DetectPlanarTest test("SURF", 80, SURF::create()); test.safe_run(); }
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

class FeatureDetectorUsingMaskTest : public cvtest::BaseTest
{
public:
    FeatureDetectorUsingMaskTest(const Ptr<FeatureDetector>& featureDetector) :
        featureDetector_(featureDetector)
    {
        CV_Assert(featureDetector_);
    }

protected:

    void run(int)
    {
        const int nStepX = 2;
        const int nStepY = 2;

        const string imageFilename = string(ts->get_data_path()) + "/features2d/tsukuba.png";

        Mat image = imread(imageFilename);
        if(image.empty())
        {
            ts->printf(cvtest::TS::LOG, "Image %s can not be read.\n", imageFilename.c_str());
            ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
            return;
        }

        Mat mask(image.size(), CV_8U);

        const int stepX = image.size().width / nStepX;
        const int stepY = image.size().height / nStepY;

        vector<KeyPoint> keyPoints;
        vector<Point2f> points;
        for(int i=0; i<nStepX; ++i)
            for(int j=0; j<nStepY; ++j)
            {

                mask.setTo(0);
                Rect whiteArea(i * stepX, j * stepY, stepX, stepY);
                mask(whiteArea).setTo(255);

                featureDetector_->detect(image, keyPoints, mask);
                KeyPoint::convert(keyPoints, points);

                for(size_t k=0; k<points.size(); ++k)
                {
                    if ( !whiteArea.contains(points[k]) )
                    {
                        ts->printf(cvtest::TS::LOG, "The feature point is outside of the mask.");
                        ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
                        return;
                    }
                }
            }

        ts->set_failed_test_info( cvtest::TS::OK );
    }

    Ptr<FeatureDetector> featureDetector_;
};

TEST(Features2d_SIFT_using_mask, regression)
{
1354
    FeatureDetectorUsingMaskTest test(SIFT::create());
1355 1356 1357 1358 1359
    test.safe_run();
}

TEST(DISABLED_Features2d_SURF_using_mask, regression)
{
1360
    FeatureDetectorUsingMaskTest test(SURF::create());
1361 1362
    test.safe_run();
}
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390

TEST( XFeatures2d_DescriptorExtractor, batch )
{
    string path = string(cvtest::TS::ptr()->get_data_path() + "detectors_descriptors_evaluation/images_datasets/graf");
    vector<Mat> imgs, descriptors;
    vector<vector<KeyPoint> > keypoints;
    int i, n = 6;
    Ptr<SIFT> sift = SIFT::create();

    for( i = 0; i < n; i++ )
    {
        string imgname = format("%s/img%d.png", path.c_str(), i+1);
        Mat img = imread(imgname, 0);
        imgs.push_back(img);
    }

    sift->detect(imgs, keypoints);
    sift->compute(imgs, keypoints, descriptors);

    ASSERT_EQ((int)keypoints.size(), n);
    ASSERT_EQ((int)descriptors.size(), n);

    for( i = 0; i < n; i++ )
    {
        EXPECT_GT((int)keypoints[i].size(), 100);
        EXPECT_GT(descriptors[i].rows, 100);
    }
}