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


#include "precomp.hpp"
#include <float.h>
#include <limits.h>

/* Valery Mosyagin */

#undef quad

#define EPS64D 1e-9

int cvComputeEssentialMatrix(  CvMatr32f rotMatr,
                                    CvMatr32f transVect,
                                    CvMatr32f essMatr);

int cvConvertEssential2Fundamental( CvMatr32f essMatr,
                                         CvMatr32f fundMatr,
                                         CvMatr32f cameraMatr1,
                                         CvMatr32f cameraMatr2);

int cvComputeEpipolesFromFundMatrix(CvMatr32f fundMatr,
                                         CvPoint3D32f* epipole1,
                                         CvPoint3D32f* epipole2);

void icvTestPoint( CvPoint2D64d testPoint,
                CvVect64d line1,CvVect64d line2,
                CvPoint2D64d basePoint,
                int* result);



int icvGetSymPoint3D(  CvPoint3D64d pointCorner,
                            CvPoint3D64d point1,
                            CvPoint3D64d point2,
                            CvPoint3D64d *pointSym2)
{
    double len1,len2;
    double alpha;
    icvGetPieceLength3D(pointCorner,point1,&len1);
    if( len1 < EPS64D )
    {
        return CV_BADARG_ERR;
    }
    icvGetPieceLength3D(pointCorner,point2,&len2);
    alpha = len2 / len1;

    pointSym2->x = pointCorner.x + alpha*(point1.x - pointCorner.x);
    pointSym2->y = pointCorner.y + alpha*(point1.y - pointCorner.y);
    pointSym2->z = pointCorner.z + alpha*(point1.z - pointCorner.z);
    return CV_NO_ERR;
}

/*  author Valery Mosyagin */

/* Compute 3D point for scanline and alpha betta */
int icvCompute3DPoint( double alpha,double betta,
                            CvStereoLineCoeff* coeffs,
                            CvPoint3D64d* point)
{

    double partX;
    double partY;
    double partZ;
    double partAll;
    double invPartAll;

    double alphabetta = alpha*betta;
109

110 111 112 113 114 115 116 117 118
    partAll = alpha - betta;
    if( fabs(partAll) > 0.00001  ) /* alpha must be > betta */
    {

        partX   = coeffs->Xcoef        + coeffs->XcoefA *alpha +
                  coeffs->XcoefB*betta + coeffs->XcoefAB*alphabetta;

        partY   = coeffs->Ycoef        + coeffs->YcoefA *alpha +
                  coeffs->YcoefB*betta + coeffs->YcoefAB*alphabetta;
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
        partZ   = coeffs->Zcoef        + coeffs->ZcoefA *alpha +
                  coeffs->ZcoefB*betta + coeffs->ZcoefAB*alphabetta;

        invPartAll = 1.0 / partAll;

        point->x = partX * invPartAll;
        point->y = partY * invPartAll;
        point->z = partZ * invPartAll;
        return CV_NO_ERR;
    }
    else
    {
        return CV_BADFACTOR_ERR;
    }
}

/*--------------------------------------------------------------------------------------*/

/* Compute rotate matrix and trans vector for change system */
int icvCreateConvertMatrVect( CvMatr64d     rotMatr1,
                                CvMatr64d     transVect1,
                                CvMatr64d     rotMatr2,
                                CvMatr64d     transVect2,
                                CvMatr64d     convRotMatr,
                                CvMatr64d     convTransVect)
{
    double invRotMatr2[9];
    double tmpVect[3];


    icvInvertMatrix_64d(rotMatr2,3,invRotMatr2);
    /* Test for error */

    icvMulMatrix_64d(   rotMatr1,
                        3,3,
                        invRotMatr2,
                        3,3,
                        convRotMatr);

    icvMulMatrix_64d(   convRotMatr,
                        3,3,
                        transVect2,
162
                        1,3,
163
                        tmpVect);
164

165 166
    icvSubVector_64d(transVect1,tmpVect,convTransVect,3);

167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    return CV_NO_ERR;
}

/*--------------------------------------------------------------------------------------*/

