test_cameracalibration.cpp 95.2 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
/*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"
43
#include "opencv2/stereo.hpp"
44

A
Alexander Alekhin 已提交
45
namespace opencv_test { namespace {
46

47 48 49 50 51 52 53
#if 0
class CV_ProjectPointsTest : public cvtest::ArrayTest
{
public:
    CV_ProjectPointsTest();

protected:
54
    int read_params( const cv::FileStorage& fs );
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
    void fill_array( int test_case_idx, int i, int j, Mat& arr );
    int prepare_test_case( int test_case_idx );
    void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
    double get_success_error_level( int test_case_idx, int i, int j );
    void run_func();
    void prepare_to_validation( int );

    bool calc_jacobians;
};


CV_ProjectPointsTest::CV_ProjectPointsTest()
    : cvtest::ArrayTest( "3d-ProjectPoints", "cvProjectPoints2", "" )
{
    test_array[INPUT].push_back(NULL);  // rotation vector
    test_array[OUTPUT].push_back(NULL); // rotation matrix
    test_array[OUTPUT].push_back(NULL); // jacobian (J)
    test_array[OUTPUT].push_back(NULL); // rotation vector (backward transform result)
    test_array[OUTPUT].push_back(NULL); // inverse transform jacobian (J1)
    test_array[OUTPUT].push_back(NULL); // J*J1 (or J1*J) == I(3x3)
    test_array[REF_OUTPUT].push_back(NULL);
    test_array[REF_OUTPUT].push_back(NULL);
    test_array[REF_OUTPUT].push_back(NULL);
    test_array[REF_OUTPUT].push_back(NULL);
    test_array[REF_OUTPUT].push_back(NULL);

    element_wise_relative_error = false;
    calc_jacobians = false;
}


86
int CV_ProjectPointsTest::read_params( const cv::FileStorage& fs )
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
{
    int code = cvtest::ArrayTest::read_params( fs );
    return code;
}


void CV_ProjectPointsTest::get_test_array_types_and_sizes(
    int /*test_case_idx*/, vector<vector<Size> >& sizes, vector<vector<int> >& types )
{
    RNG& rng = ts->get_rng();
    int depth = cvtest::randInt(rng) % 2 == 0 ? CV_32F : CV_64F;
    int i, code;

    code = cvtest::randInt(rng) % 3;
    types[INPUT][0] = CV_MAKETYPE(depth, 1);

    if( code == 0 )
    {
        sizes[INPUT][0] = cvSize(1,1);
        types[INPUT][0] = CV_MAKETYPE(depth, 3);
    }
    else if( code == 1 )
        sizes[INPUT][0] = cvSize(3,1);
    else
        sizes[INPUT][0] = cvSize(1,3);

    sizes[OUTPUT][0] = cvSize(3, 3);
    types[OUTPUT][0] = CV_MAKETYPE(depth, 1);

    types[OUTPUT][1] = CV_MAKETYPE(depth, 1);

    if( cvtest::randInt(rng) % 2 )
        sizes[OUTPUT][1] = cvSize(3,9);
    else
        sizes[OUTPUT][1] = cvSize(9,3);

    types[OUTPUT][2] = types[INPUT][0];
    sizes[OUTPUT][2] = sizes[INPUT][0];

    types[OUTPUT][3] = types[OUTPUT][1];
    sizes[OUTPUT][3] = cvSize(sizes[OUTPUT][1].height, sizes[OUTPUT][1].width);

    types[OUTPUT][4] = types[OUTPUT][1];
    sizes[OUTPUT][4] = cvSize(3,3);

    calc_jacobians = 1;//cvtest::randInt(rng) % 3 != 0;
    if( !calc_jacobians )
        sizes[OUTPUT][1] = sizes[OUTPUT][3] = sizes[OUTPUT][4] = cvSize(0,0);

    for( i = 0; i < 5; i++ )
    {
        types[REF_OUTPUT][i] = types[OUTPUT][i];
        sizes[REF_OUTPUT][i] = sizes[OUTPUT][i];
    }
}


double CV_ProjectPointsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int j )
{
    return j == 4 ? 1e-2 : 1e-2;
}


void CV_ProjectPointsTest::fill_array( int /*test_case_idx*/, int /*i*/, int /*j*/, CvMat* arr )
{
    double r[3], theta0, theta1, f;
    CvMat _r = cvMat( arr->rows, arr->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(arr->type)), r );
    RNG& rng = ts->get_rng();

    r[0] = cvtest::randReal(rng)*CV_PI*2;
    r[1] = cvtest::randReal(rng)*CV_PI*2;
    r[2] = cvtest::randReal(rng)*CV_PI*2;

    theta0 = sqrt(r[0]*r[0] + r[1]*r[1] + r[2]*r[2]);
    theta1 = fmod(theta0, CV_PI*2);

    if( theta1 > CV_PI )
        theta1 = -(CV_PI*2 - theta1);

    f = theta1/(theta0 ? theta0 : 1);
    r[0] *= f;
    r[1] *= f;
    r[2] *= f;

    cvTsConvert( &_r, arr );
}


int CV_ProjectPointsTest::prepare_test_case( int test_case_idx )
{
    int code = cvtest::ArrayTest::prepare_test_case( test_case_idx );
    return code;
}


void CV_ProjectPointsTest::run_func()
{
    CvMat *v2m_jac = 0, *m2v_jac = 0;
    if( calc_jacobians )
    {
        v2m_jac = &test_mat[OUTPUT][1];
        m2v_jac = &test_mat[OUTPUT][3];
    }

    cvProjectPoints2( &test_mat[INPUT][0], &test_mat[OUTPUT][0], v2m_jac );
    cvProjectPoints2( &test_mat[OUTPUT][0], &test_mat[OUTPUT][2], m2v_jac );
}


void CV_ProjectPointsTest::prepare_to_validation( int /*test_case_idx*/ )
{
    const CvMat* vec = &test_mat[INPUT][0];
    CvMat* m = &test_mat[REF_OUTPUT][0];
    CvMat* vec2 = &test_mat[REF_OUTPUT][2];
    CvMat* v2m_jac = 0, *m2v_jac = 0;
    double theta0, theta1;

    if( calc_jacobians )
    {
        v2m_jac = &test_mat[REF_OUTPUT][1];
        m2v_jac = &test_mat[REF_OUTPUT][3];
    }


    cvTsProjectPoints( vec, m, v2m_jac );
    cvTsProjectPoints( m, vec2, m2v_jac );
    cvTsCopy( vec, vec2 );

215
    theta0 = cvtest::norm( cvarrtomat(vec2), 0, CV_L2 );
216 217 218 219 220 221 222 223 224
    theta1 = fmod( theta0, CV_PI*2 );

    if( theta1 > CV_PI )
        theta1 = -(CV_PI*2 - theta1);
    cvScale( vec2, vec2, theta1/(theta0 ? theta0 : 1) );

    if( calc_jacobians )
    {
        //cvInvert( v2m_jac, m2v_jac, CV_SVD );
225
        if( cvtest::norm(cvarrtomat(&test_mat[OUTPUT][3]), 0, CV_C) < 1000 )
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        {
            cvTsGEMM( &test_mat[OUTPUT][1], &test_mat[OUTPUT][3],
                      1, 0, 0, &test_mat[OUTPUT][4],
                      v2m_jac->rows == 3 ? 0 : CV_GEMM_A_T + CV_GEMM_B_T );
        }
        else
        {
            cvTsSetIdentity( &test_mat[OUTPUT][4], cvScalarAll(1.) );
            cvTsCopy( &test_mat[REF_OUTPUT][2], &test_mat[OUTPUT][2] );
        }
        cvTsSetIdentity( &test_mat[REF_OUTPUT][4], cvScalarAll(1.) );
    }
}


CV_ProjectPointsTest ProjectPoints_test;

#endif

// --------------------------------- CV_CameraCalibrationTest --------------------------------------------

247 248
typedef Matx33d RotMat;

249 250 251 252 253 254 255 256 257
class CV_CameraCalibrationTest : public cvtest::BaseTest
{
public:
    CV_CameraCalibrationTest();
    ~CV_CameraCalibrationTest();
    void clear();
protected:
    int compare(double* val, double* refVal, int len,
                double eps, const char* paramName);
258 259 260 261 262 263
    virtual void calibrate(Size imageSize,
        const std::vector<std::vector<Point2d> >& imagePoints,
        const std::vector<std::vector<Point3d> >& objectPoints,
        int iFixedPoint, Mat& distortionCoeffs, Mat& cameraMatrix, std::vector<Vec3d>& translationVectors,
        std::vector<RotMat>& rotationMatrices, std::vector<Point3d>& newObjPoints,
        std::vector<double>& stdDevs, std::vector<double>& perViewErrors,
264
        int flags ) = 0;
265 266 267 268
    virtual void project( const std::vector<Point3d>& objectPoints,
        const RotMat& rotationMatrix, const Vec3d& translationVector,
        const Mat& cameraMatrix, const Mat& distortion,
        std::vector<Point2d>& imagePoints ) = 0;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

    void run(int);
};

CV_CameraCalibrationTest::CV_CameraCalibrationTest()
{
}

CV_CameraCalibrationTest::~CV_CameraCalibrationTest()
{
    clear();
}

void CV_CameraCalibrationTest::clear()
{
A
Andrey Kamaev 已提交
284
    cvtest::BaseTest::clear();
285 286 287 288 289 290 291 292 293 294 295
}

int CV_CameraCalibrationTest::compare(double* val, double* ref_val, int len,
                                      double eps, const char* param_name )
{
    return cvtest::cmpEps2_64f( ts, val, ref_val, len, eps, param_name );
}

void CV_CameraCalibrationTest::run( int start_from )
{
    int code = cvtest::TS::OK;
296 297
    cv::String            filepath;
    cv::String            filename;
298

299 300 301
    std::vector<std::vector<Point2d> >  imagePoints;
    std::vector<std::vector<Point3d> >  objectPoints;
    std::vector<std::vector<Point2d> >  reprojectPoints;
302

303 304 305 306 307
    std::vector<Vec3d>        transVects;
    std::vector<RotMat>       rotMatrs;
    std::vector<Point3d>      newObjPoints;
    std::vector<double>       stdDevs;
    std::vector<double>       perViewErrors;
308

309 310 311 312 313
    std::vector<Vec3d>        goodTransVects;
    std::vector<RotMat>       goodRotMatrs;
    std::vector<Point3d>      goodObjPoints;
    std::vector<double>       goodPerViewErrors;
    std::vector<double>       goodStdDevs;
314

315 316 317
    Mat             cameraMatrix;
    Mat             distortion = Mat::zeros(1, 5, CV_64F);
    Mat             goodDistortion = Mat::zeros(1, 5, CV_64F);
318 319 320 321 322 323 324

    FILE*           file = 0;
    FILE*           datafile = 0;
    int             i,j;
    int             currImage;
    int             currPoint;
    char            i_dat_file[100];
325

326
    int progress = 0;
327
    int values_read = -1;
328

329 330 331
    filepath = cv::format("%scv/cameracalibration/", ts->get_data_path().c_str() );
    filename = cv::format("%sdatafiles.txt", filepath.c_str() );
    datafile = fopen( filename.c_str(), "r" );
332 333
    if( datafile == 0 )
    {
334
        ts->printf( cvtest::TS::LOG, "Could not open file with list of test files: %s\n", filename.c_str() );
335
        code = cvtest::TS::FAIL_MISSING_TEST_DATA;
336 337
        ts->set_failed_test_info( code );
        return;
338 339
    }

340
    int numTests = 0;
341 342
    values_read = fscanf(datafile,"%d",&numTests);
    CV_Assert(values_read == 1);
343

344
    for( int currTest = start_from; currTest < numTests; currTest++ )
345
    {
346 347
        values_read = fscanf(datafile,"%s",i_dat_file);
        CV_Assert(values_read == 1);
348 349
        filename = cv::format("%s%s", filepath.c_str(), i_dat_file);
        file = fopen(filename.c_str(),"r");
350 351 352 353 354 355

        ts->update_context( this, currTest, true );

        if( file == 0 )
        {
            ts->printf( cvtest::TS::LOG,
356
                "Can't open current test file: %s\n",filename.c_str());
357 358 359
            if( numTests == 1 )
            {
                code = cvtest::TS::FAIL_MISSING_TEST_DATA;
360
                break;
361 362 363 364
            }
            continue; // if there is more than one test, just skip the test
        }

365
        Size imageSize;
366 367
        values_read = fscanf(file,"%d %d\n",&(imageSize.width),&(imageSize.height));
        CV_Assert(values_read == 2);
368 369 370 371
        if( imageSize.width <= 0 || imageSize.height <= 0 )
        {
            ts->printf( cvtest::TS::LOG, "Image size in test file is incorrect\n" );
            code = cvtest::TS::FAIL_INVALID_TEST_DATA;
372
            break;
373 374 375
        }

        /* Read etalon size */
376
        Size etalonSize;
377 378
        values_read = fscanf(file,"%d %d\n",&(etalonSize.width),&(etalonSize.height));
        CV_Assert(values_read == 2);
379 380 381 382
        if( etalonSize.width <= 0 || etalonSize.height <= 0 )
        {
            ts->printf( cvtest::TS::LOG, "Pattern size in test file is incorrect\n" );
            code = cvtest::TS::FAIL_INVALID_TEST_DATA;
383
            break;
384 385
        }

386
        int numPoints = etalonSize.width * etalonSize.height;
387 388

        /* Read number of images */
389
        int numImages = 0;
390 391
        values_read = fscanf(file,"%d\n",&numImages);
        CV_Assert(values_read == 1);
392 393 394 395
        if( numImages <=0 )
        {
            ts->printf( cvtest::TS::LOG, "Number of images in test file is incorrect\n");
            code = cvtest::TS::FAIL_INVALID_TEST_DATA;
396
            break;
397 398
        }

399
        /* Read calibration flags */
400
        int calibFlags = 0;
401 402 403 404 405 406 407 408
        values_read = fscanf(file,"%d\n",&calibFlags);
        CV_Assert(values_read == 1);

        /* Read index of the fixed point */
        int iFixedPoint;
        values_read = fscanf(file,"%d\n",&iFixedPoint);
        CV_Assert(values_read == 1);

409
        /* Need to allocate memory */
410 411 412
        imagePoints.resize(numImages);
        objectPoints.resize(numImages);
        reprojectPoints.resize(numImages);
413 414
        for( currImage = 0; currImage < numImages; currImage++ )
        {
415 416 417
            imagePoints[currImage].resize(numPoints);
            objectPoints[currImage].resize(numPoints);
            reprojectPoints[currImage].resize(numPoints);
418 419
        }

420 421 422 423 424 425 426 427 428 429 430 431 432 433
        transVects.resize(numImages);
        rotMatrs.resize(numImages);
        newObjPoints.resize(numPoints);
        stdDevs.resize(CALIB_NINTRINSIC + 6*numImages + 3*numPoints);
        perViewErrors.resize(numImages);

        goodTransVects.resize(numImages);
        goodRotMatrs.resize(numImages);
        goodObjPoints.resize(numPoints);
        goodPerViewErrors.resize(numImages);

        int nstddev = CALIB_NINTRINSIC + 6*numImages + 3*numPoints;
        goodStdDevs.resize(nstddev);

434 435 436 437 438
        for( currImage = 0; currImage < numImages; currImage++ )
        {
            for( currPoint = 0; currPoint < numPoints; currPoint++ )
            {
                double x,y,z;
439 440
                values_read = fscanf(file,"%lf %lf %lf\n",&x,&y,&z);
                CV_Assert(values_read == 3);
441

442 443 444
                objectPoints[currImage][currPoint].x = x;
                objectPoints[currImage][currPoint].y = y;
                objectPoints[currImage][currPoint].z = z;
445 446 447 448 449 450 451 452 453
            }
        }

        /* Read image points */
        for( currImage = 0; currImage < numImages; currImage++ )
        {
            for( currPoint = 0; currPoint < numPoints; currPoint++ )
            {
                double x,y;
454 455
                values_read = fscanf(file,"%lf %lf\n",&x,&y);
                CV_Assert(values_read == 2);
456

457 458
                imagePoints[currImage][currPoint].x = x;
                imagePoints[currImage][currPoint].y = y;
459 460 461 462 463 464 465
            }
        }

        /* Read good data computed before */

        /* Focal lengths */
        double goodFcx,goodFcy;
466 467
        values_read = fscanf(file,"%lf %lf",&goodFcx,&goodFcy);
        CV_Assert(values_read == 2);
468 469 470

        /* Principal points */
        double goodCx,goodCy;
471 472
        values_read = fscanf(file,"%lf %lf",&goodCx,&goodCy);
        CV_Assert(values_read == 2);
473 474 475

        /* Read distortion */

476 477 478 479
        for( i = 0; i < 4; i++ )
        {
            values_read = fscanf(file,"%lf",&goodDistortion.at<double>(i)); CV_Assert(values_read == 1);
        }
480

I
typos  
Ilya Lavrenov 已提交
481
        /* Read good Rot matrices */
482 483 484 485
        for( currImage = 0; currImage < numImages; currImage++ )
        {
            for( i = 0; i < 3; i++ )
                for( j = 0; j < 3; j++ )
486
                {
K
Kataev Victor 已提交
487 488
                    // Yes, load with transpose
                    values_read = fscanf(file, "%lf", &goodRotMatrs[currImage].val[j*3+i]);
489 490
                    CV_Assert(values_read == 1);
                }
491 492 493 494 495 496
        }

        /* Read good Trans vectors */
        for( currImage = 0; currImage < numImages; currImage++ )
        {
            for( i = 0; i < 3; i++ )
497
            {
498
                values_read = fscanf(file, "%lf", &goodTransVects[currImage].val[i]);
499 500
                CV_Assert(values_read == 1);
            }
501 502
        }

503 504 505 506
        bool releaseObject = iFixedPoint > 0 && iFixedPoint < numPoints - 1;
        /* Read good refined 3D object points */
        if( releaseObject )
        {
507
            for( i = 0; i < numPoints; i++ )
508 509 510
            {
                for( j = 0; j < 3; j++ )
                {
511
                    values_read = fscanf(file, "%lf", &goodObjPoints[i].x + j);
512 513 514 515 516
                    CV_Assert(values_read == 1);
                }
            }
        }

517
        /* Read good stdDeviations */
518
        for (i = 0; i < CALIB_NINTRINSIC + numImages*6; i++)
519
        {
520
            values_read = fscanf(file, "%lf", &goodStdDevs[i]);
521 522
            CV_Assert(values_read == 1);
        }
523
        for( ; i < nstddev; i++ )
524
        {
525
            if( releaseObject )
526
            {
527
                values_read = fscanf(file, "%lf", &goodStdDevs[i]);
528 529
                CV_Assert(values_read == 1);
            }
530 531
            else
                goodStdDevs[i] = 0.0;
532
        }
533

534 535 536 537 538
        cameraMatrix = Mat::zeros(3, 3, CV_64F);
        cameraMatrix.at<double>(0, 0) = cameraMatrix.at<double>(1, 1) = 807.;
        cameraMatrix.at<double>(0, 2) = (imageSize.width - 1)*0.5;
        cameraMatrix.at<double>(1, 2) = (imageSize.height - 1)*0.5;
        cameraMatrix.at<double>(2, 2) = 1.;
539 540

        /* Now we can calibrate camera */
541
        calibrate(  imageSize,
542 543
                    imagePoints,
                    objectPoints,
544
                    iFixedPoint,
545 546 547 548
                    distortion,
                    cameraMatrix,
                    transVects,
                    rotMatrs,
549
                    newObjPoints,
550 551
                    stdDevs,
                    perViewErrors,
552 553 554 555 556
                    calibFlags );

        /* ---- Reproject points to the image ---- */
        for( currImage = 0; currImage < numImages; currImage++ )
        {
557 558
            if( releaseObject )
            {
559
                objectPoints[currImage] = newObjPoints;
560
            }
561 562 563
            project(  objectPoints[currImage],
                      rotMatrs[currImage],
                      transVects[currImage],
564 565
                      cameraMatrix,
                      distortion,
566
                      reprojectPoints[currImage]);
567 568 569 570 571 572 573 574
        }

        /* ----- Compute reprojection error ----- */
        double dx,dy;
        double rx,ry;

        for( currImage = 0; currImage < numImages; currImage++ )
        {
575 576
            double imageMeanDx = 0;
            double imageMeanDy = 0;
577 578
            for( currPoint = 0; currPoint < etalonSize.width * etalonSize.height; currPoint++ )
            {
579 580 581 582
                rx = reprojectPoints[currImage][currPoint].x;
                ry = reprojectPoints[currImage][currPoint].y;
                dx = rx - imagePoints[currImage][currPoint].x;
                dy = ry - imagePoints[currImage][currPoint].y;
583

584 585
                imageMeanDx += dx*dx;
                imageMeanDy += dy*dy;
586
            }
587 588 589 590 591 592 593
            goodPerViewErrors[currImage] = sqrt( (imageMeanDx + imageMeanDy) /
                                           (etalonSize.width * etalonSize.height));

            //only for c-version of test (it does not provides evaluation of perViewErrors
            //and returns zeros)
            if(perViewErrors[currImage] == 0.0)
                perViewErrors[currImage] = goodPerViewErrors[currImage];
594 595 596
        }

        /* ========= Compare parameters ========= */
597 598 599 600 601 602 603 604 605
        CV_Assert(cameraMatrix.type() == CV_64F && cameraMatrix.size() == Size(3, 3));
        CV_Assert(distortion.type() == CV_64F);

        Size dsz = distortion.size();
        CV_Assert(dsz == Size(4, 1) || dsz == Size(1, 4) || dsz == Size(5, 1) || dsz == Size(1, 5));

        /*std::cout << "cameraMatrix: " << cameraMatrix << "\n";
        std::cout << "curr distCoeffs: " << distortion << "\n";
        std::cout << "good distCoeffs: " << goodDistortion << "\n";*/
606 607

        /* ----- Compare focal lengths ----- */
608
        code = compare(&cameraMatrix.at<double>(0, 0), &goodFcx, 1, 0.1, "fx");
609
        if( code < 0 )
610
            break;
611

612
        code = compare(&cameraMatrix.at<double>(1, 1),&goodFcy, 1, 0.1, "fy");
613
        if( code < 0 )
614
            break;
615 616

        /* ----- Compare principal points ----- */
617
        code = compare(&cameraMatrix.at<double>(0,2), &goodCx, 1, 0.1, "cx");
618
        if( code < 0 )
619
            break;
620

621
        code = compare(&cameraMatrix.at<double>(1,2), &goodCy, 1, 0.1, "cy");
622
        if( code < 0 )
623
            break;
624 625

        /* ----- Compare distortion ----- */
626
        code = compare(&distortion.at<double>(0), &goodDistortion.at<double>(0), 4, 0.1, "[k1,k2,p1,p2]");
627
        if( code < 0 )
628
            break;
629 630

        /* ----- Compare rot matrixs ----- */
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
        CV_Assert(rotMatrs.size() == (size_t)numImages);
        CV_Assert(transVects.size() == (size_t)numImages);

        //code = compare(rotMatrs[0].val, goodRotMatrs[0].val, 9*numImages, 0.05, "rotation matrices");
        for( i = 0; i < numImages; i++ )
        {
            if( cv::norm(rotMatrs[i], goodRotMatrs[i], NORM_INF) > 0.05 )
            {
                printf("rot mats for frame #%d are very different\n", i);
                std::cout << "curr:\n" << rotMatrs[i] << std::endl;
                std::cout << "good:\n" << goodRotMatrs[i] << std::endl;

                code = TS::FAIL_BAD_ACCURACY;
                break;
            }
        }
647
        if( code < 0 )
648
            break;
649 650

        /* ----- Compare rot matrixs ----- */
651
        code = compare(transVects[0].val, goodTransVects[0].val, 3*numImages, 0.1, "translation vectors");
652
        if( code < 0 )
653
            break;
654

655 656 657
        /* ----- Compare refined 3D object points ----- */
        if( releaseObject )
        {
658
            code = compare(&newObjPoints[0].x, &goodObjPoints[0].x, 3*numPoints, 0.1, "refined 3D object points");
659
            if( code < 0 )
660
                break;
661 662
        }

663
        /* ----- Compare per view re-projection errors ----- */
664
        CV_Assert(perViewErrors.size() == (size_t)numImages);
K
Kataev Victor 已提交
665
        code = compare(&perViewErrors[0], &goodPerViewErrors[0], numImages, 0.1, "per view errors vector");
666
        if( code < 0 )
667
            break;
668 669

        /* ----- Compare standard deviations of parameters ----- */
670 671 672
        if( stdDevs.size() < (size_t)nstddev )
            stdDevs.resize(nstddev);
        for ( i = 0; i < nstddev; i++)
673 674 675 676
        {
            if(stdDevs[i] == 0.0)
                stdDevs[i] = goodStdDevs[i];
        }
677
        code = compare(&stdDevs[0], &goodStdDevs[0], nstddev, .5,
678
                       "stdDevs vector");
679
        if( code < 0 )
680
            break;
681

682
        /*if( maxDx > 1.0 )
683 684 685
        {
            ts->printf( cvtest::TS::LOG,
                      "Error in reprojection maxDx=%f > 1.0\n",maxDx);
686
            code = cvtest::TS::FAIL_BAD_ACCURACY; break;
687 688 689 690 691 692
        }

        if( maxDy > 1.0 )
        {
            ts->printf( cvtest::TS::LOG,
                      "Error in reprojection maxDy=%f > 1.0\n",maxDy);
693 694
            code = cvtest::TS::FAIL_BAD_ACCURACY; break;
        }*/
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

        progress = update_progress( progress, currTest, numTests, 0 );

        fclose(file);
        file = 0;
    }

    if( file )
        fclose(file);

    if( datafile )
        fclose(datafile);

    if( code < 0 )
        ts->set_failed_test_info( code );
}

// --------------------------------- CV_CameraCalibrationTest_CPP --------------------------------------------

class CV_CameraCalibrationTest_CPP : public CV_CameraCalibrationTest
{
public:
A
Andrey Kamaev 已提交
717
    CV_CameraCalibrationTest_CPP(){}
718
protected:
719 720 721 722 723 724 725 726 727 728 729
    virtual void calibrate(Size imageSize,
                           const std::vector<std::vector<Point2d> >& imagePoints,
                           const std::vector<std::vector<Point3d> >& objectPoints,
                           int iFixedPoint, Mat& distortionCoeffs, Mat& cameraMatrix, std::vector<Vec3d>& translationVectors,
                           std::vector<RotMat>& rotationMatrices, std::vector<Point3d>& newObjPoints,
                           std::vector<double>& stdDevs, std::vector<double>& perViewErrors,
                           int flags );
    virtual void project( const std::vector<Point3d>& objectPoints,
                         const RotMat& rotationMatrix, const Vec3d& translationVector,
                         const Mat& cameraMatrix, const Mat& distortion,
                         std::vector<Point2d>& imagePoints );
730 731
};