/* Compute point coordinates in other system */
int icvConvertPointSystem(CvPoint3D64d  M2,
                            CvPoint3D64d* M1,
                            CvMatr64d     rotMatr,
                            CvMatr64d     transVect
                            )
{
    double tmpVect[3];

    icvMulMatrix_64d(   rotMatr,
                        3,3,
                        (double*)&M2,
185
                        1,3,
186 187 188
                        tmpVect);

    icvAddVector_64d(tmpVect,transVect,(double*)M1,3);
189

190 191 192
    return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
193
static int icvComputeCoeffForStereoV3( double quad1[4][2],
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                                double quad2[4][2],
                                int    numScanlines,
                                CvMatr64d    camMatr1,
                                CvMatr64d    rotMatr1,
                                CvMatr64d    transVect1,
                                CvMatr64d    camMatr2,
                                CvMatr64d    rotMatr2,
                                CvMatr64d    transVect2,
                                CvStereoLineCoeff*    startCoeffs,
                                int* needSwapCamera)
{
    /* For each pair */
    /* In this function we must define position of cameras */

    CvPoint2D64d point1;
    CvPoint2D64d point2;
    CvPoint2D64d point3;
    CvPoint2D64d point4;

    int currLine;
    *needSwapCamera = 0;
    for( currLine = 0; currLine < numScanlines; currLine++ )
    {
        /* Compute points */
        double alpha = ((double)currLine)/((double)(numScanlines)); /* maybe - 1 */

        point1.x = (1.0 - alpha) * quad1[0][0] + alpha * quad1[3][0];
        point1.y = (1.0 - alpha) * quad1[0][1] + alpha * quad1[3][1];

        point2.x = (1.0 - alpha) * quad1[1][0] + alpha * quad1[2][0];
        point2.y = (1.0 - alpha) * quad1[1][1] + alpha * quad1[2][1];
225

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        point3.x = (1.0 - alpha) * quad2[0][0] + alpha * quad2[3][0];
        point3.y = (1.0 - alpha) * quad2[0][1] + alpha * quad2[3][1];

        point4.x = (1.0 - alpha) * quad2[1][0] + alpha * quad2[2][0];
        point4.y = (1.0 - alpha) * quad2[1][1] + alpha * quad2[2][1];

        /* We can compute coeffs for this line */
        icvComCoeffForLine(    point1,
                            point2,
                            point3,
                            point4,
                            camMatr1,
                            rotMatr1,
                            transVect1,
                            camMatr2,
                            rotMatr2,
                            transVect2,
                            &startCoeffs[currLine],
                            needSwapCamera);
    }
246
    return CV_NO_ERR;
247 248
}
/*--------------------------------------------------------------------------------------*/
249
static int icvComputeCoeffForStereoNew(   double quad1[4][2],
250 251 252 253 254 255 256 257 258 259 260 261 262
                                        double quad2[4][2],
                                        int    numScanlines,
                                        CvMatr32f    camMatr1,
                                        CvMatr32f    rotMatr1,
                                        CvMatr32f    transVect1,
                                        CvMatr32f    camMatr2,
                                        CvStereoLineCoeff*    startCoeffs,
                                        int* needSwapCamera)
{
    /* Convert data */

    double camMatr1_64d[9];
    double camMatr2_64d[9];
263

264 265
    double rotMatr1_64d[9];
    double transVect1_64d[3];
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    double rotMatr2_64d[9];
    double transVect2_64d[3];

    icvCvt_32f_64d(camMatr1,camMatr1_64d,9);
    icvCvt_32f_64d(camMatr2,camMatr2_64d,9);

    icvCvt_32f_64d(rotMatr1,rotMatr1_64d,9);
    icvCvt_32f_64d(transVect1,transVect1_64d,3);

    rotMatr2_64d[0] = 1;
    rotMatr2_64d[1] = 0;
    rotMatr2_64d[2] = 0;
    rotMatr2_64d[3] = 0;
    rotMatr2_64d[4] = 1;
    rotMatr2_64d[5] = 0;
    rotMatr2_64d[6] = 0;
    rotMatr2_64d[7] = 0;
    rotMatr2_64d[8] = 1;

    transVect2_64d[0] = 0;
    transVect2_64d[1] = 0;
    transVect2_64d[2] = 0;

    int status = icvComputeCoeffForStereoV3( quad1,
                                                quad2,
                                                numScanlines,
                                                camMatr1_64d,
                                                rotMatr1_64d,
                                                transVect1_64d,
                                                camMatr2_64d,
                                                rotMatr2_64d,
                                                transVect2_64d,
                                                startCoeffs,
                                                needSwapCamera);


    return status;

}
/*--------------------------------------------------------------------------------------*/
int icvComputeCoeffForStereo(  CvStereoCamera* stereoCamera)
{
    double quad1[4][2];
    double quad2[4][2];

    int i;
    for( i = 0; i < 4; i++ )
    {
        quad1[i][0] = stereoCamera->quad[0][i].x;
        quad1[i][1] = stereoCamera->quad[0][i].y;

        quad2[i][0] = stereoCamera->quad[1][i].x;
        quad2[i][1] = stereoCamera->quad[1][i].y;
    }

    icvComputeCoeffForStereoNew(        quad1,
                                        quad2,
                                        stereoCamera->warpSize.height,
                                        stereoCamera->camera[0]->matrix,
                                        stereoCamera->rotMatrix,
                                        stereoCamera->transVector,
                                        stereoCamera->camera[1]->matrix,
                                        stereoCamera->lineCoeffs,
                                        &(stereoCamera->needSwapCameras));
    return CV_OK;
}


/*--------------------------------------------------------------------------------------*/
int icvComCoeffForLine(   CvPoint2D64d point1,
                            CvPoint2D64d point2,
                            CvPoint2D64d point3,
                            CvPoint2D64d point4,
                            CvMatr64d    camMatr1,
                            CvMatr64d    rotMatr1,
                            CvMatr64d    transVect1,
                            CvMatr64d    camMatr2,
                            CvMatr64d    rotMatr2,
                            CvMatr64d    transVect2,
                            CvStereoLineCoeff* coeffs,
                            int* needSwapCamera)
{
    /* Get direction for all points */
    /* Direction for camera 1 */
351

352 353 354
    CvPoint3D64f direct1;
    CvPoint3D64f direct2;
    CvPoint3D64f camPoint1;
355

356 357 358 359 360
    CvPoint3D64f directS3;
    CvPoint3D64f directS4;
    CvPoint3D64f direct3;
    CvPoint3D64f direct4;
    CvPoint3D64f camPoint2;
361

362 363
    icvGetDirectionForPoint(   point1,
                            camMatr1,
364
                            &direct1);
365

366 367
    icvGetDirectionForPoint(   point2,
                            camMatr1,
368
                            &direct2);
369 370 371 372 373

    /* Direction for camera 2 */

    icvGetDirectionForPoint(   point3,
                            camMatr2,
374
                            &directS3);
375

376 377
    icvGetDirectionForPoint(   point4,
                            camMatr2,
378
                            &directS4);
379 380

    /* Create convertion for camera 2: two direction and camera point */
381

382 383 384 385 386 387 388 389 390 391
    double convRotMatr[9];
    double convTransVect[3];

    icvCreateConvertMatrVect(  rotMatr1,
                            transVect1,
                            rotMatr2,
                            transVect2,
                            convRotMatr,
                            convTransVect);

392 393 394
    CvPoint3D64f zeroVect;
    zeroVect.x = zeroVect.y = zeroVect.z = 0.0;
    camPoint1.x = camPoint1.y = camPoint1.z = 0.0;
395

396 397 398
    icvConvertPointSystem(directS3,&direct3,convRotMatr,convTransVect);
    icvConvertPointSystem(directS4,&direct4,convRotMatr,convTransVect);
    icvConvertPointSystem(zeroVect,&camPoint2,convRotMatr,convTransVect);
399

400
    CvPoint3D64f pointB;
401

402
    int postype = 0;
403

404 405
    /* Changed order */
    /* Compute point B: xB,yB,zB */
406 407 408
    icvGetCrossLines(camPoint1,direct2,
                  camPoint2,direct3,
                  &pointB);
409

410
    if( pointB.z < 0 )/* If negative use other lines for cross */
411 412
    {
        postype = 1;
413 414 415
        icvGetCrossLines(camPoint1,direct1,
                      camPoint2,direct4,
                      &pointB);
416 417 418 419 420 421 422 423 424 425
    }

    CvPoint3D64d pointNewA;
    CvPoint3D64d pointNewC;

    pointNewA.x = pointNewA.y = pointNewA.z = 0;
    pointNewC.x = pointNewC.y = pointNewC.z = 0;

    if( postype == 0 )
    {
426 427 428
        icvGetSymPoint3D(   camPoint1,
                            direct1,
                            pointB,
429 430
                            &pointNewA);

431 432 433
        icvGetSymPoint3D(   camPoint2,
                            direct4,
                            pointB,
434 435 436 437 438
                            &pointNewC);
    }
    else
    {/* In this case we must change cameras */
        *needSwapCamera = 1;
439 440 441
        icvGetSymPoint3D(   camPoint2,
                            direct3,
                            pointB,
442 443
                            &pointNewA);

444 445 446
        icvGetSymPoint3D(   camPoint1,
                            direct2,
                            pointB,
447 448 449 450 451
                            &pointNewC);
    }


    double gamma;
452

453 454 455 456 457 458 459 460
    double xA,yA,zA;
    double xB,yB,zB;
    double xC,yC,zC;

    xA = pointNewA.x;
    yA = pointNewA.y;
    zA = pointNewA.z;

461 462 463
    xB = pointB.x;
    yB = pointB.y;
    zB = pointB.z;
464 465 466 467 468 469 470 471 472 473 474

    xC = pointNewC.x;
    yC = pointNewC.y;
    zC = pointNewC.z;

    double len1,len2;
    len1 = sqrt( (xA-xB)*(xA-xB) + (yA-yB)*(yA-yB) + (zA-zB)*(zA-zB) );
    len2 = sqrt( (xB-xC)*(xB-xC) + (yB-yC)*(yB-yC) + (zB-zC)*(zB-zC) );
    gamma = len2 / len1;

    icvComputeStereoLineCoeffs( pointNewA,
475 476
                                pointB,
                                camPoint1,
477 478
                                gamma,
                                coeffs);
479

480 481 482 483 484 485 486 487 488 489 490 491
    return CV_NO_ERR;
}


/*--------------------------------------------------------------------------------------*/

int icvGetDirectionForPoint(  CvPoint2D64d point,
                                CvMatr64d camMatr,
                                CvPoint3D64d* direct)
{
    /*  */
    double invMatr[9];
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506
    /* Invert matrix */

    icvInvertMatrix_64d(camMatr,3,invMatr);
    /* TEST FOR ERRORS */

    double vect[3];
    vect[0] = point.x;
    vect[1] = point.y;
    vect[2] = 1;

    /* Mul matr */
    icvMulMatrix_64d(   invMatr,
                        3,3,
                        vect,
507
                        1,3,
508 509
                        (double*)direct);

510
    return CV_NO_ERR;
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
}

/*--------------------------------------------------------------------------------------*/

int icvGetCrossLines(CvPoint3D64d point11,CvPoint3D64d point12,
                       CvPoint3D64d point21,CvPoint3D64d point22,
                       CvPoint3D64d* midPoint)
{
    double xM,yM,zM;
    double xN,yN,zN;

    double xA,yA,zA;
    double xB,yB,zB;

    double xC,yC,zC;
    double xD,yD,zD;

    xA = point11.x;
    yA = point11.y;
    zA = point11.z;

    xB = point12.x;
    yB = point12.y;
    zB = point12.z;

    xC = point21.x;
    yC = point21.y;
    zC = point21.z;

    xD = point22.x;
    yD = point22.y;
    zD = point22.z;

    double a11,a12,a21,a22;
    double b1,b2;

    a11 =  (xB-xA)*(xB-xA)+(yB-yA)*(yB-yA)+(zB-zA)*(zB-zA);
    a12 = -(xD-xC)*(xB-xA)-(yD-yC)*(yB-yA)-(zD-zC)*(zB-zA);
    a21 =  (xB-xA)*(xD-xC)+(yB-yA)*(yD-yC)+(zB-zA)*(zD-zC);
    a22 = -(xD-xC)*(xD-xC)-(yD-yC)*(yD-yC)-(zD-zC)*(zD-zC);
    b1  = -( (xA-xC)*(xB-xA)+(yA-yC)*(yB-yA)+(zA-zC)*(zB-zA) );
    b2  = -( (xA-xC)*(xD-xC)+(yA-yC)*(yD-yC)+(zA-zC)*(zD-zC) );

    double delta;
    double deltaA,deltaB;
    double alpha,betta;

    delta  = a11*a22-a12*a21;
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    if( fabs(delta) < EPS64D )
    {
        /*return ERROR;*/
    }

    deltaA = b1*a22-b2*a12;
    deltaB = a11*b2-b1*a21;

    alpha = deltaA / delta;
    betta = deltaB / delta;

    xM = xA+alpha*(xB-xA);
    yM = yA+alpha*(yB-yA);
    zM = zA+alpha*(zB-zA);

    xN = xC+betta*(xD-xC);
    yN = yC+betta*(yD-yC);
    zN = zC+betta*(zD-zC);

    /* Compute middle point */
    midPoint->x = (xM + xN) * 0.5;
    midPoint->y = (yM + yN) * 0.5;
    midPoint->z = (zM + zN) * 0.5;

    return CV_NO_ERR;
}

/*--------------------------------------------------------------------------------------*/

int icvComputeStereoLineCoeffs(   CvPoint3D64d pointA,
                                    CvPoint3D64d pointB,
                                    CvPoint3D64d pointCam1,
                                    double gamma,
                                    CvStereoLineCoeff*    coeffs)
{
    double x1,y1,z1;

    x1 = pointCam1.x;
    y1 = pointCam1.y;
    z1 = pointCam1.z;

    double xA,yA,zA;
    double xB,yB,zB;

    xA = pointA.x;
    yA = pointA.y;
    zA = pointA.z;

    xB = pointB.x;
    yB = pointB.y;
    zB = pointB.z;

    if( gamma > 0 )
    {
        coeffs->Xcoef   = -x1 + xA;
        coeffs->XcoefA  =  xB + x1 - xA;
        coeffs->XcoefB  = -xA - gamma * x1 + gamma * xA;
        coeffs->XcoefAB = -xB + xA + gamma * xB - gamma * xA;

        coeffs->Ycoef   = -y1 + yA;
        coeffs->YcoefA  =  yB + y1 - yA;
        coeffs->YcoefB  = -yA - gamma * y1 + gamma * yA;
        coeffs->YcoefAB = -yB + yA + gamma * yB - gamma * yA;

        coeffs->Zcoef   = -z1 + zA;
        coeffs->ZcoefA  =  zB + z1 - zA;
        coeffs->ZcoefB  = -zA - gamma * z1 + gamma * zA;
        coeffs->ZcoefAB = -zB + zA + gamma * zB - gamma * zA;
    }
    else
    {
        gamma = - gamma;
        coeffs->Xcoef   = -( -x1 + xA);
        coeffs->XcoefB  = -(  xB + x1 - xA);
        coeffs->XcoefA  = -( -xA - gamma * x1 + gamma * xA);
        coeffs->XcoefAB = -( -xB + xA + gamma * xB - gamma * xA);

        coeffs->Ycoef   = -( -y1 + yA);
        coeffs->YcoefB  = -(  yB + y1 - yA);
        coeffs->YcoefA  = -( -yA - gamma * y1 + gamma * yA);
        coeffs->YcoefAB = -( -yB + yA + gamma * yB - gamma * yA);

        coeffs->Zcoef   = -( -z1 + zA);
        coeffs->ZcoefB  = -(  zB + z1 - zA);
        coeffs->ZcoefA  = -( -zA - gamma * z1 + gamma * zA);
        coeffs->ZcoefAB = -( -zB + zA + gamma * zB - gamma * zA);
    }



    return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/


/*---------------------------------------------------------------------------------------*/

/* This function get minimum angle started at point which contains rect */
int icvGetAngleLine( CvPoint2D64d startPoint, CvSize imageSize,CvPoint2D64d *point1,CvPoint2D64d *point2)
{
    /* Get crosslines with image corners */

    /* Find four lines */

    CvPoint2D64d pa,pb,pc,pd;
665

666 667 668 669 670 671 672 673 674 675 676
    pa.x = 0;
    pa.y = 0;

    pb.x = imageSize.width-1;
    pb.y = 0;

    pd.x = imageSize.width-1;
    pd.y = imageSize.height-1;

    pc.x = 0;
    pc.y = imageSize.height-1;
677

678 679
    /* We can compute points for angle */
    /* Test for place section */
680

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    if( startPoint.x < 0 )
    {/* 1,4,7 */
        if( startPoint.y < 0)
        {/* 1 */
            *point1 = pb;
            *point2 = pc;
        }
        else if( startPoint.y > imageSize.height-1 )
        {/* 7 */
            *point1 = pa;
            *point2 = pd;
        }
        else
        {/* 4 */
            *point1 = pa;
            *point2 = pc;
        }
    }
    else if ( startPoint.x > imageSize.width-1 )
    {/* 3,6,9 */
        if( startPoint.y < 0 )
        {/* 3 */
            *point1 = pa;
            *point2 = pd;
        }
        else if ( startPoint.y > imageSize.height-1 )
        {/* 9 */
            *point1 = pb;
            *point2 = pc;
        }
        else
        {/* 6 */
            *point1 = pb;
            *point2 = pd;
        }
    }
    else
    {/* 2,5,8 */
        if( startPoint.y < 0 )
        {/* 2 */
            if( startPoint.x < imageSize.width/2 )
            {
                *point1 = pb;
                *point2 = pa;
            }
            else
            {
                *point1 = pa;
                *point2 = pb;
            }
        }
        else if( startPoint.y > imageSize.height-1 )
        {/* 8 */
            if( startPoint.x < imageSize.width/2 )
            {
                *point1 = pc;
                *point2 = pd;
            }
            else
            {
                *point1 = pd;
                *point2 = pc;
            }
        }
        else
        {/* 5 - point in the image */
            return 2;
        }
    }
    return 0;
}/* GetAngleLine */

/*---------------------------------------------------------------------------------------*/

void icvGetCoefForPiece(   CvPoint2D64d p_start,CvPoint2D64d p_end,
                        double *a,double *b,double *c,
                        int* result)
{
    double det;
    double detA,detB,detC;

    det = p_start.x*p_end.y+p_end.x+p_start.y-p_end.y-p_start.y*p_end.x-p_start.x;
    if( fabs(det) < EPS64D)/* Error */
    {
        *result = 0;
        return;
    }

    detA = p_start.y - p_end.y;
    detB = p_end.x - p_start.x;
    detC = p_start.x*p_end.y - p_end.x*p_start.y;

    double invDet = 1.0 / det;
    *a = detA * invDet;
    *b = detB * invDet;
    *c = detC * invDet;

    *result = 1;
    return;
}

/*---------------------------------------------------------------------------------------*/

/* Get common area of rectifying */
785
static void icvGetCommonArea( CvSize imageSize,
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
                    CvPoint3D64d epipole1,CvPoint3D64d epipole2,
                    CvMatr64d fundMatr,
                    CvVect64d coeff11,CvVect64d coeff12,
                    CvVect64d coeff21,CvVect64d coeff22,
                    int* result)
{
    int res = 0;
    CvPoint2D64d point11;
    CvPoint2D64d point12;
    CvPoint2D64d point21;
    CvPoint2D64d point22;

    double corr11[3];
    double corr12[3];
    double corr21[3];
    double corr22[3];

    double pointW11[3];
    double pointW12[3];
    double pointW21[3];
    double pointW22[3];

    double transFundMatr[3*3];
    /* Compute transpose of fundamental matrix */
    icvTransposeMatrix_64d( fundMatr, 3, 3, transFundMatr );
811

812 813
    CvPoint2D64d epipole1_2d;
    CvPoint2D64d epipole2_2d;
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    if( fabs(epipole1.z) < 1e-8 )
    {/* epipole1 in infinity */
        *result = 0;
        return;
    }
    epipole1_2d.x = epipole1.x / epipole1.z;
    epipole1_2d.y = epipole1.y / epipole1.z;

    if( fabs(epipole2.z) < 1e-8 )
    {/* epipole2 in infinity */
        *result = 0;
        return;
    }
    epipole2_2d.x = epipole2.x / epipole2.z;
    epipole2_2d.y = epipole2.y / epipole2.z;

    int stat = icvGetAngleLine( epipole1_2d, imageSize,&point11,&point12);
    if( stat == 2 )
    {
        /* No angle */
        *result = 0;
        return;
    }

    stat = icvGetAngleLine( epipole2_2d, imageSize,&point21,&point22);
    if( stat == 2 )
    {
        /* No angle */
        *result = 0;
        return;
    }

    /* ============= Computation for line 1 ================ */
    /* Find correspondence line for angle points11 */
    /* corr21 = Fund'*p1 */

    pointW11[0] = point11.x;
    pointW11[1] = point11.y;
    pointW11[2] = 1.0;

    icvTransformVector_64d( transFundMatr, /* !!! Modified from not transposed */
856
                            pointW11,
857 858 859 860 861 862 863 864 865 866
                            corr21,
                            3,3);

    /* Find crossing of line with image 2 */
    CvPoint2D64d start;
    CvPoint2D64d end;
    icvGetCrossRectDirect( imageSize,
                        corr21[0],corr21[1],corr21[2],
                        &start,&end,
                        &res);
867

868 869 870 871 872 873 874 875 876 877 878 879 880 881
    if( res == 0 )
    {/* We have not cross */
        /* We must define new angle */

        pointW21[0] = point21.x;
        pointW21[1] = point21.y;
        pointW21[2] = 1.0;

        /* Find correspondence line for this angle points */
        /* We know point and try to get corr line */
        /* For point21 */
        /* corr11 = Fund * p21 */

        icvTransformVector_64d( fundMatr, /* !!! Modified */
882
                                pointW21,
883 884 885 886 887 888 889 890 891
                                corr11,
                                3,3);

        /* We have cross. And it's result cross for up line. Set result coefs */

        /* Set coefs for line 1 image 1 */
        coeff11[0] = corr11[0];
        coeff11[1] = corr11[1];
        coeff11[2] = corr11[2];
892

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
        /* Set coefs for line 1 image 2 */
        icvGetCoefForPiece(    epipole2_2d,point21,
                            &coeff21[0],&coeff21[1],&coeff21[2],
                            &res);
        if( res == 0 )
        {
            *result = 0;
            return;/* Error */
        }
    }
    else
    {/* Line 1 cross image 2 */
        /* Set coefs for line 1 image 1 */
        icvGetCoefForPiece(    epipole1_2d,point11,
                            &coeff11[0],&coeff11[1],&coeff11[2],
                            &res);
        if( res == 0 )
        {
            *result = 0;
            return;/* Error */
        }
914

915 916 917 918
        /* Set coefs for line 1 image 2 */
        coeff21[0] = corr21[0];
        coeff21[1] = corr21[1];
        coeff21[2] = corr21[2];
919

920 921 922 923 924 925 926 927 928 929 930
    }

    /* ============= Computation for line 2 ================ */
    /* Find correspondence line for angle points11 */
    /* corr22 = Fund*p2 */

    pointW12[0] = point12.x;
    pointW12[1] = point12.y;
    pointW12[2] = 1.0;

    icvTransformVector_64d( transFundMatr,
931
                            pointW12,
932 933 934 935 936 937 938 939
                            corr22,
                            3,3);

    /* Find crossing of line with image 2 */
    icvGetCrossRectDirect( imageSize,
                        corr22[0],corr22[1],corr22[2],
                        &start,&end,
                        &res);
940

941 942 943 944 945 946 947 948 949 950 951 952 953 954
    if( res == 0 )
    {/* We have not cross */
        /* We must define new angle */

        pointW22[0] = point22.x;
        pointW22[1] = point22.y;
        pointW22[2] = 1.0;

        /* Find correspondence line for this angle points */
        /* We know point and try to get corr line */
        /* For point21 */
        /* corr2 = Fund' * p1 */

        icvTransformVector_64d( fundMatr,
955
                                pointW22,
956 957 958
                                corr12,
                                3,3);

959

960 961 962 963 964 965
        /* We have cross. And it's result cross for down line. Set result coefs */

        /* Set coefs for line 2 image 1 */
        coeff12[0] = corr12[0];
        coeff12[1] = corr12[1];
        coeff12[2] = corr12[2];
966

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
        /* Set coefs for line 1 image 2 */
        icvGetCoefForPiece(    epipole2_2d,point22,
                            &coeff22[0],&coeff22[1],&coeff22[2],
                            &res);
        if( res == 0 )
        {
            *result = 0;
            return;/* Error */
        }
    }
    else
    {/* Line 2 cross image 2 */
        /* Set coefs for line 2 image 1 */
        icvGetCoefForPiece(    epipole1_2d,point12,
                            &coeff12[0],&coeff12[1],&coeff12[2],
                            &res);
        if( res == 0 )
        {
            *result = 0;
            return;/* Error */
        }
988

989 990 991 992
        /* Set coefs for line 1 image 2 */
        coeff22[0] = corr22[0];
        coeff22[1] = corr22[1];
        coeff22[2] = corr22[2];
993

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    }

    /* Now we know common area */

    return;

}/* GetCommonArea */

/*---------------------------------------------------------------------------------------*/

/* Get cross for direction1 and direction2 */
/*  Result = 1 - cross */
/*  Result = 2 - parallel and not equal */
/*  Result = 3 - parallel and equal */

void icvGetCrossDirectDirect(  CvVect64d direct1,CvVect64d direct2,
                            CvPoint2D64d *cross,int* result)
{
    double det  = direct1[0]*direct2[1] - direct2[0]*direct1[1];
    double detx = -direct1[2]*direct2[1] + direct1[1]*direct2[2];

    if( fabs(det) > EPS64D )
    {/* Have cross */
        cross->x = detx/det;
        cross->y = (-direct1[0]*direct2[2] + direct2[0]*direct1[2])/det;
        *result = 1;
    }
    else
    {/* may be parallel */
        if( fabs(detx) > EPS64D )
        {/* parallel and not equal */
            *result = 2;
        }
        else
        {/* equals */
            *result = 3;
        }
    }

    return;
}

/*---------------------------------------------------------------------------------------*/

/* Get cross for piece p1,p2 and direction a,b,c */
/*  Result = 0 - no cross */
/*  Result = 1 - cross */
/*  Result = 2 - parallel and not equal */
/*  Result = 3 - parallel and equal */

void icvGetCrossPieceDirect(   CvPoint2D64d p_start,CvPoint2D64d p_end,
                            double a,double b,double c,
                            CvPoint2D64d *cross,int* result)
{

    if( (a*p_start.x + b*p_start.y + c) * (a*p_end.x + b*p_end.y + c) <= 0 )
    {/* Have cross */
        double det;
        double detxc,detyc;
1053

1054
        det = a * (p_end.x - p_start.x) + b * (p_end.y - p_start.y);
1055

1056 1057 1058 1059 1060 1061 1062 1063 1064
        if( fabs(det) < EPS64D )
        {/* lines are parallel and may be equal or line is point */
            if(  fabs(a*p_start.x + b*p_start.y + c) < EPS64D )
            {/* line is point or not diff */
                *result = 3;
                return;
            }
            else
            {
1065
                *result = 2;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
            }
            return;
        }

        detxc = b*(p_end.y*p_start.x - p_start.y*p_end.x) + c*(p_start.x - p_end.x);
        detyc = a*(p_end.x*p_start.y - p_start.x*p_end.y) + c*(p_start.y - p_end.y);

        cross->x = detxc / det;
        cross->y = detyc / det;
        *result = 1;

    }
    else
    {
        *result = 0;
    }
    return;
}
/*--------------------------------------------------------------------------------------*/

void icvGetCrossPiecePiece( CvPoint2D64d p1_start,CvPoint2D64d p1_end,
                            CvPoint2D64d p2_start,CvPoint2D64d p2_end,
                            CvPoint2D64d* cross,
                            int* result)
{
    double ex1,ey1,ex2,ey2;
    double px1,py1,px2,py2;
    double del;
    double delA,delB,delX,delY;
    double alpha,betta;

    ex1 = p1_start.x;
    ey1 = p1_start.y;
    ex2 = p1_end.x;
    ey2 = p1_end.y;

    px1 = p2_start.x;
    py1 = p2_start.y;
    px2 = p2_end.x;
    py2 = p2_end.y;

    del = (py1-py2)*(ex1-ex2)-(px1-px2)*(ey1-ey2);
    if( fabs(del) <= EPS64D )
    {/* May be they are parallel !!! */
        *result = 0;
        return;
    }

    delA =  (ey1-ey2)*(ex1-px1) + (ex1-ex2)*(py1-ey1);
    delB =  (py1-py2)*(ex1-px1) + (px1-px2)*(py1-ey1);

    alpha = delA / del;
    betta = delB / del;

    if( alpha < 0 || alpha > 1.0 || betta < 0 || betta > 1.0)
    {
        *result = 0;
        return;
    }

    delX =  (px1-px2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2))+
            (ex1-ex2)*(px1*(py1-py2)-py1*(px1-px2));

    delY =  (py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2))+
            (ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2));

    cross->x = delX / del;
    cross->y = delY / del;