732 733 734 735 736 737 738
void CV_CameraCalibrationTest_CPP::calibrate(Size imageSize,
    const std::vector<std::vector<Point2d> >& _imagePoints,
    const std::vector<std::vector<Point3d> >& _objectPoints,
    int iFixedPoint, Mat& _distCoeffs, Mat& _cameraMatrix, std::vector<Vec3d>& translationVectors,
    std::vector<RotMat>& rotationMatrices, std::vector<Point3d>& newObjPoints,
    std::vector<double>& stdDevs, std::vector<double>& perViewErrors,
    int flags )
739
{
740 741
    int pointCount = (int)_imagePoints[0].size();
    size_t i, imageCount = _imagePoints.size();
A
Andrey Kamaev 已提交
742 743 744 745
    vector<vector<Point3f> > objectPoints( imageCount );
    vector<vector<Point2f> > imagePoints( imageCount );
    Mat cameraMatrix, distCoeffs(1,4,CV_64F,Scalar::all(0));
    vector<Mat> rvecs, tvecs;
746
    Mat newObjMat;
747
    Mat stdDevsMatInt, stdDevsMatExt;
748
    Mat stdDevsMatObj;
749
    Mat perViewErrorsMat;
A
Andrey Kamaev 已提交
750

751
    for( i = 0; i < imageCount; i++ )
A
Andrey Kamaev 已提交
752
    {
753 754
        Mat(_imagePoints[i]).convertTo(imagePoints[i], CV_32F);
        Mat(_objectPoints[i]).convertTo(objectPoints[i], CV_32F);
A
Andrey Kamaev 已提交
755 756
    }

757
    size_t nstddev0 = CALIB_NINTRINSIC + imageCount*6, nstddev1 = nstddev0 + _imagePoints[0].size()*3;
758
    for( i = nstddev0; i < nstddev1; i++ )
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    {
        stdDevs[i] = 0.0;
    }

    calibrateCameraRO( objectPoints,
                       imagePoints,
                       imageSize,
                       iFixedPoint,
                       cameraMatrix,
                       distCoeffs,
                       rvecs,
                       tvecs,
                       newObjMat,
                       stdDevsMatInt,
                       stdDevsMatExt,
                       stdDevsMatObj,
                       perViewErrorsMat,
                       flags );

778
    bool releaseObject = iFixedPoint > 0 && iFixedPoint < pointCount - 1;
779 780
    if( releaseObject )
    {
781
        newObjMat.convertTo( newObjPoints, CV_64F );
782 783
    }

784 785 786
    Mat stdDevMats[] = {stdDevsMatInt, stdDevsMatExt, stdDevsMatObj}, stdDevsMat;
    vconcat(stdDevMats, releaseObject ? 3 : 2, stdDevsMat);
    stdDevsMat.convertTo(stdDevs, CV_64F);
787

788 789 790
    perViewErrorsMat.convertTo(perViewErrors, CV_64F);
    cameraMatrix.convertTo(_cameraMatrix, CV_64F);
    distCoeffs.convertTo(_distCoeffs, CV_64F);
A
Andrey Kamaev 已提交
791

792
    for( i = 0; i < imageCount; i++ )
A
Andrey Kamaev 已提交
793
    {
794
        Mat r9;
795
        Rodrigues( rvecs[i], r9 );
796 797
        r9.convertTo(rotationMatrices[i], CV_64F);
        tvecs[i].convertTo(translationVectors[i], CV_64F);
A
Andrey Kamaev 已提交
798
    }
799 800
}

801 802 803 804 805

void CV_CameraCalibrationTest_CPP::project( const std::vector<Point3d>& objectPoints,
                         const RotMat& rotationMatrix, const Vec3d& translationVector,
                         const Mat& cameraMatrix, const Mat& distortion,
                         std::vector<Point2d>& imagePoints )
806
{
807 808
    projectPoints(objectPoints, rotationMatrix, translationVector, cameraMatrix, distortion, imagePoints );
    /*Mat objectPoints( pointCount, 3, CV_64FC1, _objectPoints );
A
Andrey Kamaev 已提交
809 810 811 812 813 814
    Mat rmat( 3, 3, CV_64FC1, rotationMatrix ),
        rvec( 1, 3, CV_64FC1 ),
        tvec( 1, 3, CV_64FC1, translationVector );
    Mat cameraMatrix( 3, 3, CV_64FC1, _cameraMatrix );
    Mat distCoeffs( 1, 4, CV_64FC1, distortion );
    vector<Point2f> imagePoints;
A
Alexander Alekhin 已提交
815
    cvtest::Rodrigues( rmat, rvec );
A
Andrey Kamaev 已提交
816 817 818 819 820 821 822 823

    objectPoints.convertTo( objectPoints, CV_32FC1 );
    projectPoints( objectPoints, rvec, tvec,
                   cameraMatrix, distCoeffs, imagePoints );
    vector<Point2f>::const_iterator it = imagePoints.begin();
    for( int i = 0; it != imagePoints.end(); ++it, i++ )
    {
        _imagePoints[i] = cvPoint2D64f( it->x, it->y );
824
    }*/
825 826 827 828 829 830 831 832
}


//----------------------------------------- CV_CalibrationMatrixValuesTest --------------------------------

class CV_CalibrationMatrixValuesTest : public cvtest::BaseTest
{
public:
A
Andrey Kamaev 已提交
833
    CV_CalibrationMatrixValuesTest() {}
834
protected:
A
Andrey Kamaev 已提交
835 836 837 838
    void run(int);
    virtual void calibMatrixValues( const Mat& cameraMatrix, Size imageSize,
        double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength,
        Point2d& principalPoint, double& aspectRatio ) = 0;
839 840 841 842
};

void CV_CalibrationMatrixValuesTest::run(int)
{
A
Andrey Kamaev 已提交
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
    int code = cvtest::TS::OK;
    const double fcMinVal = 1e-5;
    const double fcMaxVal = 1000;
    const double apertureMaxVal = 0.01;

    RNG rng = ts->get_rng();

    double fx, fy, cx, cy, nx, ny;
    Mat cameraMatrix( 3, 3, CV_64FC1 );
    cameraMatrix.setTo( Scalar(0) );
    fx = cameraMatrix.at<double>(0,0) = rng.uniform( fcMinVal, fcMaxVal );
    fy = cameraMatrix.at<double>(1,1) = rng.uniform( fcMinVal, fcMaxVal );
    cx = cameraMatrix.at<double>(0,2) = rng.uniform( fcMinVal, fcMaxVal );
    cy = cameraMatrix.at<double>(1,2) = rng.uniform( fcMinVal, fcMaxVal );
    cameraMatrix.at<double>(2,2) = 1;

    Size imageSize( 600, 400 );

    double apertureWidth = (double)rng * apertureMaxVal,
           apertureHeight = (double)rng * apertureMaxVal;

    double fovx, fovy, focalLength, aspectRatio,
           goodFovx, goodFovy, goodFocalLength, goodAspectRatio;
    Point2d principalPoint, goodPrincipalPoint;


    calibMatrixValues( cameraMatrix, imageSize, apertureWidth, apertureHeight,
        fovx, fovy, focalLength, principalPoint, aspectRatio );

    // calculate calibration matrix values
    goodAspectRatio = fy / fx;

    if( apertureWidth != 0.0 && apertureHeight != 0.0 )
    {
        nx = imageSize.width / apertureWidth;
        ny = imageSize.height / apertureHeight;
    }
    else
    {
        nx = 1.0;
        ny = goodAspectRatio;
    }

886 887
    goodFovx = (atan2(cx, fx) + atan2(imageSize.width  - cx, fx)) * 180.0 / CV_PI;
    goodFovy = (atan2(cy, fy) + atan2(imageSize.height - cy, fy)) * 180.0 / CV_PI;
A
Andrey Kamaev 已提交
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

    goodFocalLength = fx / nx;

    goodPrincipalPoint.x = cx / nx;
    goodPrincipalPoint.y = cy / ny;

    // check results
    if( fabs(fovx - goodFovx) > FLT_EPSILON )
    {
        ts->printf( cvtest::TS::LOG, "bad fovx (real=%f, good = %f\n", fovx, goodFovx );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
        goto _exit_;
    }
    if( fabs(fovy - goodFovy) > FLT_EPSILON )
    {
        ts->printf( cvtest::TS::LOG, "bad fovy (real=%f, good = %f\n", fovy, goodFovy );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
        goto _exit_;
    }
    if( fabs(focalLength - goodFocalLength) > FLT_EPSILON )
    {
        ts->printf( cvtest::TS::LOG, "bad focalLength (real=%f, good = %f\n", focalLength, goodFocalLength );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
        goto _exit_;
    }
    if( fabs(aspectRatio - goodAspectRatio) > FLT_EPSILON )
    {
        ts->printf( cvtest::TS::LOG, "bad aspectRatio (real=%f, good = %f\n", aspectRatio, goodAspectRatio );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
        goto _exit_;
    }
A
Alexander Alekhin 已提交
919
    if( cv::norm(principalPoint - goodPrincipalPoint) > FLT_EPSILON ) // Point2d
A
Andrey Kamaev 已提交
920 921 922 923 924
    {
        ts->printf( cvtest::TS::LOG, "bad principalPoint\n" );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
        goto _exit_;
    }
925 926

_exit_:
A
Andrey Kamaev 已提交
927 928 929
    RNG& _rng = ts->get_rng();
    _rng = rng;
    ts->set_failed_test_info( code );
930 931 932 933 934 935 936
}

//----------------------------------------- CV_CalibrationMatrixValuesTest_CPP --------------------------------

class CV_CalibrationMatrixValuesTest_CPP : public CV_CalibrationMatrixValuesTest
{
public:
A
Andrey Kamaev 已提交
937
    CV_CalibrationMatrixValuesTest_CPP() {}
938
protected:
A
Andrey Kamaev 已提交
939 940 941
    virtual void calibMatrixValues( const Mat& cameraMatrix, Size imageSize,
        double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength,
        Point2d& principalPoint, double& aspectRatio );
942 943 944
};

void CV_CalibrationMatrixValuesTest_CPP::calibMatrixValues( const Mat& cameraMatrix, Size imageSize,
A
Andrey Kamaev 已提交
945 946 947
                                                         double apertureWidth, double apertureHeight,
                                                         double& fovx, double& fovy, double& focalLength,
                                                         Point2d& principalPoint, double& aspectRatio )
948
{
A
Andrey Kamaev 已提交
949 950
    calibrationMatrixValues( cameraMatrix, imageSize, apertureWidth, apertureHeight,
        fovx, fovy, focalLength, principalPoint, aspectRatio );
951 952 953 954 955 956 957
}


//----------------------------------------- CV_ProjectPointsTest --------------------------------
void calcdfdx( const vector<vector<Point2f> >& leftF, const vector<vector<Point2f> >& rightF, double eps, Mat& dfdx )
{
    const int fdim = 2;
A
Andrey Kamaev 已提交
958 959 960 961
    CV_Assert( !leftF.empty() && !rightF.empty() && !leftF[0].empty() && !rightF[0].empty() );
    CV_Assert( leftF[0].size() ==  rightF[0].size() );
    CV_Assert( fabs(eps) > std::numeric_limits<double>::epsilon() );
    int fcount = (int)leftF[0].size(), xdim = (int)leftF.size();
962

A
Andrey Kamaev 已提交
963
    dfdx.create( fcount*fdim, xdim, CV_64FC1 );
964

A
Andrey Kamaev 已提交
965 966 967 968
    vector<vector<Point2f> >::const_iterator arrLeftIt = leftF.begin();
    vector<vector<Point2f> >::const_iterator arrRightIt = rightF.begin();
    for( int xi = 0; xi < xdim; xi++, ++arrLeftIt, ++arrRightIt )
    {
969 970 971 972 973 974 975
        CV_Assert( (int)arrLeftIt->size() ==  fcount );
        CV_Assert( (int)arrRightIt->size() ==  fcount );
        vector<Point2f>::const_iterator lIt = arrLeftIt->begin();
        vector<Point2f>::const_iterator rIt = arrRightIt->begin();
        for( int fi = 0; fi < dfdx.rows; fi+=fdim, ++lIt, ++rIt )
        {
            dfdx.at<double>(fi, xi )   = 0.5 * ((double)(rIt->x - lIt->x)) / eps;
A
Andrey Kamaev 已提交
976 977 978
            dfdx.at<double>(fi+1, xi ) = 0.5 * ((double)(rIt->y - lIt->y)) / eps;
        }
    }
979 980 981 982 983
}

class CV_ProjectPointsTest : public cvtest::BaseTest
{
public:
A
Andrey Kamaev 已提交
984
    CV_ProjectPointsTest() {}
985
protected:
A
Andrey Kamaev 已提交
986 987 988 989 990 991 992 993 994
    void run(int);
    virtual void project( const Mat& objectPoints,
        const Mat& rvec, const Mat& tvec,
        const Mat& cameraMatrix,
        const Mat& distCoeffs,
        vector<Point2f>& imagePoints,
        Mat& dpdrot, Mat& dpdt, Mat& dpdf,
        Mat& dpdc, Mat& dpddist,
        double aspectRatio=0 ) = 0;
995 996 997 998 999 1000
};

void CV_ProjectPointsTest::run(int)
{
    //typedef float matType;

A
Andrey Kamaev 已提交
1001 1002
    int code = cvtest::TS::OK;
    const int pointCount = 100;
1003

A
Andrey Kamaev 已提交
1004
    const float zMinVal = 10.0f, zMaxVal = 100.0f,
1005
                rMinVal = -0.3f, rMaxVal = 0.3f,
A
Andrey Kamaev 已提交
1006
                tMinVal = -2.0f, tMaxVal = 2.0f;
1007 1008 1009

    const float imgPointErr = 1e-3f,
                dEps = 1e-3f;
A
Andrey Kamaev 已提交
1010

1011 1012 1013 1014 1015 1016
    double err;

    Size imgSize( 600, 800 );
    Mat_<float> objPoints( pointCount, 3), rvec( 1, 3), rmat, tvec( 1, 3 ), cameraMatrix( 3, 3 ), distCoeffs( 1, 4 ),
      leftRvec, rightRvec, leftTvec, rightTvec, leftCameraMatrix, rightCameraMatrix, leftDistCoeffs, rightDistCoeffs;

A
Andrey Kamaev 已提交
1017
    RNG rng = ts->get_rng();
1018

A
Andrey Kamaev 已提交
1019 1020
    // generate data
    cameraMatrix << 300.f,  0.f,    imgSize.width/2.f,
1021 1022
                    0.f,    300.f,  imgSize.height/2.f,
                    0.f,    0.f,    1.f;
A
Andrey Kamaev 已提交
1023
    distCoeffs << 0.1, 0.01, 0.001, 0.001;
1024

A
Andrey Kamaev 已提交
1025 1026 1027
    rvec(0,0) = rng.uniform( rMinVal, rMaxVal );
    rvec(0,1) = rng.uniform( rMinVal, rMaxVal );
    rvec(0,2) = rng.uniform( rMinVal, rMaxVal );
A
Alexander Alekhin 已提交
1028
    rmat = cv::Mat_<float>::zeros(3, 3);
1029
    Rodrigues( rvec, rmat );
1030

A
Andrey Kamaev 已提交
1031 1032 1033
    tvec(0,0) = rng.uniform( tMinVal, tMaxVal );
    tvec(0,1) = rng.uniform( tMinVal, tMaxVal );
    tvec(0,2) = rng.uniform( tMinVal, tMaxVal );
1034 1035

    for( int y = 0; y < objPoints.rows; y++ )
A
Andrey Kamaev 已提交
1036 1037 1038 1039
    {
        Mat point(1, 3, CV_32FC1, objPoints.ptr(y) );
        float z = rng.uniform( zMinVal, zMaxVal );
        point.at<float>(0,2) = z;
1040 1041 1042
        point.at<float>(0,0) = (rng.uniform(2.f,(float)(imgSize.width-2)) - cameraMatrix(0,2)) / cameraMatrix(0,0) * z;
        point.at<float>(0,1) = (rng.uniform(2.f,(float)(imgSize.height-2)) - cameraMatrix(1,2)) / cameraMatrix(1,1) * z;
        point = (point - tvec) * rmat;
A
Andrey Kamaev 已提交
1043
    }
1044

A
Andrey Kamaev 已提交
1045 1046 1047 1048 1049
    vector<Point2f> imgPoints;
    vector<vector<Point2f> > leftImgPoints;
    vector<vector<Point2f> > rightImgPoints;
    Mat dpdrot, dpdt, dpdf, dpdc, dpddist,
        valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist;
1050

A
Andrey Kamaev 已提交
1051 1052
    project( objPoints, rvec, tvec, cameraMatrix, distCoeffs,
        imgPoints, dpdrot, dpdt, dpdf, dpdc, dpddist, 0 );
1053 1054

    // calculate and check image points
1055
    CV_Assert( (int)imgPoints.size() == pointCount );
A
Andrey Kamaev 已提交
1056 1057 1058 1059 1060
    vector<Point2f>::const_iterator it = imgPoints.begin();
    for( int i = 0; i < pointCount; i++, ++it )
    {
        Point3d p( objPoints(i,0), objPoints(i,1), objPoints(i,2) );
        double z = p.x*rmat(2,0) + p.y*rmat(2,1) + p.z*rmat(2,2) + tvec(0,2),
1061 1062 1063
               x = (p.x*rmat(0,0) + p.y*rmat(0,1) + p.z*rmat(0,2) + tvec(0,0)) / z,
               y = (p.x*rmat(1,0) + p.y*rmat(1,1) + p.z*rmat(1,2) + tvec(0,1)) / z,
               r2 = x*x + y*y,
A
Andrey Kamaev 已提交
1064 1065 1066
               r4 = r2*r2;
        Point2f validImgPoint;
        double a1 = 2*x*y,
1067 1068 1069
               a2 = r2 + 2*x*x,
               a3 = r2 + 2*y*y,
               cdist = 1+distCoeffs(0,0)*r2+distCoeffs(0,1)*r4;
A
Andrey Kamaev 已提交
1070
        validImgPoint.x = static_cast<float>((double)cameraMatrix(0,0)*(x*cdist + (double)distCoeffs(0,2)*a1 + (double)distCoeffs(0,3)*a2)
1071
            + (double)cameraMatrix(0,2));
A
Andrey Kamaev 已提交
1072
        validImgPoint.y = static_cast<float>((double)cameraMatrix(1,1)*(y*cdist + (double)distCoeffs(0,2)*a3 + distCoeffs(0,3)*a1)
1073 1074 1075 1076
            + (double)cameraMatrix(1,2));

        if( fabs(it->x - validImgPoint.x) > imgPointErr ||
            fabs(it->y - validImgPoint.y) > imgPointErr )
A
Andrey Kamaev 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
        {
            ts->printf( cvtest::TS::LOG, "bad image point\n" );
            code = cvtest::TS::FAIL_BAD_ACCURACY;
            goto _exit_;
        }
    }

    // check derivatives
    // 1. rotation
    leftImgPoints.resize(3);
1087
    rightImgPoints.resize(3);
A
Andrey Kamaev 已提交
1088 1089
    for( int i = 0; i < 3; i++ )
    {
1090 1091 1092 1093 1094 1095
        rvec.copyTo( leftRvec ); leftRvec(0,i) -= dEps;
        project( objPoints, leftRvec, tvec, cameraMatrix, distCoeffs,
            leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
        rvec.copyTo( rightRvec ); rightRvec(0,i) += dEps;
        project( objPoints, rightRvec, tvec, cameraMatrix, distCoeffs,
            rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
A
Andrey Kamaev 已提交
1096
    }
1097
    calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdrot );
1098
    err = cvtest::norm( dpdrot, valDpdrot, NORM_INF );
1099
    if( err > 3 )
A
Andrey Kamaev 已提交
1100 1101 1102 1103
    {
        ts->printf( cvtest::TS::LOG, "bad dpdrot: too big difference = %g\n", err );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
    }
1104 1105 1106

    // 2. translation
    for( int i = 0; i < 3; i++ )
A
Andrey Kamaev 已提交
1107
    {
1108 1109 1110 1111 1112 1113
        tvec.copyTo( leftTvec ); leftTvec(0,i) -= dEps;
        project( objPoints, rvec, leftTvec, cameraMatrix, distCoeffs,
            leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
        tvec.copyTo( rightTvec ); rightTvec(0,i) += dEps;
        project( objPoints, rvec, rightTvec, cameraMatrix, distCoeffs,
            rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
A
Andrey Kamaev 已提交
1114
    }
1115
    calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdt );
1116
    if( cvtest::norm( dpdt, valDpdt, NORM_INF ) > 0.2 )
A
Andrey Kamaev 已提交
1117 1118 1119 1120
    {
        ts->printf( cvtest::TS::LOG, "bad dpdtvec\n" );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
    }
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

    // 3. camera matrix
    // 3.1. focus
    leftImgPoints.resize(2);
    rightImgPoints.resize(2);
    cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(0,0) -= dEps;
    project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs,
        leftImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(1,1) -= dEps;
    project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs,
        leftImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(0,0) += dEps;
    project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs,
        rightImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(1,1) += dEps;
    project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs,
        rightImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdf );
1139
    if ( cvtest::norm( dpdf, valDpdf, NORM_L2 ) > 0.2 )
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    {
        ts->printf( cvtest::TS::LOG, "bad dpdf\n" );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
    }
    // 3.2. principal point
    leftImgPoints.resize(2);
    rightImgPoints.resize(2);
    cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(0,2) -= dEps;
    project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs,
        leftImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(1,2) -= dEps;
    project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs,
        leftImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(0,2) += dEps;
    project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs,
        rightImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(1,2) += dEps;
    project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs,
        rightImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
    calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdc );
1160
    if ( cvtest::norm( dpdc, valDpdc, NORM_L2 ) > 0.2 )
1161 1162 1163 1164 1165 1166 1167 1168
    {
        ts->printf( cvtest::TS::LOG, "bad dpdc\n" );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
    }

    // 4. distortion
    leftImgPoints.resize(distCoeffs.cols);
    rightImgPoints.resize(distCoeffs.cols);
A
Andrey Kamaev 已提交
1169 1170
    for( int i = 0; i < distCoeffs.cols; i++ )
    {
1171 1172 1173 1174 1175 1176
        distCoeffs.copyTo( leftDistCoeffs ); leftDistCoeffs(0,i) -= dEps;
        project( objPoints, rvec, tvec, cameraMatrix, leftDistCoeffs,
            leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
        distCoeffs.copyTo( rightDistCoeffs ); rightDistCoeffs(0,i) += dEps;
        project( objPoints, rvec, tvec, cameraMatrix, rightDistCoeffs,
            rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 );
A
Andrey Kamaev 已提交
1177
    }
1178
    calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpddist );
1179
    if( cvtest::norm( dpddist, valDpddist, NORM_L2 ) > 0.3 )
A
Andrey Kamaev 已提交
1180 1181 1182 1183
    {
        ts->printf( cvtest::TS::LOG, "bad dpddist\n" );
        code = cvtest::TS::FAIL_BAD_ACCURACY;
    }
1184 1185

_exit_:
A
Andrey Kamaev 已提交
1186 1187 1188
    RNG& _rng = ts->get_rng();
    _rng = rng;
    ts->set_failed_test_info( code );
1189 1190 1191 1192 1193 1194
}

//----------------------------------------- CV_ProjectPointsTest_CPP --------------------------------
class CV_ProjectPointsTest_CPP : public CV_ProjectPointsTest
{
public:
A
Andrey Kamaev 已提交
1195
    CV_ProjectPointsTest_CPP() {}
1196
protected:
A
Andrey Kamaev 已提交
1197 1198 1199 1200 1201 1202 1203 1204
    virtual void project( const Mat& objectPoints,
        const Mat& rvec, const Mat& tvec,
        const Mat& cameraMatrix,
        const Mat& distCoeffs,
        vector<Point2f>& imagePoints,
        Mat& dpdrot, Mat& dpdt, Mat& dpdf,
        Mat& dpdc, Mat& dpddist,
        double aspectRatio=0 );
1205 1206 1207
};

void CV_ProjectPointsTest_CPP::project( const Mat& objectPoints, const Mat& rvec, const Mat& tvec,
A
Andrey Kamaev 已提交
1208 1209
                                       const Mat& cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints,
                                       Mat& dpdrot, Mat& dpdt, Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio)
1210
{
1211
    Mat J;
A
Andrey Kamaev 已提交
1212
    projectPoints( objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, J, aspectRatio);
1213 1214 1215 1216 1217
    J.colRange(0, 3).copyTo(dpdrot);
    J.colRange(3, 6).copyTo(dpdt);
    J.colRange(6, 8).copyTo(dpdf);
    J.colRange(8, 10).copyTo(dpdc);
    J.colRange(10, J.cols).copyTo(dpddist);
1218 1219 1220 1221 1222 1223 1224
}

///////////////////////////////// Stereo Calibration /////////////////////////////////////

class CV_StereoCalibrationTest : public cvtest::BaseTest
{
public:
A
Andrey Kamaev 已提交
1225 1226 1227
    CV_StereoCalibrationTest();
    ~CV_StereoCalibrationTest();
    void clear();
1228
protected:
A
Andrey Kamaev 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    bool checkPandROI( int test_case_idx,
        const Mat& M, const Mat& D, const Mat& R,
        const Mat& P, Size imgsize, Rect roi );

    // covers of tested functions
    virtual double calibrateStereoCamera( const vector<vector<Point3f> >& objectPoints,
        const vector<vector<Point2f> >& imagePoints1,
        const vector<vector<Point2f> >& imagePoints2,
        Mat& cameraMatrix1, Mat& distCoeffs1,
        Mat& cameraMatrix2, Mat& distCoeffs2,
        Size imageSize, Mat& R, Mat& T,
1240 1241 1242 1243
        Mat& E, Mat& F,
        std::vector<RotMat>& rotationMatrices, std::vector<Vec3d>& translationVectors,
        vector<double>& perViewErrors1, vector<double>& perViewErrors2,
        TermCriteria criteria, int flags ) = 0;
A
Andrey Kamaev 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    virtual void rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1,
        const Mat& cameraMatrix2, const Mat& distCoeffs2,
        Size imageSize, const Mat& R, const Mat& T,
        Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q,
        double alpha, Size newImageSize,
        Rect* validPixROI1, Rect* validPixROI2, int flags ) = 0;
    virtual bool rectifyUncalibrated( const Mat& points1,
        const Mat& points2, const Mat& F, Size imgSize,
        Mat& H1, Mat& H2, double threshold=5 ) = 0;
    virtual void triangulate( const Mat& P1, const Mat& P2,
1254 1255
        const Mat &points1, const Mat &points2,
        Mat &points4D ) = 0;
A
Andrey Kamaev 已提交
1256
    virtual void correct( const Mat& F,
1257 1258
        const Mat &points1, const Mat &points2,
        Mat &newPoints1, Mat &newPoints2 ) = 0;
1259 1260
    int compare(double* val, double* refVal, int len,
                double eps, const char* paramName);