1134

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    *result = 1;
    return;
}


/*---------------------------------------------------------------------------------------*/

void icvGetPieceLength(CvPoint2D64d point1,CvPoint2D64d point2,double* dist)
{
    double dx = point2.x - point1.x;
    double dy = point2.y - point1.y;
    *dist = sqrt( dx*dx + dy*dy );
    return;
}

/*---------------------------------------------------------------------------------------*/

void icvGetPieceLength3D(CvPoint3D64d point1,CvPoint3D64d point2,double* dist)
{
    double dx = point2.x - point1.x;
    double dy = point2.y - point1.y;
    double dz = point2.z - point1.z;
    *dist = sqrt( dx*dx + dy*dy + dz*dz );
    return;
}

/*---------------------------------------------------------------------------------------*/

/* Find line from epipole which cross image rect */
/* Find points of cross 0 or 1 or 2. Return number of points in cross */
void icvGetCrossRectDirect(    CvSize imageSize,
                            double a,double b,double c,
                            CvPoint2D64d *start,CvPoint2D64d *end,
                            int* result)
{
    CvPoint2D64d frameBeg;
    CvPoint2D64d frameEnd;
    CvPoint2D64d cross[4];
    int     haveCross[4];
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    haveCross[0] = 0;
    haveCross[1] = 0;
    haveCross[2] = 0;
    haveCross[3] = 0;

    frameBeg.x = 0;
    frameBeg.y = 0;
    frameEnd.x = imageSize.width;
    frameEnd.y = 0;

1185 1186
    icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[0],&haveCross[0]);

1187 1188 1189 1190
    frameBeg.x = imageSize.width;
    frameBeg.y = 0;
    frameEnd.x = imageSize.width;
    frameEnd.y = imageSize.height;
1191
    icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[1],&haveCross[1]);
1192 1193 1194 1195 1196

    frameBeg.x = imageSize.width;
    frameBeg.y = imageSize.height;
    frameEnd.x = 0;
    frameEnd.y = imageSize.height;
1197
    icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[2],&haveCross[2]);
1198 1199 1200 1201 1202

    frameBeg.x = 0;
    frameBeg.y = imageSize.height;
    frameEnd.x = 0;
    frameEnd.y = 0;
1203
    icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[3],&haveCross[3]);
1204 1205 1206 1207 1208 1209 1210 1211 1212

    double maxDist;

    int maxI=0,maxJ=0;


    int i,j;

    maxDist = -1.0;
1213

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    double distance;

    for( i = 0; i < 3; i++ )
    {
        if( haveCross[i] == 1 )
        {
            for( j = i + 1; j < 4; j++ )
            {
                if( haveCross[j] == 1)
                {/* Compute dist */
                    icvGetPieceLength(cross[i],cross[j],&distance);
                    if( distance > maxDist )
                    {
                        maxI = i;
                        maxJ = j;
                        maxDist = distance;
                    }
                }
            }
        }
    }

    if( maxDist >= 0 )
    {/* We have cross */
        *start = cross[maxI];
        *result = 1;
        if( maxDist > 0 )
        {
            *end   = cross[maxJ];
            *result = 2;
        }
    }
    else
    {
        *result = 0;
    }

    return;
}/* GetCrossRectDirect */

/*---------------------------------------------------------------------------------------*/
void icvProjectPointToImage(   CvPoint3D64d point,
                            CvMatr64d camMatr,CvMatr64d rotMatr,CvVect64d transVect,
                            CvPoint2D64d* projPoint)
{

    double tmpVect1[3];
    double tmpVect2[3];
1262

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    icvMulMatrix_64d (  rotMatr,
                        3,3,
                        (double*)&point,
                        1,3,
                        tmpVect1);

    icvAddVector_64d ( tmpVect1, transVect,tmpVect2, 3);

    icvMulMatrix_64d (  camMatr,
                        3,3,
                        tmpVect2,
                        1,3,
                        tmpVect1);

    projPoint->x = tmpVect1[0] / tmpVect1[2];
    projPoint->y = tmpVect1[1] / tmpVect1[2];
1279

1280 1281 1282 1283 1284
    return;
}