1261

A
Andrey Kamaev 已提交
1262
    void run(int);
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
};


CV_StereoCalibrationTest::CV_StereoCalibrationTest()
{
}


CV_StereoCalibrationTest::~CV_StereoCalibrationTest()
{
A
Andrey Kamaev 已提交
1273
    clear();
1274 1275 1276 1277
}

void CV_StereoCalibrationTest::clear()
{
A
Andrey Kamaev 已提交
1278
    cvtest::BaseTest::clear();
1279 1280 1281
}

bool CV_StereoCalibrationTest::checkPandROI( int test_case_idx, const Mat& M, const Mat& D, const Mat& R,
A
Andrey Kamaev 已提交
1282
                                            const Mat& P, Size imgsize, Rect roi )
1283
{
A
Andrey Kamaev 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    const double eps = 0.05;
    const int N = 21;
    int x, y, k;
    vector<Point2f> pts, upts;

    // step 1. check that all the original points belong to the destination image
    for( y = 0; y < N; y++ )
        for( x = 0; x < N; x++ )
            pts.push_back(Point2f((float)x*imgsize.width/(N-1), (float)y*imgsize.height/(N-1)));

S
Suleyman TURKMEN 已提交
1294
    undistortPoints(pts, upts, M, D, R, P );
A
Andrey Kamaev 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303
    for( k = 0; k < N*N; k++ )
        if( upts[k].x < -imgsize.width*eps || upts[k].x > imgsize.width*(1+eps) ||
            upts[k].y < -imgsize.height*eps || upts[k].y > imgsize.height*(1+eps) )
        {
            ts->printf(cvtest::TS::LOG, "Test #%d. The point (%g, %g) was mapped to (%g, %g) which is out of image\n",
                test_case_idx, pts[k].x, pts[k].y, upts[k].x, upts[k].y);
            return false;
        }

1304 1305 1306 1307 1308
    // step 2. check that all the points inside ROI belong to the original source image
    Mat temp(imgsize, CV_8U), utemp, map1, map2;
    temp = Scalar::all(1);
    initUndistortRectifyMap(M, D, R, P, imgsize, CV_16SC2, map1, map2);
    remap(temp, utemp, map1, map2, INTER_LINEAR);
A
Andrey Kamaev 已提交
1309

1310 1311
    if(roi.x < 0 || roi.y < 0 || roi.x + roi.width > imgsize.width || roi.y + roi.height > imgsize.height)
    {
A
Andrey Kamaev 已提交
1312
            ts->printf(cvtest::TS::LOG, "Test #%d. The ROI=(%d, %d, %d, %d) is outside of the imge rectangle\n",
1313
                            test_case_idx, roi.x, roi.y, roi.width, roi.height);
A
Andrey Kamaev 已提交
1314
            return false;
1315 1316 1317 1318
    }
    double s = sum(utemp(roi))[0];
    if( s > roi.area() || roi.area() - s > roi.area()*(1-eps) )
    {
A
Andrey Kamaev 已提交
1319
            ts->printf(cvtest::TS::LOG, "Test #%d. The ratio of black pixels inside the valid ROI (~%g%%) is too large\n",
1320
                            test_case_idx, s*100./roi.area());
A
Andrey Kamaev 已提交
1321
            return false;
1322
    }
A
Andrey Kamaev 已提交
1323

1324
    return true;
1325 1326
}

1327 1328 1329 1330 1331 1332
int CV_StereoCalibrationTest::compare(double* val, double* ref_val, int len,
                                      double eps, const char* param_name )
{
    return cvtest::cmpEps2_64f( ts, val, ref_val, len, eps, param_name );
}

1333 1334
void CV_StereoCalibrationTest::run( int )
{
A
Andrey Kamaev 已提交
1335 1336 1337 1338
    const int ntests = 1;
    const double maxReprojErr = 2;
    const double maxScanlineDistErr_c = 3;
    const double maxScanlineDistErr_uc = 4;
1339
    const double maxDiffBtwRmsErrors = 1e-4;
A
Andrey Kamaev 已提交
1340 1341 1342 1343
    FILE* f = 0;

    for(int testcase = 1; testcase <= ntests; testcase++)
    {
1344
        cv::String filepath;
A
Andrey Kamaev 已提交
1345
        char buf[1000];
1346 1347
        filepath = cv::format("%scv/stereo/case%d/stereo_calib.txt", ts->get_data_path().c_str(), testcase );
        f = fopen(filepath.c_str(), "rt");
A
Andrey Kamaev 已提交
1348 1349 1350 1351 1352
        Size patternSize;
        vector<string> imglist;

        if( !f || !fgets(buf, sizeof(buf)-3, f) || sscanf(buf, "%d%d", &patternSize.width, &patternSize.height) != 2 )
        {
1353
            ts->printf( cvtest::TS::LOG, "The file %s can not be opened or has invalid content\n", filepath.c_str() );
A
Andrey Kamaev 已提交
1354
            ts->set_failed_test_info( f ? cvtest::TS::FAIL_INVALID_TEST_DATA : cvtest::TS::FAIL_MISSING_TEST_DATA );
1355 1356
            if (f)
                fclose(f);
A
Andrey Kamaev 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
            return;
        }

        for(;;)
        {
            if( !fgets( buf, sizeof(buf)-3, f ))
                break;
            size_t len = strlen(buf);
            while( len > 0 && isspace(buf[len-1]))
                buf[--len] = '\0';
            if( buf[0] == '#')
                continue;
1369
            filepath = cv::format("%scv/stereo/case%d/%s", ts->get_data_path().c_str(), testcase, buf );
A
Andrey Kamaev 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
            imglist.push_back(string(filepath));
        }
        fclose(f);

        if( imglist.size() == 0 || imglist.size() % 2 != 0 )
        {
            ts->printf( cvtest::TS::LOG, "The number of images is 0 or an odd number in the case #%d\n", testcase );
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
            return;
        }

        int nframes = (int)(imglist.size()/2);
        int npoints = patternSize.width*patternSize.height;
        vector<vector<Point3f> > objpt(nframes);
        vector<vector<Point2f> > imgpt1(nframes);
        vector<vector<Point2f> > imgpt2(nframes);
        Size imgsize;
        int total = 0;

        for( int i = 0; i < nframes; i++ )
        {
            Mat left = imread(imglist[i*2]);
            Mat right = imread(imglist[i*2+1]);
1393
            if(left.empty() || right.empty())
A
Andrey Kamaev 已提交
1394 1395
            {
                ts->printf( cvtest::TS::LOG, "Can not load images %s and %s, testcase %d\n",
1396
                            imglist[i*2].c_str(), imglist[i*2+1].c_str(), testcase );
A
Andrey Kamaev 已提交
1397 1398 1399 1400 1401 1402 1403 1404
                ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
                return;
            }
            imgsize = left.size();
            bool found1 = findChessboardCorners(left, patternSize, imgpt1[i]);
            bool found2 = findChessboardCorners(right, patternSize, imgpt2[i]);
            if(!found1 || !found2)
            {
1405
                ts->printf( cvtest::TS::LOG, "The function could not detect boards (%d x %d) on the images %s and %s, testcase %d\n",
1406 1407
                            patternSize.width, patternSize.height,
                            imglist[i*2].c_str(), imglist[i*2+1].c_str(), testcase );
A
Andrey Kamaev 已提交
1408 1409 1410 1411 1412 1413 1414 1415
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
            total += (int)imgpt1[i].size();
            for( int j = 0; j < npoints; j++ )
                objpt[i].push_back(Point3f((float)(j%patternSize.width), (float)(j/patternSize.width), 0.f));
        }

1416 1417 1418 1419 1420 1421 1422 1423 1424
        vector<RotMat> rotMats1(nframes);
        vector<Vec3d> transVecs1(nframes);
        vector<RotMat> rotMats2(nframes);
        vector<Vec3d> transVecs2(nframes);
        vector<double> rmsErrorPerView1(nframes);
        vector<double> rmsErrorPerView2(nframes);
        vector<double> rmsErrorPerViewFromReprojectedImgPts1(nframes);
        vector<double> rmsErrorPerViewFromReprojectedImgPts2(nframes);

A
Andrey Kamaev 已提交
1425 1426 1427 1428 1429 1430
        // rectify (calibrated)
        Mat M1 = Mat::eye(3,3,CV_64F), M2 = Mat::eye(3,3,CV_64F), D1(5,1,CV_64F), D2(5,1,CV_64F), R, T, E, F;
        M1.at<double>(0,2) = M2.at<double>(0,2)=(imgsize.width-1)*0.5;
        M1.at<double>(1,2) = M2.at<double>(1,2)=(imgsize.height-1)*0.5;
        D1 = Scalar::all(0);
        D2 = Scalar::all(0);
1431 1432
        double rmsErrorFromStereoCalib = calibrateStereoCamera(objpt, imgpt1, imgpt2, M1, D1, M2, D2, imgsize, R, T, E, F,
            rotMats1, transVecs1, rmsErrorPerView1, rmsErrorPerView2,
A
Andrey Kamaev 已提交
1433
            TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 30, 1e-6),
1434
            CALIB_SAME_FOCAL_LENGTH
A
Andrey Kamaev 已提交
1435
            //+ CV_CALIB_FIX_ASPECT_RATIO
1436 1437 1438 1439
            + CALIB_FIX_PRINCIPAL_POINT
            + CALIB_ZERO_TANGENT_DIST
            + CALIB_FIX_K3
            + CALIB_FIX_K4 + CALIB_FIX_K5 //+ CV_CALIB_FIX_K6
A
Andrey Kamaev 已提交
1440
            );
1441 1442

        /* rmsErrorFromStereoCalib /= nframes*npoints; */
1443
        if (rmsErrorFromStereoCalib > maxReprojErr)
A
Andrey Kamaev 已提交
1444
        {
1445
            ts->printf(cvtest::TS::LOG, "The average reprojection error is too big (=%g), testcase %d\n",
1446
                       rmsErrorFromStereoCalib, testcase);
1447 1448 1449
            ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
            return;
        }
1450

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
        double rmsErrorFromReprojectedImgPts = 0.0f;
        if (rotMats1.empty() || transVecs1.empty())
        {
            rmsErrorPerViewFromReprojectedImgPts1 = rmsErrorPerView1;
            rmsErrorPerViewFromReprojectedImgPts2 = rmsErrorPerView2;
            rmsErrorFromReprojectedImgPts = rmsErrorFromStereoCalib;
        }
        else
        {
            size_t totalPoints = 0;
1461
            double totalErr[2] = { 0, 0 };
1462 1463 1464 1465 1466 1467 1468 1469
            for (size_t i = 0; i < objpt.size(); ++i) {
                RotMat r1 = rotMats1[i];
                Vec3d t1 = transVecs1[i];

                RotMat r2 = Mat(R * r1);
                Mat T2t = R * t1;
                Vec3d t2 = Mat(T2t + T);

1470 1471
                vector<Point2f> reprojectedImgPts[2] = { vector<Point2f>(nframes),
                                                         vector<Point2f>(nframes) };
1472 1473 1474
                projectPoints(objpt[i], r1, t1, M1, D1, reprojectedImgPts[0]);
                projectPoints(objpt[i], r2, t2, M2, D2, reprojectedImgPts[1]);

1475
                double viewErr[2];
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
                viewErr[0] = cv::norm(imgpt1[i], reprojectedImgPts[0], cv::NORM_L2SQR);
                viewErr[1] = cv::norm(imgpt2[i], reprojectedImgPts[1], cv::NORM_L2SQR);

                size_t n = objpt[i].size();
                totalErr[0] += viewErr[0];
                totalErr[1] += viewErr[1];
                totalPoints += n;

                rmsErrorPerViewFromReprojectedImgPts1[i] = sqrt(viewErr[0] / n);
                rmsErrorPerViewFromReprojectedImgPts2[i] = sqrt(viewErr[1] / n);
            }
            rmsErrorFromReprojectedImgPts = std::sqrt((totalErr[0] + totalErr[1]) / (2 * totalPoints));
        }
1489

1490
        if (abs(rmsErrorFromStereoCalib - rmsErrorFromReprojectedImgPts) > maxDiffBtwRmsErrors)
A
Andrey Kamaev 已提交
1491
        {
1492
            ts->printf(cvtest::TS::LOG,
1493 1494 1495 1496
                       "The difference of the average reprojection error from the calibration function and from the "
                       "reprojected image points is too big (|%g - %g| = %g), testcase %d\n",
                       rmsErrorFromStereoCalib, rmsErrorFromReprojectedImgPts,
                       (rmsErrorFromStereoCalib - rmsErrorFromReprojectedImgPts), testcase);
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
            ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
            return;
        }

        /* ----- Compare per view rms re-projection errors ----- */
        CV_Assert(rmsErrorPerView1.size() == (size_t)nframes);
        CV_Assert(rmsErrorPerViewFromReprojectedImgPts1.size() == (size_t)nframes);
        CV_Assert(rmsErrorPerView2.size() == (size_t)nframes);
        CV_Assert(rmsErrorPerViewFromReprojectedImgPts2.size() == (size_t)nframes);
        int code1 = compare(&rmsErrorPerView1[0], &rmsErrorPerViewFromReprojectedImgPts1[0], nframes,
1507
                            maxDiffBtwRmsErrors, "per view errors vector");
1508
        int code2 = compare(&rmsErrorPerView2[0], &rmsErrorPerViewFromReprojectedImgPts2[0], nframes,
1509
                            maxDiffBtwRmsErrors, "per view errors vector");
1510 1511 1512
        if (code1 < 0)
        {
            ts->printf(cvtest::TS::LOG,
1513 1514 1515
                       "Some of the per view rms reprojection errors differ between calibration function and reprojected "
                       "points, for the first camera, testcase %d\n",
                       testcase);
1516 1517 1518 1519 1520 1521
            ts->set_failed_test_info(code1);
            return;
        }
        if (code2 < 0)
        {
            ts->printf(cvtest::TS::LOG,
1522 1523 1524
                       "Some of the per view rms reprojection errors differ between calibration function and reprojected "
                       "points, for the second camera, testcase %d\n",
                       testcase);
1525
            ts->set_failed_test_info(code2);
A
Andrey Kamaev 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534
            return;
        }

        Mat R1, R2, P1, P2, Q;
        Rect roi1, roi2;
        rectify(M1, D1, M2, D2, imgsize, R, T, R1, R2, P1, P2, Q, 1, imgsize, &roi1, &roi2, 0);
        Mat eye33 = Mat::eye(3,3,CV_64F);
        Mat R1t = R1.t(), R2t = R2.t();

1535 1536
        if( cvtest::norm(R1t*R1 - eye33, NORM_L2) > 0.01 ||
            cvtest::norm(R2t*R2 - eye33, NORM_L2) > 0.01 ||
A
Andrey Kamaev 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
            abs(determinant(F)) > 0.01)
        {
            ts->printf( cvtest::TS::LOG, "The computed (by rectify) R1 and R2 are not orthogonal,"
                "or the computed (by calibrate) F is not singular, testcase %d\n", testcase);
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
            return;
        }

        if(!checkPandROI(testcase, M1, D1, R1, P1, imgsize, roi1))
        {
            ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
            return;
        }

        if(!checkPandROI(testcase, M2, D2, R2, P2, imgsize, roi2))
        {
            ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
            return;
        }
1556

1557 1558
        //check that Tx after rectification is equal to distance between cameras
        double tx = fabs(P2.at<double>(0, 3) / P2.at<double>(0, 0));
1559
        if (fabs(tx - cvtest::norm(T, NORM_L2)) > 1e-5)
1560
        {
A
Andrey Kamaev 已提交
1561 1562
            ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
            return;
1563 1564
        }

1565 1566 1567 1568 1569 1570
        //check that Q reprojects points before the camera
        double testPoint[4] = {0.0, 0.0, 100.0, 1.0};
        Mat reprojectedTestPoint = Q * Mat_<double>(4, 1, testPoint);
        CV_Assert(reprojectedTestPoint.type() == CV_64FC1);
        if( reprojectedTestPoint.at<double>(2) / reprojectedTestPoint.at<double>(3) < 0 )
        {
A
Andrey Kamaev 已提交
1571 1572
            ts->printf( cvtest::TS::LOG, "A point after rectification is reprojected behind the camera, testcase %d\n", testcase);
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
1573 1574
        }

1575 1576 1577 1578
        //check that Q reprojects the same points as reconstructed by triangulation
        const float minCoord = -300.0f;
        const float maxCoord = 300.0f;
        const float minDisparity = 0.1f;
1579
        const float maxDisparity = 60.0f;
1580
        const int pointsCount = 500;
1581
        const float requiredAccuracy = 1e-3f;
1582
        const float allowToFail = 0.2f; // 20%
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
        RNG& rng = ts->get_rng();

        Mat projectedPoints_1(2, pointsCount, CV_32FC1);
        Mat projectedPoints_2(2, pointsCount, CV_32FC1);
        Mat disparities(1, pointsCount, CV_32FC1);

        rng.fill(projectedPoints_1, RNG::UNIFORM, minCoord, maxCoord);
        rng.fill(disparities, RNG::UNIFORM, minDisparity, maxDisparity);
        projectedPoints_2.row(0) = projectedPoints_1.row(0) - disparities;
        Mat ys_2 = projectedPoints_2.row(1);
        projectedPoints_1.row(1).copyTo(ys_2);

1595 1596
        Mat points4d;
        triangulate(P1, P2, projectedPoints_1, projectedPoints_2, points4d);
1597
        Mat homogeneousPoints4d = points4d.t();
1598
        const int dimension = 4;
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
        homogeneousPoints4d = homogeneousPoints4d.reshape(dimension);
        Mat triangulatedPoints;
        convertPointsFromHomogeneous(homogeneousPoints4d, triangulatedPoints);

        Mat sparsePoints;
        sparsePoints.push_back(projectedPoints_1);
        sparsePoints.push_back(disparities);
        sparsePoints = sparsePoints.t();
        sparsePoints = sparsePoints.reshape(3);
        Mat reprojectedPoints;
        perspectiveTransform(sparsePoints, reprojectedPoints, Q);

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        Mat diff;
        absdiff(triangulatedPoints, reprojectedPoints, diff);
        Mat mask = diff > requiredAccuracy;
        mask = mask.reshape(1);
        mask = mask.col(0) | mask.col(1) | mask.col(2);
        int numFailed = countNonZero(mask);
#if 0
        std::cout << "numFailed=" << numFailed << std::endl;
        for (int i = 0; i < triangulatedPoints.rows; i++)
        {
            if (mask.at<uchar>(i))
            {
                // failed points usually have 'w'~0 (points4d[3])
                std::cout << "i=" << i << " triangulatePoints=" << triangulatedPoints.row(i) << " reprojectedPoints=" << reprojectedPoints.row(i) << std::endl <<
                    "     points4d=" << points4d.col(i).t() << " projectedPoints_1=" << projectedPoints_1.col(i).t() << " disparities=" << disparities.col(i).t() << std::endl;
            }
        }
#endif

        if (numFailed >= allowToFail * pointsCount)
1631
        {
1632 1633
            ts->printf( cvtest::TS::LOG, "Points reprojected with a matrix Q and points reconstructed by triangulation are different (tolerance=%g, failed=%d), testcase %d\n",
                requiredAccuracy, numFailed, testcase);
A
Andrey Kamaev 已提交
1634
            ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
1635
        }
1636 1637

        //check correctMatches
1638
        const float constraintAccuracy = 1e-5f;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
        Mat newPoints1, newPoints2;
        Mat points1 = projectedPoints_1.t();
        points1 = points1.reshape(2, 1);
        Mat points2 = projectedPoints_2.t();
        points2 = points2.reshape(2, 1);
        correctMatches(F, points1, points2, newPoints1, newPoints2);
        Mat newHomogeneousPoints1, newHomogeneousPoints2;
        convertPointsToHomogeneous(newPoints1, newHomogeneousPoints1);
        convertPointsToHomogeneous(newPoints2, newHomogeneousPoints2);
        newHomogeneousPoints1 = newHomogeneousPoints1.reshape(1);
        newHomogeneousPoints2 = newHomogeneousPoints2.reshape(1);
        Mat typedF;
        F.convertTo(typedF, newHomogeneousPoints1.type());
        for (int i = 0; i < newHomogeneousPoints1.rows; ++i)
        {
            Mat error = newHomogeneousPoints2.row(i) * typedF * newHomogeneousPoints1.row(i).t();
            CV_Assert(error.rows == 1 && error.cols == 1);
1656
            if (cvtest::norm(error, NORM_L2) > constraintAccuracy)
1657 1658 1659 1660 1661
            {
                ts->printf( cvtest::TS::LOG, "Epipolar constraint is violated after correctMatches, testcase %d\n", testcase);
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
            }
        }
1662

A
Andrey Kamaev 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
        // rectifyUncalibrated
        CV_Assert( imgpt1.size() == imgpt2.size() );
        Mat _imgpt1( total, 1, CV_32FC2 ), _imgpt2( total, 1, CV_32FC2 );
        vector<vector<Point2f> >::const_iterator iit1 = imgpt1.begin();
        vector<vector<Point2f> >::const_iterator iit2 = imgpt2.begin();
        for( int pi = 0; iit1 != imgpt1.end(); ++iit1, ++iit2 )
        {
            vector<Point2f>::const_iterator pit1 = iit1->begin();
            vector<Point2f>::const_iterator pit2 = iit2->begin();
            CV_Assert( iit1->size() == iit2->size() );
            for( ; pit1 != iit1->end(); ++pit1, ++pit2, pi++ )
            {
                _imgpt1.at<Point2f>(pi,0) = Point2f( pit1->x, pit1->y );
                _imgpt2.at<Point2f>(pi,0) = Point2f( pit2->x, pit2->y );
            }
        }

        Mat _M1, _M2, _D1, _D2;
        vector<Mat> _R1, _R2, _T1, _T2;
        calibrateCamera( objpt, imgpt1, imgsize, _M1, _D1, _R1, _T1, 0 );
M
Maks Naumov 已提交
1683
        calibrateCamera( objpt, imgpt2, imgsize, _M2, _D2, _R2, _T2, 0 );
A
Andrey Kamaev 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
        undistortPoints( _imgpt1, _imgpt1, _M1, _D1, Mat(), _M1 );
        undistortPoints( _imgpt2, _imgpt2, _M2, _D2, Mat(), _M2 );

        Mat matF, _H1, _H2;
        matF = findFundamentalMat( _imgpt1, _imgpt2 );
        rectifyUncalibrated( _imgpt1, _imgpt2, matF, imgsize, _H1, _H2 );

        Mat rectifPoints1, rectifPoints2;
        perspectiveTransform( _imgpt1, rectifPoints1, _H1 );
        perspectiveTransform( _imgpt2, rectifPoints2, _H2 );

        bool verticalStereo = abs(P2.at<double>(0,3)) < abs(P2.at<double>(1,3));
        double maxDiff_c = 0, maxDiff_uc = 0;
        for( int i = 0, k = 0; i < nframes; i++ )
        {
            vector<Point2f> temp[2];
S
Suleyman TURKMEN 已提交
1700 1701
            undistortPoints(imgpt1[i], temp[0], M1, D1, R1, P1);
            undistortPoints(imgpt2[i], temp[1], M2, D2, R2, P2);
A
Andrey Kamaev 已提交
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729

            for( int j = 0; j < npoints; j++, k++ )
            {
                double diff_c = verticalStereo ? abs(temp[0][j].x - temp[1][j].x) : abs(temp[0][j].y - temp[1][j].y);
                Point2f d = rectifPoints1.at<Point2f>(k,0) - rectifPoints2.at<Point2f>(k,0);
                double diff_uc = verticalStereo ? abs(d.x) : abs(d.y);
                maxDiff_c = max(maxDiff_c, diff_c);
                maxDiff_uc = max(maxDiff_uc, diff_uc);
                if( maxDiff_c > maxScanlineDistErr_c )
                {
                    ts->printf( cvtest::TS::LOG, "The distance between %s coordinates is too big(=%g) (used calibrated stereo), testcase %d\n",
                        verticalStereo ? "x" : "y", diff_c, testcase);
                    ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
                    return;
                }
                if( maxDiff_uc > maxScanlineDistErr_uc )
                {
                    ts->printf( cvtest::TS::LOG, "The distance between %s coordinates is too big(=%g) (used uncalibrated stereo), testcase %d\n",
                        verticalStereo ? "x" : "y", diff_uc, testcase);
                    ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
                    return;
                }
            }
        }

        ts->printf( cvtest::TS::LOG, "Testcase %d. Max distance (calibrated) =%g\n"
            "Max distance (uncalibrated) =%g\n", testcase, maxDiff_c, maxDiff_uc );
    }
1730 1731 1732 1733 1734 1735 1736
}

//-------------------------------- CV_StereoCalibrationTest_CPP ------------------------------

class CV_StereoCalibrationTest_CPP : public CV_StereoCalibrationTest
{
public:
A
Andrey Kamaev 已提交
1737
    CV_StereoCalibrationTest_CPP() {}
1738
protected:
A
Andrey Kamaev 已提交
1739 1740 1741 1742 1743 1744
    virtual double calibrateStereoCamera( const vector<vector<Point3f> >& objectPoints,
        const vector<vector<Point2f> >& imagePoints1,
        const vector<vector<Point2f> >& imagePoints2,
        Mat& cameraMatrix1, Mat& distCoeffs1,
        Mat& cameraMatrix2, Mat& distCoeffs2,
        Size imageSize, Mat& R, Mat& T,
1745 1746 1747 1748
        Mat& E, Mat& F,
        std::vector<RotMat>& rotationMatrices, std::vector<Vec3d>& translationVectors,
        vector<double>& perViewErrors1, vector<double>& perViewErrors2,
        TermCriteria criteria, int flags );
A
Andrey Kamaev 已提交
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    virtual void rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1,
        const Mat& cameraMatrix2, const Mat& distCoeffs2,
        Size imageSize, const Mat& R, const Mat& T,
        Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q,
        double alpha, Size newImageSize,
        Rect* validPixROI1, Rect* validPixROI2, int flags );
    virtual bool rectifyUncalibrated( const Mat& points1,
        const Mat& points2, const Mat& F, Size imgSize,
        Mat& H1, Mat& H2, double threshold=5 );
    virtual void triangulate( const Mat& P1, const Mat& P2,
1759 1760
        const Mat &points1, const Mat &points2,
        Mat &points4D );
1761 1762 1763
    virtual void correct( const Mat& F,
        const Mat &points1, const Mat &points2,
        Mat &newPoints1, Mat &newPoints2 );
1764 1765 1766
};

double CV_StereoCalibrationTest_CPP::calibrateStereoCamera( const vector<vector<Point3f> >& objectPoints,
1767 1768 1769 1770 1771 1772 1773 1774 1775
                                                            const vector<vector<Point2f> >& imagePoints1,
                                                            const vector<vector<Point2f> >& imagePoints2,
                                                            Mat& cameraMatrix1, Mat& distCoeffs1,
                                                            Mat& cameraMatrix2, Mat& distCoeffs2,
                                                            Size imageSize, Mat& R, Mat& T,
                                                            Mat& E, Mat& F,
                                                            std::vector<RotMat>& rotationMatrices, std::vector<Vec3d>& translationVectors,
                                                            vector<double>& perViewErrors1, vector<double>& perViewErrors2,
                                                            TermCriteria criteria, int flags )