/*---------------------------------------------------------------------------------------*/
/* Get quads for transform images */
1285
void icvGetQuadsTransform(
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
                          CvSize        imageSize,
                        CvMatr64d     camMatr1,
                        CvMatr64d     rotMatr1,
                        CvVect64d     transVect1,
                        CvMatr64d     camMatr2,
                        CvMatr64d     rotMatr2,
                        CvVect64d     transVect2,
                        CvSize*       warpSize,
                        double quad1[4][2],
                        double quad2[4][2],
                        CvMatr64d     fundMatr,
                        CvPoint3D64d* epipole1,
                        CvPoint3D64d* epipole2
                        )
{
    /* First compute fundamental matrix and epipoles */
    int res;


    /* Compute epipoles and fundamental matrix using new functions */
    {
        double convRotMatr[9];
        double convTransVect[3];

        icvCreateConvertMatrVect( rotMatr1,
                                  transVect1,
                                  rotMatr2,
                                  transVect2,
                                  convRotMatr,
                                  convTransVect);
        float convRotMatr_32f[9];
        float convTransVect_32f[3];

        icvCvt_64d_32f(convRotMatr,convRotMatr_32f,9);
        icvCvt_64d_32f(convTransVect,convTransVect_32f,3);

        /* We know R and t */
        /* Compute essential matrix */
        float essMatr[9];
        float fundMatr_32f[9];

        float camMatr1_32f[9];
        float camMatr2_32f[9];

        icvCvt_64d_32f(camMatr1,camMatr1_32f,9);
        icvCvt_64d_32f(camMatr2,camMatr2_32f,9);

        cvComputeEssentialMatrix(   convRotMatr_32f,
                                    convTransVect_32f,
                                    essMatr);

        cvConvertEssential2Fundamental( essMatr,
                                        fundMatr_32f,
                                        camMatr1_32f,
                                        camMatr2_32f);
1341

1342 1343
        CvPoint3D32f epipole1_32f;
        CvPoint3D32f epipole2_32f;
1344

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        cvComputeEpipolesFromFundMatrix( fundMatr_32f,
                                         &epipole1_32f,
                                         &epipole2_32f);
        /* copy to 64d epipoles */
        epipole1->x = epipole1_32f.x;
        epipole1->y = epipole1_32f.y;
        epipole1->z = epipole1_32f.z;

        epipole2->x = epipole2_32f.x;
        epipole2->y = epipole2_32f.y;
        epipole2->z = epipole2_32f.z;
1356

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
        /* Convert fundamental matrix */
        icvCvt_32f_64d(fundMatr_32f,fundMatr,9);
    }

    double coeff11[3];
    double coeff12[3];
    double coeff21[3];
    double coeff22[3];

    icvGetCommonArea(   imageSize,
                        *epipole1,*epipole2,
                        fundMatr,
                        coeff11,coeff12,
                        coeff21,coeff22,
                        &res);

    CvPoint2D64d point11, point12,point21, point22;
    double width1,width2;
    double height1,height2;
    double tmpHeight1,tmpHeight2;

    CvPoint2D64d epipole1_2d;
    CvPoint2D64d epipole2_2d;

    /* ----- Image 1 ----- */
    if( fabs(epipole1->z) < 1e-8 )
    {
        return;
    }
    epipole1_2d.x = epipole1->x / epipole1->z;
    epipole1_2d.y = epipole1->y / epipole1->z;

    icvGetCutPiece( coeff11,coeff12,
                epipole1_2d,
                imageSize,
                &point11,&point12,
                &point21,&point22,
                &res);

    /* Compute distance */
    icvGetPieceLength(point11,point21,&width1);
    icvGetPieceLength(point11,point12,&tmpHeight1);
    icvGetPieceLength(point21,point22,&tmpHeight2);
    height1 = MAX(tmpHeight1,tmpHeight2);

    quad1[0][0] = point11.x;
    quad1[0][1] = point11.y;

    quad1[1][0] = point21.x;
    quad1[1][1] = point21.y;

    quad1[2][0] = point22.x;
    quad1[2][1] = point22.y;

    quad1[3][0] = point12.x;
    quad1[3][1] = point12.y;

    /* ----- Image 2 ----- */
    if( fabs(epipole2->z) < 1e-8 )
    {
        return;
    }
    epipole2_2d.x = epipole2->x / epipole2->z;
    epipole2_2d.y = epipole2->y / epipole2->z;

    icvGetCutPiece( coeff21,coeff22,
                epipole2_2d,
                imageSize,
                &point11,&point12,
                &point21,&point22,
                &res);

    /* Compute distance */
    icvGetPieceLength(point11,point21,&width2);
    icvGetPieceLength(point11,point12,&tmpHeight1);
    icvGetPieceLength(point21,point22,&tmpHeight2);
    height2 = MAX(tmpHeight1,tmpHeight2);

    quad2[0][0] = point11.x;
    quad2[0][1] = point11.y;

    quad2[1][0] = point21.x;
    quad2[1][1] = point21.y;

    quad2[2][0] = point22.x;
    quad2[2][1] = point22.y;

    quad2[3][0] = point12.x;
    quad2[3][1] = point12.y;


    /*=======================================================*/
    /* This is a new additional way to compute quads. */
    /* We must correct quads */
    {
        double convRotMatr[9];
        double convTransVect[3];

        double newQuad1[4][2];
        double newQuad2[4][2];


        icvCreateConvertMatrVect( rotMatr1,
                                  transVect1,
                                  rotMatr2,
                                  transVect2,
                                  convRotMatr,
                                  convTransVect);

        /* -------------Compute for first image-------------- */
        CvPoint2D32f pointb1;
        CvPoint2D32f pointe1;
1469

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        CvPoint2D32f pointb2;
        CvPoint2D32f pointe2;

        pointb1.x = (float)quad1[0][0];
        pointb1.y = (float)quad1[0][1];

        pointe1.x = (float)quad1[3][0];
        pointe1.y = (float)quad1[3][1];

        icvComputeeInfiniteProject1(convRotMatr,
                                    camMatr1,
                                    camMatr2,
                                    pointb1,
                                    &pointb2);

        icvComputeeInfiniteProject1(convRotMatr,
                                    camMatr1,
                                    camMatr2,
                                    pointe1,
                                    &pointe2);

        /*  JUST TEST FOR POINT */

        /* Compute distances */
        double dxOld,dyOld;
        double dxNew,dyNew;
        double distOld,distNew;
1497

1498 1499 1500
        dxOld = quad2[1][0] - quad2[0][0];
        dyOld = quad2[1][1] - quad2[0][1];
        distOld = dxOld*dxOld + dyOld*dyOld;
1501

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
        dxNew = quad2[1][0] - pointb2.x;
        dyNew = quad2[1][1] - pointb2.y;
        distNew = dxNew*dxNew + dyNew*dyNew;

        if( distNew > distOld )
        {/* Get new points for second quad */
            newQuad2[0][0] = pointb2.x;
            newQuad2[0][1] = pointb2.y;
            newQuad2[3][0] = pointe2.x;
            newQuad2[3][1] = pointe2.y;
            newQuad1[0][0] = quad1[0][0];
            newQuad1[0][1] = quad1[0][1];
            newQuad1[3][0] = quad1[3][0];
            newQuad1[3][1] = quad1[3][1];
        }
        else
        {/* Get new points for first quad */

            pointb2.x = (float)quad2[0][0];
            pointb2.y = (float)quad2[0][1];

            pointe2.x = (float)quad2[3][0];
            pointe2.y = (float)quad2[3][1];

            icvComputeeInfiniteProject2(convRotMatr,
                                        camMatr1,
                                        camMatr2,
                                        &pointb1,
                                        pointb2);

            icvComputeeInfiniteProject2(convRotMatr,
                                        camMatr1,
                                        camMatr2,
                                        &pointe1,
                                        pointe2);


            /*  JUST TEST FOR POINT */

            newQuad2[0][0] = quad2[0][0];
            newQuad2[0][1] = quad2[0][1];
            newQuad2[3][0] = quad2[3][0];
            newQuad2[3][1] = quad2[3][1];
1545

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
            newQuad1[0][0] = pointb1.x;
            newQuad1[0][1] = pointb1.y;
            newQuad1[3][0] = pointe1.x;
            newQuad1[3][1] = pointe1.y;
        }

        /* -------------Compute for second image-------------- */
        pointb1.x = (float)quad1[1][0];
        pointb1.y = (float)quad1[1][1];

        pointe1.x = (float)quad1[2][0];
        pointe1.y = (float)quad1[2][1];

        icvComputeeInfiniteProject1(convRotMatr,
                                    camMatr1,
                                    camMatr2,
                                    pointb1,
                                    &pointb2);

        icvComputeeInfiniteProject1(convRotMatr,
                                    camMatr1,
                                    camMatr2,
                                    pointe1,
                                    &pointe2);

        /* Compute distances */
1572

1573 1574 1575
        dxOld = quad2[0][0] - quad2[1][0];
        dyOld = quad2[0][1] - quad2[1][1];
        distOld = dxOld*dxOld + dyOld*dyOld;
1576

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
        dxNew = quad2[0][0] - pointb2.x;
        dyNew = quad2[0][1] - pointb2.y;
        distNew = dxNew*dxNew + dyNew*dyNew;

        if( distNew > distOld )
        {/* Get new points for second quad */
            newQuad2[1][0] = pointb2.x;
            newQuad2[1][1] = pointb2.y;
            newQuad2[2][0] = pointe2.x;
            newQuad2[2][1] = pointe2.y;
            newQuad1[1][0] = quad1[1][0];
            newQuad1[1][1] = quad1[1][1];
            newQuad1[2][0] = quad1[2][0];
            newQuad1[2][1] = quad1[2][1];
        }
        else
        {/* Get new points for first quad */

            pointb2.x = (float)quad2[1][0];
            pointb2.y = (float)quad2[1][1];

            pointe2.x = (float)quad2[2][0];
            pointe2.y = (float)quad2[2][1];

            icvComputeeInfiniteProject2(convRotMatr,
                                        camMatr1,
                                        camMatr2,
                                        &pointb1,
                                        pointb2);

            icvComputeeInfiniteProject2(convRotMatr,
                                        camMatr1,
                                        camMatr2,
                                        &pointe1,
                                        pointe2);

            newQuad2[1][0] = quad2[1][0];
            newQuad2[1][1] = quad2[1][1];
            newQuad2[2][0] = quad2[2][0];
            newQuad2[2][1] = quad2[2][1];
1617

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
            newQuad1[1][0] = pointb1.x;
            newQuad1[1][1] = pointb1.y;
            newQuad1[2][0] = pointe1.x;
            newQuad1[2][1] = pointe1.y;
        }



/*-------------------------------------------------------------------------------*/

        /* Copy new quads to old quad */
        int i;
        for( i = 0; i < 4; i++ )
        {
            {
                quad1[i][0] = newQuad1[i][0];
                quad1[i][1] = newQuad1[i][1];
                quad2[i][0] = newQuad2[i][0];
                quad2[i][1] = newQuad2[i][1];
            }
        }
    }
    /*=======================================================*/

    double warpWidth,warpHeight;

    warpWidth  = MAX(width1,width2);
    warpHeight = MAX(height1,height2);

    warpSize->width  = (int)warpWidth;
    warpSize->height = (int)warpHeight;

    warpSize->width  = cvRound(warpWidth-1);
    warpSize->height = cvRound(warpHeight-1);

/* !!! by Valery Mosyagin. this lines added just for test no warp */
    warpSize->width  = imageSize.width;
    warpSize->height = imageSize.height;

    return;
}


/*---------------------------------------------------------------------------------------*/

1663
static void icvGetQuadsTransformNew(  CvSize        imageSize,
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 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 1730 1731 1732 1733 1734
                            CvMatr32f     camMatr1,
                            CvMatr32f     camMatr2,
                            CvMatr32f     rotMatr1,
                            CvVect32f     transVect1,
                            CvSize*       warpSize,
                            double        quad1[4][2],
                            double        quad2[4][2],
                            CvMatr32f     fundMatr,
                            CvPoint3D32f* epipole1,
                            CvPoint3D32f* epipole2
                        )
{
    /* Convert data */
    /* Convert camera matrix */
    double camMatr1_64d[9];
    double camMatr2_64d[9];
    double rotMatr1_64d[9];
    double transVect1_64d[3];
    double rotMatr2_64d[9];
    double transVect2_64d[3];
    double fundMatr_64d[9];
    CvPoint3D64d epipole1_64d;
    CvPoint3D64d epipole2_64d;

    icvCvt_32f_64d(camMatr1,camMatr1_64d,9);
    icvCvt_32f_64d(camMatr2,camMatr2_64d,9);
    icvCvt_32f_64d(rotMatr1,rotMatr1_64d,9);
    icvCvt_32f_64d(transVect1,transVect1_64d,3);

    /* Create vector and matrix */

    rotMatr2_64d[0] = 1;
    rotMatr2_64d[1] = 0;
    rotMatr2_64d[2] = 0;
    rotMatr2_64d[3] = 0;
    rotMatr2_64d[4] = 1;
    rotMatr2_64d[5] = 0;
    rotMatr2_64d[6] = 0;
    rotMatr2_64d[7] = 0;
    rotMatr2_64d[8] = 1;

    transVect2_64d[0] = 0;
    transVect2_64d[1] = 0;
    transVect2_64d[2] = 0;

    icvGetQuadsTransform(   imageSize,
                            camMatr1_64d,
                            rotMatr1_64d,
                            transVect1_64d,
                            camMatr2_64d,
                            rotMatr2_64d,
                            transVect2_64d,
                            warpSize,
                            quad1,
                            quad2,
                            fundMatr_64d,
                            &epipole1_64d,
                            &epipole2_64d
                        );

    /* Convert epipoles */
    epipole1->x = (float)(epipole1_64d.x);
    epipole1->y = (float)(epipole1_64d.y);
    epipole1->z = (float)(epipole1_64d.z);

    epipole2->x = (float)(epipole2_64d.x);
    epipole2->y = (float)(epipole2_64d.y);
    epipole2->z = (float)(epipole2_64d.z);

    /* Convert fundamental matrix */
    icvCvt_64d_32f(fundMatr_64d,fundMatr,9);
1735

1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    return;
}

/*---------------------------------------------------------------------------------------*/
void icvGetQuadsTransformStruct(  CvStereoCamera* stereoCamera)
{
    /* Wrapper for icvGetQuadsTransformNew */


    double  quad1[4][2];
    double  quad2[4][2];

    icvGetQuadsTransformNew(     cvSize(cvRound(stereoCamera->camera[0]->imgSize[0]),cvRound(stereoCamera->camera[0]->imgSize[1])),
                            stereoCamera->camera[0]->matrix,
                            stereoCamera->camera[1]->matrix,
                            stereoCamera->rotMatrix,
                            stereoCamera->transVector,
                            &(stereoCamera->warpSize),
                            quad1,
                            quad2,
                            stereoCamera->fundMatr,
                            &(stereoCamera->epipole[0]),
                            &(stereoCamera->epipole[1])
                        );

    int i;
    for( i = 0; i < 4; i++ )
    {
        stereoCamera->quad[0][i] = cvPoint2D32f(quad1[i][0],quad1[i][1]);
        stereoCamera->quad[1][i] = cvPoint2D32f(quad2[i][0],quad2[i][1]);
    }

    return;
}

/*---------------------------------------------------------------------------------------*/
void icvComputeStereoParamsForCameras(CvStereoCamera* stereoCamera)
{
1774
    /* For given intrinsic and extrinsic parameters computes rest parameters
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    **   such as fundamental matrix. warping coeffs, epipoles, ...
    */


    /* compute rotate matrix and translate vector */
    double rotMatr1[9];
    double rotMatr2[9];

    double transVect1[3];
    double transVect2[3];

    double convRotMatr[9];
    double convTransVect[3];

    /* fill matrices */
    icvCvt_32f_64d(stereoCamera->camera[0]->rotMatr,rotMatr1,9);
    icvCvt_32f_64d(stereoCamera->camera[1]->rotMatr,rotMatr2,9);

    icvCvt_32f_64d(stereoCamera->camera[0]->transVect,transVect1,3);
    icvCvt_32f_64d(stereoCamera->camera[1]->transVect,transVect2,3);
1795

1796 1797 1798 1799 1800 1801
    icvCreateConvertMatrVect(   rotMatr1,
                                transVect1,
                                rotMatr2,
                                transVect2,
                                convRotMatr,
                                convTransVect);
1802

1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
    /* copy to stereo camera params */
    icvCvt_64d_32f(convRotMatr,stereoCamera->rotMatrix,9);
    icvCvt_64d_32f(convTransVect,stereoCamera->transVector,3);


    icvGetQuadsTransformStruct(stereoCamera);
    icvComputeRestStereoParams(stereoCamera);
}



/*---------------------------------------------------------------------------------------*/

/* Get cut line for one image */
void icvGetCutPiece(   CvVect64d areaLineCoef1,CvVect64d areaLineCoef2,
                    CvPoint2D64d epipole,
                    CvSize imageSize,
                    CvPoint2D64d* point11,CvPoint2D64d* point12,
                    CvPoint2D64d* point21,CvPoint2D64d* point22,
                    int* result)
{
    /* Compute nearest cut line to epipole */
    /* Get corners inside sector */
    /* Collect all candidate point */

    CvPoint2D64d candPoints[8];
1829
    CvPoint2D64d midPoint = {0, 0};
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
    int numPoints = 0;
    int res;
    int i;

    double cutLine1[3];
    double cutLine2[3];

    /* Find middle line of sector */
    double midLine[3]={0,0,0};

1840

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 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
    /* Different way  */
    CvPoint2D64d pointOnLine1;  pointOnLine1.x = pointOnLine1.y = 0;
    CvPoint2D64d pointOnLine2;  pointOnLine2.x = pointOnLine2.y = 0;

    CvPoint2D64d start1,end1;

    icvGetCrossRectDirect( imageSize,
                        areaLineCoef1[0],areaLineCoef1[1],areaLineCoef1[2],
                        &start1,&end1,&res);
    if( res > 0 )
    {
        pointOnLine1 = start1;
    }

    icvGetCrossRectDirect( imageSize,
                        areaLineCoef2[0],areaLineCoef2[1],areaLineCoef2[2],
                        &start1,&end1,&res);
    if( res > 0 )
    {
        pointOnLine2 = start1;
    }

    icvGetMiddleAnglePoint(epipole,pointOnLine1,pointOnLine2,&midPoint);

    icvGetCoefForPiece(epipole,midPoint,&midLine[0],&midLine[1],&midLine[2],&res);

    /* Test corner points */
    CvPoint2D64d cornerPoint;
    CvPoint2D64d tmpPoints[2];

    cornerPoint.x = 0;
    cornerPoint.y = 0;
    icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
    if( res == 1 )
    {/* Add point */
        candPoints[numPoints] = cornerPoint;
        numPoints++;
    }

    cornerPoint.x = imageSize.width;
    cornerPoint.y = 0;
    icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
    if( res == 1 )
    {/* Add point */
        candPoints[numPoints] = cornerPoint;
        numPoints++;
    }
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
    cornerPoint.x = imageSize.width;
    cornerPoint.y = imageSize.height;
    icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
    if( res == 1 )
    {/* Add point */
        candPoints[numPoints] = cornerPoint;
        numPoints++;
    }

    cornerPoint.x = 0;
    cornerPoint.y = imageSize.height;
    icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
    if( res == 1 )
    {/* Add point */
        candPoints[numPoints] = cornerPoint;
        numPoints++;
    }

    /* Find cross line 1 with image border */
    icvGetCrossRectDirect( imageSize,
                        areaLineCoef1[0],areaLineCoef1[1],areaLineCoef1[2],
                        &tmpPoints[0], &tmpPoints[1],
                        &res);
    for( i = 0; i < res; i++ )
    {
        candPoints[numPoints++] = tmpPoints[i];
    }

    /* Find cross line 2 with image border */
    icvGetCrossRectDirect( imageSize,
                        areaLineCoef2[0],areaLineCoef2[1],areaLineCoef2[2],
                        &tmpPoints[0], &tmpPoints[1],
                        &res);
1922

1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
    for( i = 0; i < res; i++ )
    {
        candPoints[numPoints++] = tmpPoints[i];
    }

    if( numPoints < 2 )
    {
        *result = 0;
        return;/* Error. Not enought points */
    }
    /* Project all points to middle line and get max and min */

    CvPoint2D64d projPoint;
    CvPoint2D64d minPoint; minPoint.x = minPoint.y = FLT_MAX;
    CvPoint2D64d maxPoint; maxPoint.x = maxPoint.y = -FLT_MAX;


    double dist;
    double maxDist = 0;
    double minDist = 10000000;

1944

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    for( i = 0; i < numPoints; i++ )
    {
        icvProjectPointToDirect(candPoints[i], midLine, &projPoint);
        icvGetPieceLength(epipole,projPoint,&dist);
        if( dist < minDist)
        {
            minDist = dist;
            minPoint = projPoint;
        }

        if( dist > maxDist)
        {
            maxDist = dist;
            maxPoint = projPoint;
        }
    }

    /* We know maximum and minimum points. Now we can compute cut lines */
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
    icvGetNormalDirect(midLine,minPoint,cutLine1);
    icvGetNormalDirect(midLine,maxPoint,cutLine2);

    /* Test for begin of line. */
    CvPoint2D64d tmpPoint2;

    /* Get cross with */
    icvGetCrossDirectDirect(areaLineCoef1,cutLine1,point11,&res);
    icvGetCrossDirectDirect(areaLineCoef2,cutLine1,point12,&res);

    icvGetCrossDirectDirect(areaLineCoef1,cutLine2,point21,&res);
    icvGetCrossDirectDirect(areaLineCoef2,cutLine2,point22,&res);

    if( epipole.x > imageSize.width * 0.5 )
    {/* Need to change points */
        tmpPoint2 = *point11;
        *point11 = *point21;
        *point21 = tmpPoint2;

        tmpPoint2 = *point12;
        *point12 = *point22;
        *point22 = tmpPoint2;
    }

    return;
}
/*---------------------------------------------------------------------------------------*/
/* Get middle angle */
void icvGetMiddleAnglePoint(   CvPoint2D64d basePoint,
                            CvPoint2D64d point1,CvPoint2D64d point2,
                            CvPoint2D64d* midPoint)
{/* !!! May be need to return error */
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
    double dist1;
    double dist2;
    icvGetPieceLength(basePoint,point1,&dist1);
    icvGetPieceLength(basePoint,point2,&dist2);
    CvPoint2D64d pointNew1;
    CvPoint2D64d pointNew2;
    double alpha = dist2/dist1;

    pointNew1.x = basePoint.x + (1.0/alpha) * ( point2.x - basePoint.x );
    pointNew1.y = basePoint.y + (1.0/alpha) * ( point2.y - basePoint.y );

    pointNew2.x = basePoint.x + alpha * ( point1.x - basePoint.x );
    pointNew2.y = basePoint.y + alpha * ( point1.y - basePoint.y );

    int res;
    icvGetCrossPiecePiece(point1,point2,pointNew1,pointNew2,midPoint,&res);

    return;
}

/*---------------------------------------------------------------------------------------*/
/* Get normal direct to direct in line */
void icvGetNormalDirect(CvVect64d direct,CvPoint2D64d point,CvVect64d normDirect)
{
    normDirect[0] =   direct[1];
    normDirect[1] = - direct[0];
2023
    normDirect[2] = -(normDirect[0]*point.x + normDirect[1]*point.y);
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 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
    return;
}

/*---------------------------------------------------------------------------------------*/
CV_IMPL double icvGetVect(CvPoint2D64d basePoint,CvPoint2D64d point1,CvPoint2D64d point2)
{
    return  (point1.x - basePoint.x)*(point2.y - basePoint.y) -
            (point2.x - basePoint.x)*(point1.y - basePoint.y);
}
/*---------------------------------------------------------------------------------------*/
/* Test for point in sector           */
/* Return 0 - point not inside sector */
/* Return 1 - point inside sector     */
void icvTestPoint( CvPoint2D64d testPoint,
                CvVect64d line1,CvVect64d line2,
                CvPoint2D64d basePoint,
                int* result)
{
    CvPoint2D64d point1,point2;

    icvProjectPointToDirect(testPoint,line1,&point1);
    icvProjectPointToDirect(testPoint,line2,&point2);

    double sign1 = icvGetVect(basePoint,point1,point2);
    double sign2 = icvGetVect(basePoint,point1,testPoint);
    if( sign1 * sign2 > 0 )
    {/* Correct for first line */
        sign1 = - sign1;
        sign2 = icvGetVect(basePoint,point2,testPoint);
        if( sign1 * sign2 > 0 )
        {/* Correct for both lines */
            *result = 1;
        }
        else
        {
            *result = 0;
        }
    }
    else
    {
        *result = 0;
    }
2066

2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
    return;
}

/*---------------------------------------------------------------------------------------*/
/* Project point to line */
void icvProjectPointToDirect(  CvPoint2D64d point,CvVect64d lineCoeff,
                            CvPoint2D64d* projectPoint)
{
    double a = lineCoeff[0];
    double b = lineCoeff[1];
2077

2078 2079 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
    double det =  1.0 / ( a*a + b*b );
    double delta =  a*point.y - b*point.x;

    projectPoint->x = ( -a*lineCoeff[2] - b * delta ) * det;
    projectPoint->y = ( -b*lineCoeff[2] + a * delta ) * det ;

    return;
}

/*---------------------------------------------------------------------------------------*/
/* Get distance from point to direction */
void icvGetDistanceFromPointToDirect( CvPoint2D64d point,CvVect64d lineCoef,double*dist)
{
    CvPoint2D64d tmpPoint;
    icvProjectPointToDirect(point,lineCoef,&tmpPoint);
    double dx = point.x - tmpPoint.x;
    double dy = point.y - tmpPoint.y;
    *dist = sqrt(dx*dx+dy*dy);
    return;
}
/*---------------------------------------------------------------------------------------*/

CV_IMPL IplImage* icvCreateIsometricImage( IplImage* src, IplImage* dst,
                                       int desired_depth, int desired_num_channels )
{
    CvSize src_size ;
    src_size.width = src->width;
    src_size.height = src->height;
2106

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    CvSize dst_size = src_size;

    if( dst )
    {
        dst_size.width = dst->width;
        dst_size.height = dst->height;
    }

    if( !dst || dst->depth != desired_depth ||
        dst->nChannels != desired_num_channels ||
        dst_size.width != src_size.width ||
2118
        dst_size.height != src_size.height )
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
    {
        cvReleaseImage( &dst );
        dst = cvCreateImage( src_size, desired_depth, desired_num_channels );
        CvRect rect = cvRect(0,0,src_size.width,src_size.height);
        cvSetImageROI( dst, rect );

    }

    return dst;
}

2130
static int
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
icvCvt_32f_64d( float *src, double *dst, int size )
{
    int t;

    if( !src || !dst )
        return CV_NULLPTR_ERR;
    if( size <= 0 )
        return CV_BADRANGE_ERR;

    for( t = 0; t < size; t++ )
    {
        dst[t] = (double) (src[t]);
    }

    return CV_OK;
}

/*======================================================================================*/
/* Type conversion double -> float */
2150
static int
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
icvCvt_64d_32f( double *src, float *dst, int size )
{
    int t;

    if( !src || !dst )
        return CV_NULLPTR_ERR;
    if( size <= 0 )
        return CV_BADRANGE_ERR;

    for( t = 0; t < size; t++ )
    {
        dst[t] = (float) (src[t]);
    }

    return CV_OK;
}

/*----------------------------------------------------------------------------------*/

2170
#if 0
2171
/* Find line which cross frame by line(a,b,c) */
2172
static void FindLineForEpiline(    CvSize imageSize,
2173 2174
                            float a,float b,float c,
                            CvPoint2D32f *start,CvPoint2D32f *end,
2175
                            int*)
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
{
    CvPoint2D32f frameBeg;

    CvPoint2D32f frameEnd;
    CvPoint2D32f cross[4];
    int     haveCross[4];
    float   dist;

    haveCross[0] = 0;
    haveCross[1] = 0;
    haveCross[2] = 0;
    haveCross[3] = 0;

    frameBeg.x = 0;
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = 0;
    haveCross[0] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[0]);
2194

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = (float)(imageSize.height);
    haveCross[1] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[1]);

    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = (float)(imageSize.height);
    haveCross[2] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[2]);
2206

2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
    frameBeg.x = 0;
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = 0;
    haveCross[3] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[3]);

    int n;
    float minDist = (float)(INT_MAX);
    float maxDist = (float)(INT_MIN);

    int maxN = -1;
    int minN = -1;

    double midPointX = imageSize.width  / 2.0;
    double midPointY = imageSize.height / 2.0;

    for( n = 0; n < 4; n++ )
    {
        if( haveCross[n] > 0 )
        {
            dist =  (float)((midPointX - cross[n].x)*(midPointX - cross[n].x) +
                            (midPointY - cross[n].y)*(midPointY - cross[n].y));

            if( dist < minDist )
            {
                minDist = dist;
                minN = n;
            }

            if( dist > maxDist )
            {
                maxDist = dist;
                maxN = n;
            }
        }
    }

    if( minN >= 0 && maxN >= 0 && (minN != maxN) )
    {
        *start = cross[minN];
        *end   = cross[maxN];
    }
    else
    {
        start->x = 0;
        start->y = 0;
        end->x = 0;
        end->y = 0;
    }

    return;
2258

2259 2260 2261 2262
}


/*----------------------------------------------------------------------------------*/
2263
static int GetAngleLinee( CvPoint2D32f epipole, CvSize imageSize,CvPoint2D32f point1,CvPoint2D32f point2)
2264 2265 2266 2267 2268 2269 2270 2271 2272
{
    float width  = (float)(imageSize.width);
    float height = (float)(imageSize.height);

    /* Get crosslines with image corners */

    /* Find four lines */

    CvPoint2D32f pa,pb,pc,pd;
2273

2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    pa.x = 0;
    pa.y = 0;

    pb.x = width;
    pb.y = 0;

    pd.x = width;
    pd.y = height;

    pc.x = 0;
    pc.y = height;

    /* We can compute points for angle */
    /* Test for place section */

    float x,y;
    x = epipole.x;
    y = epipole.y;
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 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    if( x < 0 )
    {/* 1,4,7 */
        if( y < 0)
        {/* 1 */
            point1 = pb;
            point2 = pc;
        }
        else if( y > height )
        {/* 7 */
            point1 = pa;
            point2 = pd;
        }
        else
        {/* 4 */
            point1 = pa;
            point2 = pc;
        }
    }
    else if ( x > width )
    {/* 3,6,9 */
        if( y < 0 )
        {/* 3 */
            point1 = pa;
            point2 = pd;
        }
        else if ( y > height )
        {/* 9 */
            point1 = pc;
            point2 = pb;
        }
        else
        {/* 6 */
            point1 = pb;
            point2 = pd;
        }
    }
    else
    {/* 2,5,8 */
        if( y < 0 )
        {/* 2 */
            point1 = pa;
            point2 = pb;
        }
        else if( y > height )
        {/* 8 */
            point1 = pc;
            point2 = pd;
        }
        else
        {/* 5 - point in the image */
            return 2;
        }

2346

2347
    }
2348

2349 2350 2351 2352 2353

    return 0;
}

/*--------------------------------------------------------------------------------------*/
2354
static void icvComputePerspectiveCoeffs(const CvPoint2D32f srcQuad[4],const CvPoint2D32f dstQuad[4],double coeffs[3][3])
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
{/* Computes perspective coeffs for transformation from src to dst quad */


    CV_FUNCNAME( "icvComputePerspectiveCoeffs" );

    __BEGIN__;

    double A[64];
    double b[8];
    double c[8];
    CvPoint2D32f pt[4];
    int i;

    pt[0] = srcQuad[0];
    pt[1] = srcQuad[1];
    pt[2] = srcQuad[2];
    pt[3] = srcQuad[3];

    for( i = 0; i < 4; i++ )
    {
#if 0
        double x = dstQuad[i].x;
        double y = dstQuad[i].y;
        double X = pt[i].x;
        double Y = pt[i].y;
#else
        double x = pt[i].x;
        double y = pt[i].y;
        double X = dstQuad[i].x;
        double Y = dstQuad[i].y;
#endif
        double* a = A + i*16;
2387

2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
        a[0] = x;
        a[1] = y;
        a[2] = 1;
        a[3] = 0;
        a[4] = 0;
        a[5] = 0;
        a[6] = -X*x;
        a[7] = -X*y;

        a += 8;

        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = x;
        a[4] = y;
        a[5] = 1;
        a[6] = -Y*x;
        a[7] = -Y*y;

        b[i*2] = X;
        b[i*2 + 1] = Y;
    }

    {
    double invA[64];
    CvMat matA = cvMat( 8, 8, CV_64F, A );
    CvMat matInvA = cvMat( 8, 8, CV_64F, invA );
    CvMat matB = cvMat( 8, 1, CV_64F, b );
    CvMat matX = cvMat( 8, 1, CV_64F, c );

    CV_CALL( cvPseudoInverse( &matA, &matInvA ));
    CV_CALL( cvMatMulAdd( &matInvA, &matB, 0, &matX ));
    }
2422

2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    coeffs[0][0] = c[0];
    coeffs[0][1] = c[1];
    coeffs[0][2] = c[2];
    coeffs[1][0] = c[3];
    coeffs[1][1] = c[4];
    coeffs[1][2] = c[5];
    coeffs[2][0] = c[6];
    coeffs[2][1] = c[7];
    coeffs[2][2] = 1.0;

    __END__;

    return;
}
2437
#endif
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459