1776
{
1777 1778 1779
    vector<Mat> rvecs, tvecs;
    Mat perViewErrorsMat;
    double avgErr = stereoCalibrate( objectPoints, imagePoints1, imagePoints2,
1780 1781 1782 1783
                                     cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2,
                                     imageSize, R, T, E, F,
                                     rvecs, tvecs, perViewErrorsMat,
                                     flags, criteria );
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795

    size_t numImgs = imagePoints1.size();

    if (perViewErrors1.size() != numImgs)
    {
        perViewErrors1.resize(numImgs);
    }
    if (perViewErrors2.size() != numImgs)
    {
        perViewErrors2.resize(numImgs);
    }

1796
    for (int i = 0; i < (int)numImgs; i++)
1797
    {
1798 1799
        perViewErrors1[i] = perViewErrorsMat.at<double>(i, 0);
        perViewErrors2[i] = perViewErrorsMat.at<double>(i, 1);
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
    }

    if (rotationMatrices.size() != numImgs)
    {
        rotationMatrices.resize(numImgs);
    }
    if (translationVectors.size() != numImgs)
    {
        translationVectors.resize(numImgs);
    }

1811
    for( size_t i = 0; i < numImgs; i++ )
1812 1813 1814 1815 1816 1817 1818
    {
        Mat r9;
        cv::Rodrigues( rvecs[i], r9 );
        r9.convertTo(rotationMatrices[i], CV_64F);
        tvecs[i].convertTo(translationVectors[i], CV_64F);
    }
    return avgErr;
1819 1820 1821
}

void CV_StereoCalibrationTest_CPP::rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1,
A
Andrey Kamaev 已提交
1822 1823 1824 1825 1826
                                         const Mat& cameraMatrix2, const Mat& distCoeffs2,
                                         Size imageSize, const Mat& R, const Mat& T,
                                         Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q,
                                         double alpha, Size newImageSize,
                                         Rect* validPixROI1, Rect* validPixROI2, int flags )
1827
{
A
Andrey Kamaev 已提交
1828 1829
    stereoRectify( cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2,
                imageSize, R, T, R1, R2, P1, P2, Q, flags, alpha, newImageSize,validPixROI1, validPixROI2 );
1830 1831 1832
}

bool CV_StereoCalibrationTest_CPP::rectifyUncalibrated( const Mat& points1,
A
Andrey Kamaev 已提交
1833
                       const Mat& points2, const Mat& F, Size imgSize, Mat& H1, Mat& H2, double threshold )
1834
{
A
Andrey Kamaev 已提交
1835
    return stereoRectifyUncalibrated( points1, points2, F, imgSize, H1, H2, threshold );
1836 1837
}

1838 1839 1840 1841 1842 1843 1844
void CV_StereoCalibrationTest_CPP::triangulate( const Mat& P1, const Mat& P2,
        const Mat &points1, const Mat &points2,
        Mat &points4D )
{
    triangulatePoints(P1, P2, points1, points2, points4D);
}

1845 1846 1847 1848 1849 1850 1851
void CV_StereoCalibrationTest_CPP::correct( const Mat& F,
        const Mat &points1, const Mat &points2,
        Mat &newPoints1, Mat &newPoints2 )
{
    correctMatches(F, points1, points2, newPoints1, newPoints2);
}

1852 1853 1854 1855 1856
///////////////////////////////////////////////////////////////////////////////////////////////////

TEST(Calib3d_CalibrateCamera_CPP, regression) { CV_CameraCalibrationTest_CPP test; test.safe_run(); }
TEST(Calib3d_CalibrationMatrixValues_CPP, accuracy) { CV_CalibrationMatrixValuesTest_CPP test; test.safe_run(); }
TEST(Calib3d_ProjectPoints_CPP, regression) { CV_ProjectPointsTest_CPP test; test.safe_run(); }
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033

TEST(Calib3d_ProjectPoints_CPP, inputShape)
{
    Matx31d rvec = Matx31d::zeros();
    Matx31d tvec(0, 0, 1);
    Matx33d cameraMatrix = Matx33d::eye();
    const float L = 0.1f;
    {
        //3xN 1-channel
        Mat objectPoints = (Mat_<float>(3, 2) << -L,  L,
                                                  L,  L,
                                                  0,  0);
        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.cols, static_cast<int>(imagePoints.size()));
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        //Nx2 1-channel
        Mat objectPoints = (Mat_<float>(2, 3) << -L,  L, 0,
                                                  L,  L, 0);
        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.rows, static_cast<int>(imagePoints.size()));
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        //1xN 3-channel
        Mat objectPoints(1, 2, CV_32FC3);
        objectPoints.at<Vec3f>(0,0) = Vec3f(-L, L, 0);
        objectPoints.at<Vec3f>(0,1) = Vec3f(L, L, 0);

        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.cols, static_cast<int>(imagePoints.size()));
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        //Nx1 3-channel
        Mat objectPoints(2, 1, CV_32FC3);
        objectPoints.at<Vec3f>(0,0) = Vec3f(-L, L, 0);
        objectPoints.at<Vec3f>(1,0) = Vec3f(L, L, 0);

        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.rows, static_cast<int>(imagePoints.size()));
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        //vector<Point3f>
        vector<Point3f> objectPoints;
        objectPoints.push_back(Point3f(-L, L, 0));
        objectPoints.push_back(Point3f(L, L, 0));

        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.size(), imagePoints.size());
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        //vector<Point3d>
        vector<Point3d> objectPoints;
        objectPoints.push_back(Point3d(-L, L, 0));
        objectPoints.push_back(Point3d(L, L, 0));

        vector<Point2d> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.size(), imagePoints.size());
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<double>::epsilon());
    }
}

TEST(Calib3d_ProjectPoints_CPP, outputShape)
{
    Matx31d rvec = Matx31d::zeros();
    Matx31d tvec(0, 0, 1);
    Matx33d cameraMatrix = Matx33d::eye();
    const float L = 0.1f;
    {
        vector<Point3f> objectPoints;
        objectPoints.push_back(Point3f(-L,  L, 0));
        objectPoints.push_back(Point3f( L,  L, 0));
        objectPoints.push_back(Point3f( L, -L, 0));

        //Mat --> will be Nx1 2-channel
        Mat imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(static_cast<int>(objectPoints.size()), imagePoints.rows);
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(0), -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(1,0)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(1,0)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(2,0)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(2,0)(1), -L, std::numeric_limits<float>::epsilon());
    }
    {
        vector<Point3f> objectPoints;
        objectPoints.push_back(Point3f(-L,  L, 0));
        objectPoints.push_back(Point3f( L,  L, 0));
        objectPoints.push_back(Point3f( L, -L, 0));

        //Nx1 2-channel
        Mat imagePoints(3,1,CV_32FC2);
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(static_cast<int>(objectPoints.size()), imagePoints.rows);
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(0), -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(1,0)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(1,0)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(2,0)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(2,0)(1), -L, std::numeric_limits<float>::epsilon());
    }
    {
        vector<Point3f> objectPoints;
        objectPoints.push_back(Point3f(-L,  L, 0));
        objectPoints.push_back(Point3f( L,  L, 0));
        objectPoints.push_back(Point3f( L, -L, 0));

        //1xN 2-channel
        Mat imagePoints(1,3,CV_32FC2);
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(static_cast<int>(objectPoints.size()), imagePoints.cols);
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(0), -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,0)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,1)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,1)(1),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,2)(0),  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints.at<Vec2f>(0,2)(1), -L, std::numeric_limits<float>::epsilon());
    }
    {
        vector<Point3f> objectPoints;
        objectPoints.push_back(Point3f(-L, L, 0));
        objectPoints.push_back(Point3f(L, L, 0));

        //vector<Point2f>
        vector<Point2f> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.size(), imagePoints.size());
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<float>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<float>::epsilon());
    }
    {
        vector<Point3d> objectPoints;
        objectPoints.push_back(Point3d(-L, L, 0));
        objectPoints.push_back(Point3d(L, L, 0));

        //vector<Point2d>
        vector<Point2d> imagePoints;
        projectPoints(objectPoints, rvec, tvec, cameraMatrix, noArray(), imagePoints);
        EXPECT_EQ(objectPoints.size(), imagePoints.size());
        EXPECT_NEAR(imagePoints[0].x, -L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[0].y,  L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[1].x,  L, std::numeric_limits<double>::epsilon());
        EXPECT_NEAR(imagePoints[1].y,  L, std::numeric_limits<double>::epsilon());
    }
}

2034
TEST(Calib3d_StereoCalibrate_CPP, regression) { CV_StereoCalibrationTest_CPP test; test.safe_run(); }
2035

2036

2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
TEST(Calib3d_StereoCalibrate_CPP, extended)
{
    cvtest::TS* ts = cvtest::TS::ptr();
    String filepath = cv::format("%scv/stereo/case%d/", ts->get_data_path().c_str(), 1 );

    Mat left = imread(filepath+"left01.png");
    Mat right = imread(filepath+"right01.png");
    if(left.empty() || right.empty())
    {
        ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
        return;
    }

    vector<vector<Point2f> > imgpt1(1), imgpt2(1);
    vector<vector<Point3f> > objpt(1);
    Size patternSize(9, 6), imageSize(640, 480);
    bool found1 = findChessboardCorners(left, patternSize, imgpt1[0]);
    bool found2 = findChessboardCorners(right, patternSize, imgpt2[0]);

    if(!found1 || !found2)
    {
        ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
        return;
    }

    for( int j = 0; j < patternSize.width*patternSize.height; j++ )
        objpt[0].push_back(Point3f((float)(j%patternSize.width), (float)(j/patternSize.width), 0.f));

    Mat K1, K2, c1, c2, R, T, E, F, err;
    int flags = 0;
    double res0 = stereoCalibrate( objpt, imgpt1, imgpt2,
                    K1, c1, K2, c2,
                    imageSize, R, T, E, F, err, flags);

    flags = CALIB_USE_EXTRINSIC_GUESS;
    double res1 = stereoCalibrate( objpt, imgpt1, imgpt2,
                    K1, c1, K2, c2,
                    imageSize, R, T, E, F, err, flags);
2075 2076

    EXPECT_LE(res1, res0);
2077 2078 2079
    EXPECT_TRUE(err.total() == 2);
}

2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
TEST(Calib3d_StereoCalibrate, regression_10791)
{
    const Matx33d M1(
        853.1387981631528, 0, 704.154907802121,
        0, 853.6445089162528, 520.3600712930319,
        0, 0, 1
    );
    const Matx33d M2(
        848.6090216909176, 0, 701.6162856852185,
        0, 849.7040162357157, 509.1864036137,
        0, 0, 1
    );
    const Matx<double, 14, 1> D1(-6.463598629567206, 79.00104930508179, -0.0001006144444464403, -0.0005437499822299972,
        12.56900616588467, -6.056719942752855, 76.3842481414836, 45.57460250612659,
        0, 0, 0, 0, 0, 0);
    const Matx<double, 14, 1> D2(0.6123436439798265, -0.4671756923224087, -0.0001261947899033442, -0.000597334584036978,
        -0.05660119809538371, 1.037075740629769, -0.3076042835831711, -0.2502169324283623,
        0, 0, 0, 0, 0, 0);

    const Matx33d R(
        0.9999926627018476, -0.0001095586963765905, 0.003829169539302921,
        0.0001021735876758584, 0.9999981346680941, 0.0019287874145156,
        -0.003829373712065528, -0.001928382022437616, 0.9999908085776333
    );
    const Matx31d T(-58.9161771697128, -0.01581306249996402, -0.8492960216760961);

    const Size imageSize(1280, 960);

    Mat R1, R2, P1, P2, Q;
    Rect roi1, roi2;
    stereoRectify(M1, D1, M2, D2, imageSize, R, T,
                  R1, R2, P1, P2, Q,
                  CALIB_ZERO_DISPARITY, 1, imageSize, &roi1, &roi2);

    EXPECT_GE(roi1.area(), 400*300) << roi1;
    EXPECT_GE(roi2.area(), 400*300) << roi2;
}

2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
TEST(Calib3d_StereoCalibrate, regression_11131)
{
    const Matx33d M1(
        1457.572438721727, 0, 1212.945694211622,
        0, 1457.522226502963, 1007.32058848921,
        0, 0, 1
    );
    const Matx33d M2(
        1460.868570835972, 0, 1215.024068023046,
        0, 1460.791367088, 1011.107202932225,
        0, 0, 1
    );
    const Matx<double, 5, 1> D1(0, 0, 0, 0, 0);
    const Matx<double, 5, 1> D2(0, 0, 0, 0, 0);

    const Matx33d R(
        0.9985404059825475, 0.02963547172078553, -0.04515303352041626,
        -0.03103795276460111, 0.9990471552537432, -0.03068268351343364,
        0.04420071389006859, 0.03203935697372317, 0.9985087763742083
    );
    const Matx31d T(0.9995500167379527, 0.0116311595111068, 0.02764923448462666);

    const Size imageSize(2456, 2058);

    Mat R1, R2, P1, P2, Q;
    Rect roi1, roi2;
    stereoRectify(M1, D1, M2, D2, imageSize, R, T,
                  R1, R2, P1, P2, Q,
                  CALIB_ZERO_DISPARITY, 1, imageSize, &roi1, &roi2);

    EXPECT_GT(P1.at<double>(0, 0), 0);
    EXPECT_GT(P2.at<double>(0, 0), 0);
    EXPECT_GT(R1.at<double>(0, 0), 0);
    EXPECT_GT(R2.at<double>(0, 0), 0);
    EXPECT_GE(roi1.area(), 400*300) << roi1;
    EXPECT_GE(roi2.area(), 400*300) << roi2;
}