/*--------------------------------------------------------------------------------------*/

CV_IMPL void cvComputePerspectiveMap(const double c[3][3], CvArr* rectMapX, CvArr* rectMapY )
{
    CV_FUNCNAME( "cvComputePerspectiveMap" );

    __BEGIN__;

    CvSize size;
    CvMat  stubx, *mapx = (CvMat*)rectMapX;
    CvMat  stuby, *mapy = (CvMat*)rectMapY;
    int i, j;

    CV_CALL( mapx = cvGetMat( mapx, &stubx ));
    CV_CALL( mapy = cvGetMat( mapy, &stuby ));

    if( CV_MAT_TYPE( mapx->type ) != CV_32FC1 || CV_MAT_TYPE( mapy->type ) != CV_32FC1 )
        CV_ERROR( CV_StsUnsupportedFormat, "" );

    size = cvGetMatSize(mapx);
    assert( fabs(c[2][2] - 1.) < FLT_EPSILON );
2460

2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    for( i = 0; i < size.height; i++ )
    {
        float* mx = (float*)(mapx->data.ptr + mapx->step*i);
        float* my = (float*)(mapy->data.ptr + mapy->step*i);

        for( j = 0; j < size.width; j++ )
        {
            double w = 1./(c[2][0]*j + c[2][1]*i + 1.);
            double x = (c[0][0]*j + c[0][1]*i + c[0][2])*w;
            double y = (c[1][0]*j + c[1][1]*i + c[1][2])*w;

            mx[j] = (float)x;
            my[j] = (float)y;
        }
    }

    __END__;
}

/*--------------------------------------------------------------------------------------*/

CV_IMPL void cvInitPerspectiveTransform( CvSize size, const CvPoint2D32f quad[4], double matrix[3][3],
                                              CvArr* rectMap )
{
    /* Computes Perspective Transform coeffs and map if need
        for given image size and given result quad */
    CV_FUNCNAME( "cvInitPerspectiveTransform" );

    __BEGIN__;

    double A[64];
    double b[8];
    double c[8];
    CvPoint2D32f pt[4];
    CvMat  mapstub, *map = (CvMat*)rectMap;
    int i, j;

    if( map )
    {
        CV_CALL( map = cvGetMat( map, &mapstub ));

        if( CV_MAT_TYPE( map->type ) != CV_32FC2 )
            CV_ERROR( CV_StsUnsupportedFormat, "" );

        if( map->width != size.width || map->height != size.height )
            CV_ERROR( CV_StsUnmatchedSizes, "" );
    }

    pt[0] = cvPoint2D32f( 0, 0 );
    pt[1] = cvPoint2D32f( size.width, 0 );
    pt[2] = cvPoint2D32f( size.width, size.height );
    pt[3] = cvPoint2D32f( 0, size.height );

    for( i = 0; i < 4; i++ )
    {
#if 0
        double x = quad[i].x;
        double y = quad[i].y;
        double X = pt[i].x;
        double Y = pt[i].y;
#else
        double x = pt[i].x;
        double y = pt[i].y;
        double X = quad[i].x;
        double Y = quad[i].y;
#endif
        double* a = A + i*16;
2528

2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
        a[0] = x;
        a[1] = y;
        a[2] = 1;
        a[3] = 0;
        a[4] = 0;
        a[5] = 0;
        a[6] = -X*x;
        a[7] = -X*y;

        a += 8;

        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = x;
        a[4] = y;
        a[5] = 1;
        a[6] = -Y*x;
        a[7] = -Y*y;

        b[i*2] = X;
        b[i*2 + 1] = Y;
    }

    {
    double invA[64];
    CvMat matA = cvMat( 8, 8, CV_64F, A );
    CvMat matInvA = cvMat( 8, 8, CV_64F, invA );
    CvMat matB = cvMat( 8, 1, CV_64F, b );
    CvMat matX = cvMat( 8, 1, CV_64F, c );

    CV_CALL( cvPseudoInverse( &matA, &matInvA ));
    CV_CALL( cvMatMulAdd( &matInvA, &matB, 0, &matX ));
    }
2563

2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
    matrix[0][0] = c[0];
    matrix[0][1] = c[1];
    matrix[0][2] = c[2];
    matrix[1][0] = c[3];
    matrix[1][1] = c[4];
    matrix[1][2] = c[5];
    matrix[2][0] = c[6];
    matrix[2][1] = c[7];
    matrix[2][2] = 1.0;

    if( map )
    {
        for( i = 0; i < size.height; i++ )
        {
            CvPoint2D32f* maprow = (CvPoint2D32f*)(map->data.ptr + map->step*i);
            for( j = 0; j < size.width; j++ )
            {
                double w = 1./(c[6]*j + c[7]*i + 1.);
                double x = (c[0]*j + c[1]*i + c[2])*w;
                double y = (c[3]*j + c[4]*i + c[5])*w;

                maprow[j].x = (float)x;
                maprow[j].y = (float)y;
            }
        }
    }

    __END__;

    return;
}


/*-----------------------------------------------------------------------*/
/* Compute projected infinite point for second image if first image point is known */
void icvComputeeInfiniteProject1(   CvMatr64d     rotMatr,
                                    CvMatr64d     camMatr1,
                                    CvMatr64d     camMatr2,
                                    CvPoint2D32f  point1,
                                    CvPoint2D32f* point2)
{
    double invMatr1[9];
    icvInvertMatrix_64d(camMatr1,3,invMatr1);
    double P1[3];
    double p1[3];
    p1[0] = (double)(point1.x);
    p1[1] = (double)(point1.y);
    p1[2] = 1;

    icvMulMatrix_64d(   invMatr1,
                        3,3,
                        p1,
2616
                        1,3,
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
                        P1);

    double invR[9];
    icvTransposeMatrix_64d( rotMatr, 3, 3, invR );

    /* Change system 1 to system 2 */
    double P2[3];
    icvMulMatrix_64d(   invR,
                        3,3,
                        P1,
2627
                        1,3,
2628 2629 2630 2631 2632 2633 2634 2635
                        P2);

    /* Now we can project this point to image 2 */
    double projP[3];

    icvMulMatrix_64d(   camMatr2,
                        3,3,
                        P2,
2636
                        1,3,
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
                        projP);

    point2->x = (float)(projP[0] / projP[2]);
    point2->y = (float)(projP[1] / projP[2]);

    return;
}

/*-----------------------------------------------------------------------*/
/* Compute projected infinite point for second image if first image point is known */
void icvComputeeInfiniteProject2(   CvMatr64d     rotMatr,
                                    CvMatr64d     camMatr1,
                                    CvMatr64d     camMatr2,
                                    CvPoint2D32f*  point1,
                                    CvPoint2D32f point2)
{
    double invMatr2[9];
    icvInvertMatrix_64d(camMatr2,3,invMatr2);
    double P2[3];
    double p2[3];
    p2[0] = (double)(point2.x);
    p2[1] = (double)(point2.y);
    p2[2] = 1;

    icvMulMatrix_64d(   invMatr2,
                        3,3,
                        p2,
2664
                        1,3,
2665 2666 2667 2668 2669 2670 2671 2672
                        P2);

    /* Change system 1 to system 2 */

    double P1[3];
    icvMulMatrix_64d(   rotMatr,
                        3,3,
                        P2,
2673
                        1,3,
2674 2675 2676 2677 2678 2679 2680 2681
                        P1);

    /* Now we can project this point to image 2 */
    double projP[3];

    icvMulMatrix_64d(   camMatr1,
                        3,3,
                        P1,
2682
                        1,3,
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
                        projP);

    point1->x = (float)(projP[0] / projP[2]);
    point1->y = (float)(projP[1] / projP[2]);

    return;
}

/* Select best R and t for given cameras, points, ... */
/* For both cameras */
2693
static int icvSelectBestRt(         int           numImages,
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
                                    int*          numPoints,
                                    CvPoint2D32f* imagePoints1,
                                    CvPoint2D32f* imagePoints2,
                                    CvPoint3D32f* objectPoints,

                                    CvMatr32f     cameraMatrix1,
                                    CvVect32f     distortion1,
                                    CvMatr32f     rotMatrs1,
                                    CvVect32f     transVects1,

                                    CvMatr32f     cameraMatrix2,
                                    CvVect32f     distortion2,
                                    CvMatr32f     rotMatrs2,
                                    CvVect32f     transVects2,

                                    CvMatr32f     bestRotMatr,
                                    CvVect32f     bestTransVect
                                    )
{

    /* Need to convert input data 32 -> 64 */
    CvPoint3D64d* objectPoints_64d;
2716

2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    double* rotMatrs1_64d;
    double* rotMatrs2_64d;

    double* transVects1_64d;
    double* transVects2_64d;

    double cameraMatrix1_64d[9];
    double cameraMatrix2_64d[9];

    double distortion1_64d[4];
    double distortion2_64d[4];

    /* allocate memory for 64d data */
    int totalNum = 0;

2732
    for(int i = 0; i < numImages; i++ )
2733 2734 2735 2736 2737
    {
        totalNum += numPoints[i];
    }

    objectPoints_64d = (CvPoint3D64d*)calloc(totalNum,sizeof(CvPoint3D64d));
2738

2739 2740 2741 2742 2743 2744 2745
    rotMatrs1_64d    = (double*)calloc(numImages,sizeof(double)*9);
    rotMatrs2_64d    = (double*)calloc(numImages,sizeof(double)*9);

    transVects1_64d  = (double*)calloc(numImages,sizeof(double)*3);
    transVects2_64d  = (double*)calloc(numImages,sizeof(double)*3);

    /* Convert input data to 64d */
2746

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
    icvCvt_32f_64d((float*)objectPoints, (double*)objectPoints_64d,  totalNum*3);

    icvCvt_32f_64d(rotMatrs1, rotMatrs1_64d,  numImages*9);
    icvCvt_32f_64d(rotMatrs2, rotMatrs2_64d,  numImages*9);

    icvCvt_32f_64d(transVects1, transVects1_64d,  numImages*3);
    icvCvt_32f_64d(transVects2, transVects2_64d,  numImages*3);

    /* Convert to arrays */
    icvCvt_32f_64d(cameraMatrix1, cameraMatrix1_64d, 9);
    icvCvt_32f_64d(cameraMatrix2, cameraMatrix2_64d, 9);

    icvCvt_32f_64d(distortion1, distortion1_64d, 4);
    icvCvt_32f_64d(distortion2, distortion2_64d, 4);


    /* for each R and t compute error for image pair */
    float* errors;

    errors = (float*)calloc(numImages*numImages,sizeof(float));
    if( errors == 0 )
    {
        return CV_OUTOFMEM_ERR;
    }

    int currImagePair;
    int currRt;
    for( currRt = 0; currRt < numImages; currRt++ )
    {
2776
        int begPoint = 0;
2777 2778 2779 2780 2781 2782
        for(currImagePair = 0; currImagePair < numImages; currImagePair++ )
        {
            /* For current R,t R,t compute relative position of cameras */

            double convRotMatr[9];
            double convTransVect[3];
2783

2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
            icvCreateConvertMatrVect( rotMatrs1_64d + currRt*9,
                                      transVects1_64d + currRt*3,
                                      rotMatrs2_64d + currRt*9,
                                      transVects2_64d + currRt*3,
                                      convRotMatr,
                                      convTransVect);

            /* Project points using relative position of cameras */

            double convRotMatr2[9];
            double convTransVect2[3];

            convRotMatr2[0] = 1;
            convRotMatr2[1] = 0;
            convRotMatr2[2] = 0;

            convRotMatr2[3] = 0;
            convRotMatr2[4] = 1;
            convRotMatr2[5] = 0;

            convRotMatr2[6] = 0;
            convRotMatr2[7] = 0;
            convRotMatr2[8] = 1;

            convTransVect2[0] = 0;
            convTransVect2[1] = 0;
            convTransVect2[2] = 0;

            /* Compute error for given pair and Rt */
            /* We must project points to image and compute error */

            CvPoint2D64d* projImagePoints1;
            CvPoint2D64d* projImagePoints2;

            CvPoint3D64d* points1;
            CvPoint3D64d* points2;

            int numberPnt;
            numberPnt = numPoints[currImagePair];
            projImagePoints1 = (CvPoint2D64d*)calloc(numberPnt,sizeof(CvPoint2D64d));
            projImagePoints2 = (CvPoint2D64d*)calloc(numberPnt,sizeof(CvPoint2D64d));

            points1 = (CvPoint3D64d*)calloc(numberPnt,sizeof(CvPoint3D64d));
            points2 = (CvPoint3D64d*)calloc(numberPnt,sizeof(CvPoint3D64d));

            /* Transform object points to first camera position */
2830
            for(int i = 0; i < numberPnt; i++ )
2831 2832 2833 2834 2835 2836
            {
                /* Create second camera point */
                CvPoint3D64d tmpPoint;
                tmpPoint.x = (double)(objectPoints[i].x);
                tmpPoint.y = (double)(objectPoints[i].y);
                tmpPoint.z = (double)(objectPoints[i].z);
2837

2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
                icvConvertPointSystem(  tmpPoint,
                                        points2+i,
                                        rotMatrs2_64d + currImagePair*9,
                                        transVects2_64d + currImagePair*3);

                /* Create first camera point using R, t */
                icvConvertPointSystem(  points2[i],
                                        points1+i,
                                        convRotMatr,
                                        convTransVect);

                CvPoint3D64d tmpPoint2 = { 0, 0, 0 };
                icvConvertPointSystem(  tmpPoint,
                                        &tmpPoint2,
                                        rotMatrs1_64d + currImagePair*9,
                                        transVects1_64d + currImagePair*3);
2854
                /*double err;
2855 2856 2857 2858
                double dx,dy,dz;
                dx = tmpPoint2.x - points1[i].x;
                dy = tmpPoint2.y - points1[i].y;
                dz = tmpPoint2.z - points1[i].z;
2859
                err = sqrt(dx*dx + dy*dy + dz*dz);*/
2860
            }
2861

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
#if 0
            cvProjectPointsSimple(  numPoints[currImagePair],
                                    objectPoints_64d + begPoint,
                                    rotMatrs1_64d + currRt*9,
                                    transVects1_64d + currRt*3,
                                    cameraMatrix1_64d,
                                    distortion1_64d,
                                    projImagePoints1);

            cvProjectPointsSimple(  numPoints[currImagePair],
                                    objectPoints_64d + begPoint,
                                    rotMatrs2_64d + currRt*9,
                                    transVects2_64d + currRt*3,
                                    cameraMatrix2_64d,
                                    distortion2_64d,
                                    projImagePoints2);
#endif

            /* Project with no translate and no rotation */

#if 0
            {
                double nodist[4] = {0,0,0,0};
                cvProjectPointsSimple(  numPoints[currImagePair],
                                        points1,
                                        convRotMatr2,
                                        convTransVect2,
                                        cameraMatrix1_64d,
                                        nodist,
                                        projImagePoints1);

                cvProjectPointsSimple(  numPoints[currImagePair],
                                        points2,
                                        convRotMatr2,
                                        convTransVect2,
                                        cameraMatrix2_64d,
                                        nodist,
                                        projImagePoints2);
2900

2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
            }
#endif

            cvProjectPointsSimple(  numPoints[currImagePair],
                                    points1,
                                    convRotMatr2,
                                    convTransVect2,
                                    cameraMatrix1_64d,
                                    distortion1_64d,
                                    projImagePoints1);

            cvProjectPointsSimple(  numPoints[currImagePair],
                                    points2,
                                    convRotMatr2,
                                    convTransVect2,
                                    cameraMatrix2_64d,
                                    distortion2_64d,
                                    projImagePoints2);

            /* points are projected. Compute error */

            int currPoint;
            double err1 = 0;
            double err2 = 0;
            double err;
            for( currPoint = 0; currPoint < numberPnt; currPoint++ )
            {
2928
                double len1,len2;
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
                double dx1,dy1;
                dx1 = imagePoints1[begPoint+currPoint].x - projImagePoints1[currPoint].x;
                dy1 = imagePoints1[begPoint+currPoint].y - projImagePoints1[currPoint].y;
                len1 = sqrt(dx1*dx1 + dy1*dy1);
                err1 += len1;

                double dx2,dy2;
                dx2 = imagePoints2[begPoint+currPoint].x - projImagePoints2[currPoint].x;
                dy2 = imagePoints2[begPoint+currPoint].y - projImagePoints2[currPoint].y;
                len2 = sqrt(dx2*dx2 + dy2*dy2);
                err2 += len2;
            }

            err1 /= (float)(numberPnt);
            err2 /= (float)(numberPnt);

            err = (err1+err2) * 0.5;
            begPoint += numberPnt;

            /* Set this error to */
            errors[numImages*currImagePair+currRt] = (float)err;

            free(points1);
            free(points2);
            free(projImagePoints1);
            free(projImagePoints2);
        }
    }

    /* Just select R and t with minimal average error */

    int bestnumRt = 0;
    float minError = 0;/* Just for no warnings. Uses 'first' flag. */
    int first = 1;
    for( currRt = 0; currRt < numImages; currRt++ )
    {
        float avErr = 0;
        for(currImagePair = 0; currImagePair < numImages; currImagePair++ )
        {
            avErr += errors[numImages*currImagePair+currRt];
        }
        avErr /= (float)(numImages);

        if( first )
        {
            bestnumRt = 0;
            minError = avErr;
            first = 0;
        }
        else
        {
            if( avErr < minError )
            {
                bestnumRt = currRt;
                minError = avErr;
            }
        }

    }

    double bestRotMatr_64d[9];
    double bestTransVect_64d[3];

    icvCreateConvertMatrVect( rotMatrs1_64d + bestnumRt * 9,
                              transVects1_64d + bestnumRt * 3,
                              rotMatrs2_64d + bestnumRt * 9,
                              transVects2_64d + bestnumRt * 3,
                              bestRotMatr_64d,
                              bestTransVect_64d);

    icvCvt_64d_32f(bestRotMatr_64d,bestRotMatr,9);
    icvCvt_64d_32f(bestTransVect_64d,bestTransVect,3);


    free(errors);

    return CV_OK;
}


/* ----------------- Stereo calibration functions --------------------- */

float icvDefinePointPosition(CvPoint2D32f point1,CvPoint2D32f point2,CvPoint2D32f point)
{
    float ax = point2.x - point1.x;
    float ay = point2.y - point1.y;

    float bx = point.x - point1.x;
    float by = point.y - point1.y;

    return (ax*by - ay*bx);
}

/* Convert function for stereo warping */
int icvConvertWarpCoordinates(double coeffs[3][3],
                                CvPoint2D32f* cameraPoint,
                                CvPoint2D32f* warpPoint,
                                int direction)
{
    double x,y;
3029
    double det;
3030 3031 3032 3033
    if( direction == CV_WARP_TO_CAMERA )
    {/* convert from camera image to warped image coordinates */
        x = warpPoint->x;
        y = warpPoint->y;
3034

3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
        det = (coeffs[2][0] * x + coeffs[2][1] * y + coeffs[2][2]);
        if( fabs(det) > 1e-8 )
        {
            cameraPoint->x = (float)((coeffs[0][0] * x + coeffs[0][1] * y + coeffs[0][2]) / det);
            cameraPoint->y = (float)((coeffs[1][0] * x + coeffs[1][1] * y + coeffs[1][2]) / det);
            return CV_OK;
        }
    }
    else if( direction == CV_CAMERA_TO_WARP )
    {/* convert from warped image to camera image coordinates */
        x = cameraPoint->x;
        y = cameraPoint->y;

        det = (coeffs[2][0]*x-coeffs[0][0])*(coeffs[2][1]*y-coeffs[1][1])-(coeffs[2][1]*x-coeffs[0][1])*(coeffs[2][0]*y-coeffs[1][0]);

        if( fabs(det) > 1e-8 )
        {
            warpPoint->x = (float)(((coeffs[0][2]-coeffs[2][2]*x)*(coeffs[2][1]*y-coeffs[1][1])-(coeffs[2][1]*x-coeffs[0][1])*(coeffs[1][2]-coeffs[2][2]*y))/det);
            warpPoint->y = (float)(((coeffs[2][0]*x-coeffs[0][0])*(coeffs[1][2]-coeffs[2][2]*y)-(coeffs[0][2]-coeffs[2][2]*x)*(coeffs[2][0]*y-coeffs[1][0]))/det);
            return CV_OK;
        }
    }
3057

3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092
    return CV_BADFACTOR_ERR;
}

/* Compute stereo params using some camera params */
/* by Valery Mosyagin. int ComputeRestStereoParams(StereoParams *stereoparams) */
int icvComputeRestStereoParams(CvStereoCamera *stereoparams)
{


    icvGetQuadsTransformStruct(stereoparams);

    cvInitPerspectiveTransform( stereoparams->warpSize,
                                stereoparams->quad[0],
                                stereoparams->coeffs[0],
                                0);

    cvInitPerspectiveTransform( stereoparams->warpSize,
                                stereoparams->quad[1],
                                stereoparams->coeffs[1],
                                0);

    /* Create border for warped images */
    CvPoint2D32f corns[4];
    corns[0].x = 0;
    corns[0].y = 0;

    corns[1].x = (float)(stereoparams->camera[0]->imgSize[0]-1);
    corns[1].y = 0;

    corns[2].x = (float)(stereoparams->camera[0]->imgSize[0]-1);
    corns[2].y = (float)(stereoparams->camera[0]->imgSize[1]-1);

    corns[3].x = 0;
    corns[3].y = (float)(stereoparams->camera[0]->imgSize[1]-1);

3093
    for(int i = 0; i < 4; i++ )
3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
    {
        /* For first camera */
        icvConvertWarpCoordinates( stereoparams->coeffs[0],
                                corns+i,
                                stereoparams->border[0]+i,
                                CV_CAMERA_TO_WARP);

        /* For second camera */
        icvConvertWarpCoordinates( stereoparams->coeffs[1],
                                corns+i,
                                stereoparams->border[1]+i,
                                CV_CAMERA_TO_WARP);
    }

    /* Test compute  */
    {
        CvPoint2D32f warpPoints[4];
        warpPoints[0] = cvPoint2D32f(0,0);
        warpPoints[1] = cvPoint2D32f(stereoparams->warpSize.width-1,0);
        warpPoints[2] = cvPoint2D32f(stereoparams->warpSize.width-1,stereoparams->warpSize.height-1);
        warpPoints[3] = cvPoint2D32f(0,stereoparams->warpSize.height-1);

        CvPoint2D32f camPoints1[4];
        CvPoint2D32f camPoints2[4];

        for( int i = 0; i < 4; i++ )
        {
            icvConvertWarpCoordinates(stereoparams->coeffs[0],
                                camPoints1+i,
                                warpPoints+i,
                                CV_WARP_TO_CAMERA);

            icvConvertWarpCoordinates(stereoparams->coeffs[1],
                                camPoints2+i,
                                warpPoints+i,
                                CV_WARP_TO_CAMERA);
        }
    }


    /* Allocate memory for scanlines coeffs */

    stereoparams->lineCoeffs = (CvStereoLineCoeff*)calloc(stereoparams->warpSize.height,sizeof(CvStereoLineCoeff));

    /* Compute coeffs for epilines  */

    icvComputeCoeffForStereo( stereoparams);

    /* all coeffs are known */
    return CV_OK;
}

/*-------------------------------------------------------------------------------------------*/

int icvStereoCalibration( int numImages,
                            int* nums,
                            CvSize imageSize,
                            CvPoint2D32f* imagePoints1,
                            CvPoint2D32f* imagePoints2,
                            CvPoint3D32f* objectPoints,
                            CvStereoCamera* stereoparams
                           )
{
    /* Firstly we must calibrate both cameras */
    /*  Alocate memory for data */
    /* Allocate for translate vectors */
    float* transVects1;
    float* transVects2;
    float* rotMatrs1;
    float* rotMatrs2;

    transVects1 = (float*)calloc(numImages,sizeof(float)*3);
    transVects2 = (float*)calloc(numImages,sizeof(float)*3);

    rotMatrs1   = (float*)calloc(numImages,sizeof(float)*9);
    rotMatrs2   = (float*)calloc(numImages,sizeof(float)*9);

    /* Calibrate first camera */
    cvCalibrateCamera(  numImages,
                        nums,
                        imageSize,
                        imagePoints1,
                        objectPoints,
                        stereoparams->camera[0]->distortion,
                        stereoparams->camera[0]->matrix,
                        transVects1,
                        rotMatrs1,
                        1);

    /* Calibrate second camera */
    cvCalibrateCamera(  numImages,
                        nums,
                        imageSize,
                        imagePoints2,
                        objectPoints,
                        stereoparams->camera[1]->distortion,
                        stereoparams->camera[1]->matrix,
                        transVects2,
                        rotMatrs2,
                        1);

    /* Cameras are calibrated */

    stereoparams->camera[0]->imgSize[0] = (float)imageSize.width;
    stereoparams->camera[0]->imgSize[1] = (float)imageSize.height;

    stereoparams->camera[1]->imgSize[0] = (float)imageSize.width;
    stereoparams->camera[1]->imgSize[1] = (float)imageSize.height;

    icvSelectBestRt(    numImages,
                        nums,
                        imagePoints1,
                        imagePoints2,
                        objectPoints,
                        stereoparams->camera[0]->matrix,
                        stereoparams->camera[0]->distortion,
                        rotMatrs1,
                        transVects1,
                        stereoparams->camera[1]->matrix,
                        stereoparams->camera[1]->distortion,
                        rotMatrs2,
                        transVects2,
                        stereoparams->rotMatrix,
                        stereoparams->transVector
                        );

    /* Free memory */
    free(transVects1);
    free(transVects2);
    free(rotMatrs1);
    free(rotMatrs2);

    icvComputeRestStereoParams(stereoparams);

    return CV_NO_ERR;
}

3231
#if 0
3232
/* Find line from epipole */
3233
static void FindLine(CvPoint2D32f epipole,CvSize imageSize,CvPoint2D32f point,CvPoint2D32f *start,CvPoint2D32f *end)
3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
{
    CvPoint2D32f frameBeg;
    CvPoint2D32f frameEnd;
    CvPoint2D32f cross[4];
    int     haveCross[4];
    float   dist;

    haveCross[0] = 0;
    haveCross[1] = 0;
    haveCross[2] = 0;
    haveCross[3] = 0;

    frameBeg.x = 0;
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = 0;
    haveCross[0] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[0]);
3251

3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = (float)(imageSize.height);
    haveCross[1] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[1]);

    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = (float)(imageSize.height);
    haveCross[2] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[2]);
3263

3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
    frameBeg.x = 0;
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = 0;
    haveCross[3] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[3]);

    int n;
    float minDist = (float)(INT_MAX);
    float maxDist = (float)(INT_MIN);

    int maxN = -1;
    int minN = -1;
3276