R
Rostislav Vasilikhin 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
TEST(Calib_StereoCalibrate, regression_22421)
{
    cv::Mat K1, K2, dist1, dist2;
    std::vector<Mat> image_points1, image_points2;
    Mat desiredR, desiredT;

    std::string fname = cvtest::TS::ptr()->get_data_path() + std::string("/cv/cameracalibration/regression22421.yaml.gz");
    FileStorage fs(fname, FileStorage::Mode::READ);
    ASSERT_TRUE(fs.isOpened());
    fs["imagePoints1"] >> image_points1;
    fs["imagePoints2"] >> image_points2;
    fs["K1"] >> K1;
    fs["K2"] >> K2;
    fs["dist1"] >> dist1;
    fs["dist2"] >> dist2;
    fs["desiredR"] >> desiredR;
    fs["desiredT"] >> desiredT;

    std::vector<float> obj_points = {0, 0, 0,
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
                                     0.5f, 0, 0,
                                     1.f, 0, 0,
                                     1.5000001f, 0, 0,
                                     2.0f, 0, 0,
                                     0, 0.5f, 0,
                                     0.5f, 0.5f, 0,
                                     1.f, 0.5, 0,
                                     1.5000001f, 0.5f, 0,
                                     2.f, 0.5f, 0,
                                     0, 1.f, 0,
                                     0.5f, 1.f, 0,
                                     1.f, 1.f, 0,
                                     1.5000001f, 1.f, 0,
                                     2.f, 1.f, 0,
                                     0, 1.5000001f, 0,
                                     0.5f, 1.5000001f, 0,
                                     1.f, 1.5000001f, 0,
                                     1.5000001f, 1.5000001f, 0,
                                     2.f, 1.5000001f, 0};
R
Rostislav Vasilikhin 已提交
2194 2195

    cv::Mat obj_points_mat(obj_points, true);
2196
    obj_points_mat = obj_points_mat.reshape(1, int(obj_points.size()) / 3);
R
Rostislav Vasilikhin 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
    std::vector<cv::Mat> grid_points(image_points1.size(), obj_points_mat);

    cv::Mat R, T;
    double error = cv::stereoCalibrate(grid_points, image_points1, image_points2,
                                       K1, dist1, K2, dist2, cv::Size(), R, T,
                                       cv::noArray(), cv::noArray(), cv::noArray(), cv::CALIB_FIX_INTRINSIC);

    EXPECT_LE(error, 0.071544);

    double rerr = cv::norm(R, desiredR, NORM_INF);
    double terr = cv::norm(T, desiredT, NORM_INF);

    EXPECT_LE(rerr, 0.0000001);
    EXPECT_LE(terr, 0.0000001);
}

2213 2214
TEST(Calib3d_Triangulate, accuracy)
{
2215 2216
    // the testcase from http://code.opencv.org/issues/4334
    {
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
    double P1data[] = { 250, 0, 200, 0, 0, 250, 150, 0, 0, 0, 1, 0 };
    double P2data[] = { 250, 0, 200, -250, 0, 250, 150, 0, 0, 0, 1, 0 };
    Mat P1(3, 4, CV_64F, P1data), P2(3, 4, CV_64F, P2data);

    float x1data[] = { 200.f, 0.f };
    float x2data[] = { 170.f, 1.f };
    float Xdata[] = { 0.f, -5.f, 25/3.f };
    Mat x1(2, 1, CV_32F, x1data);
    Mat x2(2, 1, CV_32F, x2data);
    Mat res0(1, 3, CV_32F, Xdata);
    Mat res_, res;

    triangulatePoints(P1, P2, x1, x2, res_);
A
Alexander Alekhin 已提交
2230
    cv::transpose(res_, res_); // TODO cvtest (transpose doesn't support inplace)
2231 2232 2233
    convertPointsFromHomogeneous(res_, res);
    res = res.reshape(1, 1);

2234 2235 2236
    cout << "[1]:" << endl;
    cout << "\tres0: " << res0 << endl;
    cout << "\tres: " << res << endl;
2237

A
Alexander Alekhin 已提交
2238
    ASSERT_LE(cvtest::norm(res, res0, NORM_INF), 1e-1);
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    }

    // another testcase http://code.opencv.org/issues/3461
    {
    Matx33d K1(6137.147949, 0.000000, 644.974609,
               0.000000, 6137.147949, 573.442749,
               0.000000, 0.000000,  1.000000);
    Matx33d K2(6137.147949,  0.000000, 644.674438,
               0.000000, 6137.147949, 573.079834,
               0.000000,  0.000000, 1.000000);

    Matx34d RT1(1, 0, 0, 0,
                0, 1, 0, 0,
                0, 0, 1, 0);

    Matx34d RT2(0.998297, 0.0064108, -0.0579766,     143.614334,
               -0.0065818, 0.999975, -0.00275888,   -5.160085,
               0.0579574, 0.00313577, 0.998314,     96.066109);

    Matx34d P1 = K1*RT1;
    Matx34d P2 = K2*RT2;

    float x1data[] = { 438.f, 19.f };
    float x2data[] = { 452.363600f, 16.452225f };
    float Xdata[] = { -81.049530f, -215.702804f, 2401.645449f };
    Mat x1(2, 1, CV_32F, x1data);
    Mat x2(2, 1, CV_32F, x2data);
    Mat res0(1, 3, CV_32F, Xdata);
    Mat res_, res;

    triangulatePoints(P1, P2, x1, x2, res_);
A
Alexander Alekhin 已提交
2270
    cv::transpose(res_, res_); // TODO cvtest (transpose doesn't support inplace)
2271 2272 2273 2274 2275 2276 2277
    convertPointsFromHomogeneous(res_, res);
    res = res.reshape(1, 1);

    cout << "[2]:" << endl;
    cout << "\tres0: " << res0 << endl;
    cout << "\tres: " << res << endl;

A
Alexander Alekhin 已提交
2278
    ASSERT_LE(cvtest::norm(res, res0, NORM_INF), 2);
2279
    }
2280
}
A
Alexander Alekhin 已提交
2281

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
///////////////////////////////////////////////////////////////////////////////////////////////////

TEST(CV_RecoverPoseTest, regression_15341)
{
    // initialize test data
    const int invalid_point_count = 2;
    const float _points1_[] = {
        1537.7f, 166.8f,
        1599.1f, 179.6f,
        1288.0f, 207.5f,
        1507.1f, 193.2f,
        1742.7f, 210.0f,
        1041.6f, 271.7f,
        1591.8f, 247.2f,
        1524.0f, 261.3f,
        1330.3f, 285.0f,
        1403.1f, 284.0f,
        1506.6f, 342.9f,
        1502.8f, 347.3f,
        1344.9f, 364.9f,
        0.0f, 0.0f  // last point is initial invalid
    };

    const float _points2_[] = {
        1533.4f, 532.9f,
        1596.6f, 552.4f,
        1277.0f, 556.4f,
        1502.1f, 557.6f,
        1744.4f, 601.3f,
        1023.0f, 612.6f,
        1589.2f, 621.6f,
        1519.4f, 629.0f,
        1320.3f, 637.3f,
        1395.2f, 642.2f,
        1501.5f, 710.3f,
        1497.6f, 714.2f,
        1335.1f, 719.61f,
        1000.0f, 1000.0f  // last point is initial invalid
    };

    vector<Point2f> _points1; Mat(14, 1, CV_32FC2, (void*)_points1_).copyTo(_points1);
    vector<Point2f> _points2; Mat(14, 1, CV_32FC2, (void*)_points2_).copyTo(_points2);

    const int point_count = (int) _points1.size();
    CV_Assert(point_count == (int) _points2.size());

    // camera matrix with both focal lengths = 1, and principal point = (0, 0)
    const Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340

    // camera matrix with focal lengths 0.5 and 0.6 respectively and principal point = (100, 200)
    double cameraMatrix2Data[] = { 0.5, 0, 100,
                                   0, 0.6, 200,
                                   0, 0, 1 };
    const Mat cameraMatrix2( 3, 3, CV_64F, cameraMatrix2Data );

    // zero and nonzero distortion coefficients
    double nonZeroDistCoeffsData[] = { 0.01, 0.0001, 0, 0, 1e-04, 0.2, 0.02, 0.0002 }; // k1, k2, p1, p2, k3, k4, k5, k6
    vector<Mat> distCoeffsList = {Mat::zeros(1, 5, CV_64F), Mat{1, 8, CV_64F, nonZeroDistCoeffsData}};
    const auto &zeroDistCoeffs = distCoeffsList[0];
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354

    int Inliers = 0;

    const int ntests = 3;
    for (int testcase = 1; testcase <= ntests; ++testcase)
    {
        if (testcase == 1) // testcase with vector input data
        {
            // init temporary test data
            vector<unsigned char> mask(point_count);
            vector<Point2f> points1(_points1);
            vector<Point2f> points2(_points2);

            // Estimation of fundamental matrix using the RANSAC algorithm
2355
            Mat E, E2, R, t;
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367

            // Check pose when camera matrices are different.
            for (const auto &distCoeffs: distCoeffsList)
            {
                E = findEssentialMat(points1, points2, cameraMatrix, distCoeffs, cameraMatrix2, distCoeffs, RANSAC, 0.999, 1.0, mask);
                recoverPose(points1, points2, cameraMatrix, distCoeffs, cameraMatrix2, distCoeffs, E2, R, t, RANSAC, 0.999, 1.0, mask);
                EXPECT_LT(cv::norm(E, E2, NORM_INF), 1e-4) <<
                    "Two big difference between the same essential matrices computed using different functions with different cameras, testcase " << testcase;
                EXPECT_EQ(0, (int)mask[13]) << "Detecting outliers in function failed with different cameras, testcase " << testcase;
            }

            // Check pose when camera matrices are the same.
2368
            E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, 1000/*maxIters*/, mask);
2369 2370
            E2 = findEssentialMat(points1, points2, cameraMatrix, zeroDistCoeffs, cameraMatrix, zeroDistCoeffs, RANSAC, 0.999, 1.0, mask);
            EXPECT_LT(cv::norm(E, E2, NORM_INF), 1e-4) <<
2371 2372
                "Two big difference between the same essential matrices computed using different functions with same cameras, testcase " << testcase;
            EXPECT_EQ(0, (int)mask[13]) << "Detecting outliers in function findEssentialMat failed with same cameras, testcase " << testcase;
2373 2374
            points2[12] = Point2f(0.0f, 0.0f); // provoke another outlier detection for recover Pose
            Inliers = recoverPose(E, points1, points2, cameraMatrix, R, t, mask);
2375
            EXPECT_EQ(0, (int)mask[12]) << "Detecting outliers in function failed with same cameras, testcase " << testcase;
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
        }
        else // testcase with mat input data
        {
            Mat points1(_points1, true);
            Mat points2(_points2, true);
            Mat mask;

            if (testcase == 2)
            {
                // init temporary testdata
                mask = Mat::zeros(point_count, 1, CV_8UC1);
            }
            else // testcase == 3 - with transposed mask
            {
                mask = Mat::zeros(1, point_count, CV_8UC1);
            }

            // Estimation of fundamental matrix using the RANSAC algorithm
2394
            Mat E, E2, R, t;
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

            // Check pose when camera matrices are different.
            for (const auto &distCoeffs: distCoeffsList)
            {
                E = findEssentialMat(points1, points2, cameraMatrix, distCoeffs, cameraMatrix2, distCoeffs, RANSAC, 0.999, 1.0, mask);
                recoverPose(points1, points2, cameraMatrix, distCoeffs, cameraMatrix2, distCoeffs, E2, R, t, RANSAC, 0.999, 1.0, mask);
                EXPECT_LT(cv::norm(E, E2, NORM_INF), 1e-4) <<
                    "Two big difference between the same essential matrices computed using different functions with different cameras, testcase " << testcase;
                EXPECT_EQ(0, (int)mask.at<unsigned char>(13)) << "Detecting outliers in function failed with different cameras, testcase " << testcase;
            }

            // Check pose when camera matrices are the same.
2407
            E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, 1000/*maxIters*/, mask);
2408 2409
            E2 = findEssentialMat(points1, points2, cameraMatrix, zeroDistCoeffs, cameraMatrix, zeroDistCoeffs, RANSAC, 0.999, 1.0, mask);
            EXPECT_LT(cv::norm(E, E2, NORM_INF), 1e-4) <<
2410 2411
                "Two big difference between the same essential matrices computed using different functions with same cameras, testcase " << testcase;
            EXPECT_EQ(0, (int)mask.at<unsigned char>(13)) << "Detecting outliers in function findEssentialMat failed with same cameras, testcase " << testcase;
2412 2413
            points2.at<Point2f>(12) = Point2f(0.0f, 0.0f); // provoke an outlier detection
            Inliers = recoverPose(E, points1, points2, cameraMatrix, R, t, mask);
2414
            EXPECT_EQ(0, (int)mask.at<unsigned char>(12)) << "Detecting outliers in function failed with same cameras, testcase " << testcase;
2415 2416 2417 2418 2419 2420
        }
        EXPECT_EQ(Inliers, point_count - invalid_point_count) <<
            "Number of inliers differs from expected number of inliers, testcase " << testcase;
    }
}

A
Alexander Alekhin 已提交
2421
}} // namespace