3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
    for( n = 0; n < 4; n++ )
    {
        if( haveCross[n] > 0 )
        {
            dist =  (epipole.x - cross[n].x)*(epipole.x - cross[n].x) +
                    (epipole.y - cross[n].y)*(epipole.y - cross[n].y);

            if( dist < minDist )
            {
                minDist = dist;
                minN = n;
            }

            if( dist > maxDist )
            {
                maxDist = dist;
                maxN = n;
            }
        }
    }

    if( minN >= 0 && maxN >= 0 && (minN != maxN) )
    {
        *start = cross[minN];
        *end   = cross[maxN];
    }
    else
    {
        start->x = 0;
        start->y = 0;
        end->x = 0;
        end->y = 0;
    }

    return;
}

/* Find line which cross frame by line(a,b,c) */
3315
static void FindLineForEpiline(CvSize imageSize,float a,float b,float c,CvPoint2D32f *start,CvPoint2D32f *end)
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
{
    CvPoint2D32f frameBeg;
    CvPoint2D32f frameEnd;
    CvPoint2D32f cross[4];
    int     haveCross[4];
    float   dist;

    haveCross[0] = 0;
    haveCross[1] = 0;
    haveCross[2] = 0;
    haveCross[3] = 0;

    frameBeg.x = 0;
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = 0;
    haveCross[0] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[0]);
3333

3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = 0;
    frameEnd.x = (float)(imageSize.width);
    frameEnd.y = (float)(imageSize.height);
    haveCross[1] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[1]);

    frameBeg.x = (float)(imageSize.width);
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = (float)(imageSize.height);
    haveCross[2] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[2]);
3345

3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
    frameBeg.x = 0;
    frameBeg.y = (float)(imageSize.height);
    frameEnd.x = 0;
    frameEnd.y = 0;
    haveCross[3] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[3]);

    int n;
    float minDist = (float)(INT_MAX);
    float maxDist = (float)(INT_MIN);

    int maxN = -1;
    int minN = -1;

    double midPointX = imageSize.width  / 2.0;
    double midPointY = imageSize.height / 2.0;

    for( n = 0; n < 4; n++ )
    {
        if( haveCross[n] > 0 )
        {
            dist =  (float)((midPointX - cross[n].x)*(midPointX - cross[n].x) +
                            (midPointY - cross[n].y)*(midPointY - cross[n].y));

            if( dist < minDist )
            {
                minDist = dist;
                minN = n;
            }

            if( dist > maxDist )
            {
                maxDist = dist;
                maxN = n;
            }
        }
    }

    if( minN >= 0 && maxN >= 0 && (minN != maxN) )
    {
        *start = cross[minN];
        *end   = cross[maxN];
    }
    else
    {
        start->x = 0;
        start->y = 0;
        end->x = 0;
        end->y = 0;
    }

    return;
3397

3398 3399 3400
}

/* Cross lines */
3401
static int GetCrossLines(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f p2_start,CvPoint2D32f p2_end,CvPoint2D32f *cross)
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
{
    double ex1,ey1,ex2,ey2;
    double px1,py1,px2,py2;
    double del;
    double delA,delB,delX,delY;
    double alpha,betta;

    ex1 = p1_start.x;
    ey1 = p1_start.y;
    ex2 = p1_end.x;
    ey2 = p1_end.y;

    px1 = p2_start.x;
    py1 = p2_start.y;
    px2 = p2_end.x;
    py2 = p2_end.y;

    del = (ex1-ex2)*(py2-py1)+(ey2-ey1)*(px2-px1);
    if( del == 0)
    {
        return -1;
    }

    delA =  (px1-ex1)*(py1-py2) + (ey1-py1)*(px1-px2);
    delB =  (ex1-px1)*(ey1-ey2) + (py1-ey1)*(ex1-ex2);

    alpha =  delA / del;
    betta = -delB / del;

    if( alpha < 0 || alpha > 1.0 || betta < 0 || betta > 1.0)
    {
        return -1;
    }

    delX =  (ex1-ex2)*(py1*(px1-px2)-px1*(py1-py2))+
            (px1-px2)*(ex1*(ey1-ey2)-ey1*(ex1-ex2));

    delY =  (ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2))+
            (py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2));

    cross->x = (float)( delX / del);
    cross->y = (float)(-delY / del);
    return 1;
}
3446
#endif
3447 3448 3449

int icvGetCrossPieceVector(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f v2_start,CvPoint2D32f v2_end,CvPoint2D32f *cross)
{
3450 3451 3452 3453
    double ex1 = p1_start.x;
    double ey1 = p1_start.y;
    double ex2 = p1_end.x;
    double ey2 = p1_end.y;
3454

3455 3456 3457 3458
    double px1 = v2_start.x;
    double py1 = v2_start.y;
    double px2 = v2_end.x;
    double py2 = v2_end.y;
3459

3460
    double del = (ex1-ex2)*(py2-py1)+(ey2-ey1)*(px2-px1);
3461 3462 3463 3464 3465
    if( del == 0)
    {
        return -1;
    }

3466 3467
    double delA =  (px1-ex1)*(py1-py2) + (ey1-py1)*(px1-px2);
    //double delB =  (ex1-px1)*(ey1-ey2) + (py1-ey1)*(ex1-ex2);
3468

3469 3470
    double alpha =  delA / del;
    //double betta = -delB / del;
3471 3472 3473 3474 3475 3476

    if( alpha < 0 || alpha > 1.0 )
    {
        return -1;
    }

3477
    double delX =  (ex1-ex2)*(py1*(px1-px2)-px1*(py1-py2))+
3478 3479
            (px1-px2)*(ex1*(ey1-ey2)-ey1*(ex1-ex2));

3480
    double delY =  (ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2))+
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
            (py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2));

    cross->x = (float)( delX / del);
    cross->y = (float)(-delY / del);
    return 1;
}


int icvGetCrossLineDirect(CvPoint2D32f p1,CvPoint2D32f p2,float a,float b,float c,CvPoint2D32f* cross)
{
    double del;
    double delX,delY,delA;

    double px1,px2,py1,py2;
    double X,Y,alpha;

    px1 = p1.x;
    py1 = p1.y;

    px2 = p2.x;
    py2 = p2.y;

    del = a * (px2 - px1) + b * (py2-py1);
    if( del == 0 )
    {
        return -1;
    }

    delA = - c - a*px1 - b*py1;
    alpha = delA / del;

    if( alpha < 0 || alpha > 1.0 )
    {
        return -1;/* no cross */
    }

    delX = b * (py1*(px1-px2) - px1*(py1-py2)) + c * (px1-px2);
    delY = a * (px1*(py1-py2) - py1*(px1-px2)) + c * (py1-py2);

    X = delX / del;
    Y = delY / del;

    cross->x = (float)X;
    cross->y = (float)Y;
3525

3526 3527 3528
    return 1;
}

3529 3530
#if 0
static int cvComputeEpipoles( CvMatr32f camMatr1,  CvMatr32f camMatr2,
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
                            CvMatr32f rotMatr1,  CvMatr32f rotMatr2,
                            CvVect32f transVect1,CvVect32f transVect2,
                            CvVect32f epipole1,
                            CvVect32f epipole2)
{

    /* Copy matrix */

    CvMat ccamMatr1 = cvMat(3,3,CV_MAT32F,camMatr1);
    CvMat ccamMatr2 = cvMat(3,3,CV_MAT32F,camMatr2);
    CvMat crotMatr1 = cvMat(3,3,CV_MAT32F,rotMatr1);
    CvMat crotMatr2 = cvMat(3,3,CV_MAT32F,rotMatr2);
    CvMat ctransVect1 = cvMat(3,1,CV_MAT32F,transVect1);
    CvMat ctransVect2 = cvMat(3,1,CV_MAT32F,transVect2);
    CvMat cepipole1 = cvMat(3,1,CV_MAT32F,epipole1);
    CvMat cepipole2 = cvMat(3,1,CV_MAT32F,epipole2);


    CvMat cmatrP1   = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrP1);
    CvMat cmatrP2   = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrP2);
    CvMat cvectp1   = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&cvectp1);
    CvMat cvectp2   = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&cvectp2);
    CvMat ctmpF1    = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpF1);
    CvMat ctmpM1    = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpM1);
    CvMat ctmpM2    = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpM2);
    CvMat cinvP1    = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cinvP1);
    CvMat cinvP2    = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cinvP2);
    CvMat ctmpMatr  = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpMatr);
    CvMat ctmpVect1 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpVect1);
    CvMat ctmpVect2 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpVect2);
    CvMat cmatrF1   = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrF1);
    CvMat ctmpF     = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpF);
    CvMat ctmpE1    = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpE1);
    CvMat ctmpE2    = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpE2);

    /* Compute first */
    cvmMul( &ccamMatr1, &crotMatr1, &cmatrP1);
    cvmInvert( &cmatrP1,&cinvP1 );
    cvmMul( &ccamMatr1, &ctransVect1, &cvectp1 );
3570

3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
    /* Compute second */
    cvmMul( &ccamMatr2, &crotMatr2, &cmatrP2 );
    cvmInvert( &cmatrP2,&cinvP2 );
    cvmMul( &ccamMatr2, &ctransVect2, &cvectp2 );

    cvmMul( &cmatrP1, &cinvP2, &ctmpM1);
    cvmMul( &ctmpM1, &cvectp2, &ctmpVect1);
    cvmSub( &cvectp1,&ctmpVect1,&ctmpE1);

    cvmMul( &cmatrP2, &cinvP1, &ctmpM2);
    cvmMul( &ctmpM2, &cvectp1, &ctmpVect2);
    cvmSub( &cvectp2, &ctmpVect2, &ctmpE2);


    /* Need scale */

    cvmScale(&ctmpE1,&cepipole1,1.0);
    cvmScale(&ctmpE2,&cepipole2,1.0);

    cvmFree(&cmatrP1);
    cvmFree(&cmatrP1);
    cvmFree(&cvectp1);
    cvmFree(&cvectp2);
    cvmFree(&ctmpF1);
    cvmFree(&ctmpM1);
    cvmFree(&ctmpM2);
    cvmFree(&cinvP1);
    cvmFree(&cinvP2);
    cvmFree(&ctmpMatr);
    cvmFree(&ctmpVect1);
    cvmFree(&ctmpVect2);
    cvmFree(&cmatrF1);
    cvmFree(&ctmpF);
    cvmFree(&ctmpE1);
    cvmFree(&ctmpE2);

    return CV_NO_ERR;
}/* cvComputeEpipoles */
3609
#endif
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630

/* Compute epipoles for fundamental matrix */
int cvComputeEpipolesFromFundMatrix(CvMatr32f fundMatr,
                                         CvPoint3D32f* epipole1,
                                         CvPoint3D32f* epipole2)
{
    /* Decompose fundamental matrix using SVD ( A = U W V') */
    CvMat fundMatrC = cvMat(3,3,CV_MAT32F,fundMatr);

    CvMat* matrW = cvCreateMat(3,3,CV_MAT32F);
    CvMat* matrU = cvCreateMat(3,3,CV_MAT32F);
    CvMat* matrV = cvCreateMat(3,3,CV_MAT32F);

    /* From svd we need just last vector of U and V or last row from U' and V' */
    /* We get transposed matrixes U and V */
    cvSVD(&fundMatrC,matrW,matrU,matrV,CV_SVD_V_T|CV_SVD_U_T);

    /* Get last row from U' and compute epipole1 */
    epipole1->x = matrU->data.fl[6];
    epipole1->y = matrU->data.fl[7];
    epipole1->z = matrU->data.fl[8];
3631

3632 3633 3634 3635 3636 3637 3638
    /* Get last row from V' and compute epipole2 */
    epipole2->x = matrV->data.fl[6];
    epipole2->y = matrV->data.fl[7];
    epipole2->z = matrV->data.fl[8];

    cvReleaseMat(&matrW);
    cvReleaseMat(&matrU);
3639
    cvReleaseMat(&matrV);
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
    return CV_OK;
}

int cvConvertEssential2Fundamental( CvMatr32f essMatr,
                                         CvMatr32f fundMatr,
                                         CvMatr32f cameraMatr1,
                                         CvMatr32f cameraMatr2)
{/* Fund = inv(CM1') * Ess * inv(CM2) */

    CvMat essMatrC     = cvMat(3,3,CV_MAT32F,essMatr);
    CvMat fundMatrC    = cvMat(3,3,CV_MAT32F,fundMatr);
    CvMat cameraMatr1C = cvMat(3,3,CV_MAT32F,cameraMatr1);
    CvMat cameraMatr2C = cvMat(3,3,CV_MAT32F,cameraMatr2);

    CvMat* invCM2  = cvCreateMat(3,3,CV_MAT32F);
    CvMat* tmpMatr = cvCreateMat(3,3,CV_MAT32F);
    CvMat* invCM1T = cvCreateMat(3,3,CV_MAT32F);

    cvTranspose(&cameraMatr1C,tmpMatr);
3659
    cvInvert(tmpMatr,invCM1T);
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
    cvmMul(invCM1T,&essMatrC,tmpMatr);
    cvInvert(&cameraMatr2C,invCM2);
    cvmMul(tmpMatr,invCM2,&fundMatrC);

    /* Scale fundamental matrix */
    double scale;
    scale = 1.0/fundMatrC.data.fl[8];
    cvConvertScale(&fundMatrC,&fundMatrC,scale);

    cvReleaseMat(&invCM2);
    cvReleaseMat(&tmpMatr);
    cvReleaseMat(&invCM1T);
3672

3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
    return CV_OK;
}

/* Compute essential matrix */

int cvComputeEssentialMatrix(  CvMatr32f rotMatr,
                                    CvMatr32f transVect,
                                    CvMatr32f essMatr)
{
    float transMatr[9];

    /* Make antisymmetric matrix from transpose vector */
    transMatr[0] =   0;
    transMatr[1] = - transVect[2];
    transMatr[2] =   transVect[1];
3688

3689 3690 3691
    transMatr[3] =   transVect[2];
    transMatr[4] =   0;
    transMatr[5] = - transVect[0];
3692

3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
    transMatr[6] = - transVect[1];
    transMatr[7] =   transVect[0];
    transMatr[8] =   0;

    icvMulMatrix_32f(transMatr,3,3,rotMatr,3,3,essMatr);

    return CV_OK;
}