fundam.cpp 38 KB
Newer Older
wester committed
1 2 3 4 5 6 7 8 9
/*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.
//
//
wester committed
10
//                        Intel License Agreement
wester committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
//                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.
//
wester committed
26
//   * The name of Intel Corporation may not be used to endorse or promote products
wester committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
//     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"
wester committed
43
#include "_modelest.h"
wester committed
44

wester committed
45
using namespace cv;
wester committed
46

wester committed
47
template<typename T> int icvCompressPoints( T* ptr, const uchar* mask, int mstep, int count )
a  
Kai Westerkamp committed
48
{
wester committed
49 50 51
    int i, j;
    for( i = j = 0; i < count; i++ )
        if( mask[i*mstep] )
a  
Kai Westerkamp committed
52
        {
wester committed
53 54 55
            if( i > j )
                ptr[j] = ptr[i];
            j++;
a  
Kai Westerkamp committed
56
        }
wester committed
57
    return j;
a  
Kai Westerkamp committed
58 59
}

wester committed
60
class CvHomographyEstimator : public CvModelEstimator2
wester committed
61 62
{
public:
wester committed
63 64 65 66 67 68 69 70 71
    CvHomographyEstimator( int modelPoints );

    virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model );
    virtual bool refine( const CvMat* m1, const CvMat* m2,
                         CvMat* model, int maxIters );
protected:
    virtual void computeReprojError( const CvMat* m1, const CvMat* m2,
                                     const CvMat* model, CvMat* error );
};
wester committed
72 73


wester committed
74 75 76 77 78 79
CvHomographyEstimator::CvHomographyEstimator(int _modelPoints)
    : CvModelEstimator2(_modelPoints, cvSize(3,3), 1)
{
    assert( _modelPoints == 4 || _modelPoints == 5 );
    checkPartialSubsets = false;
}
wester committed
80

wester committed
81 82 83 84 85 86 87 88 89 90 91 92 93
int CvHomographyEstimator::runKernel( const CvMat* m1, const CvMat* m2, CvMat* H )
{
    int i, count = m1->rows*m1->cols;
    const CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;
    const CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;

    double LtL[9][9], W[9][1], V[9][9];
    CvMat _LtL = cvMat( 9, 9, CV_64F, LtL );
    CvMat matW = cvMat( 9, 1, CV_64F, W );
    CvMat matV = cvMat( 9, 9, CV_64F, V );
    CvMat _H0 = cvMat( 3, 3, CV_64F, V[8] );
    CvMat _Htemp = cvMat( 3, 3, CV_64F, V[7] );
    CvPoint2D64f cM={0,0}, cm={0,0}, sM={0,0}, sm={0,0};
wester committed
94

wester committed
95
    for( i = 0; i < count; i++ )
wester committed
96
    {
wester committed
97 98 99
        cm.x += m[i].x; cm.y += m[i].y;
        cM.x += M[i].x; cM.y += M[i].y;
    }
wester committed
100

wester committed
101 102
    cm.x /= count; cm.y /= count;
    cM.x /= count; cM.y /= count;
wester committed
103

wester committed
104 105 106 107 108 109 110
    for( i = 0; i < count; i++ )
    {
        sm.x += fabs(m[i].x - cm.x);
        sm.y += fabs(m[i].y - cm.y);
        sM.x += fabs(M[i].x - cM.x);
        sM.y += fabs(M[i].y - cM.y);
    }
wester committed
111

wester committed
112 113 114 115 116
    if( fabs(sm.x) < DBL_EPSILON || fabs(sm.y) < DBL_EPSILON ||
        fabs(sM.x) < DBL_EPSILON || fabs(sM.y) < DBL_EPSILON )
        return 0;
    sm.x = count/sm.x; sm.y = count/sm.y;
    sM.x = count/sM.x; sM.y = count/sM.y;
wester committed
117

wester committed
118 119 120 121
    double invHnorm[9] = { 1./sm.x, 0, cm.x, 0, 1./sm.y, cm.y, 0, 0, 1 };
    double Hnorm2[9] = { sM.x, 0, -cM.x*sM.x, 0, sM.y, -cM.y*sM.y, 0, 0, 1 };
    CvMat _invHnorm = cvMat( 3, 3, CV_64FC1, invHnorm );
    CvMat _Hnorm2 = cvMat( 3, 3, CV_64FC1, Hnorm2 );
wester committed
122

wester committed
123 124
    cvZero( &_LtL );
    for( i = 0; i < count; i++ )
wester committed
125
    {
wester committed
126 127 128 129 130 131 132 133 134 135
        double x = (m[i].x - cm.x)*sm.x, y = (m[i].y - cm.y)*sm.y;
        double X = (M[i].x - cM.x)*sM.x, Y = (M[i].y - cM.y)*sM.y;
        double Lx[] = { X, Y, 1, 0, 0, 0, -x*X, -x*Y, -x };
        double Ly[] = { 0, 0, 0, X, Y, 1, -y*X, -y*Y, -y };
        int j, k;
        for( j = 0; j < 9; j++ )
            for( k = j; k < 9; k++ )
                LtL[j][k] += Lx[j]*Lx[k] + Ly[j]*Ly[k];
    }
    cvCompleteSymm( &_LtL );
wester committed
136

wester committed
137 138 139 140 141
    //cvSVD( &_LtL, &matW, 0, &matV, CV_SVD_MODIFY_A + CV_SVD_V_T );
    cvEigenVV( &_LtL, &matV, &matW );
    cvMatMul( &_invHnorm, &_H0, &_Htemp );
    cvMatMul( &_Htemp, &_Hnorm2, &_H0 );
    cvConvertScale( &_H0, H, 1./_H0.data.db[8] );
wester committed
142

wester committed
143 144
    return 1;
}
wester committed
145 146


wester committed
147 148
void CvHomographyEstimator::computeReprojError( const CvMat* m1, const CvMat* m2,
                                                const CvMat* model, CvMat* _err )
wester committed
149
{
wester committed
150 151 152 153 154 155 156
    int i, count = m1->rows*m1->cols;
    const CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;
    const CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;
    const double* H = model->data.db;
    float* err = _err->data.fl;

    for( i = 0; i < count; i++ )
wester committed
157
    {
wester committed
158 159 160 161
        double ww = 1./(H[6]*M[i].x + H[7]*M[i].y + 1.);
        double dx = (H[0]*M[i].x + H[1]*M[i].y + H[2])*ww - m[i].x;
        double dy = (H[3]*M[i].x + H[4]*M[i].y + H[5])*ww - m[i].y;
        err[i] = (float)(dx*dx + dy*dy);
wester committed
162
    }
wester committed
163
}
wester committed
164

wester committed
165 166 167 168 169 170 171 172 173 174
bool CvHomographyEstimator::refine( const CvMat* m1, const CvMat* m2, CvMat* model, int maxIters )
{
    CvLevMarq solver(8, 0, cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, maxIters, DBL_EPSILON));
    int i, j, k, count = m1->rows*m1->cols;
    const CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;
    const CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;
    CvMat modelPart = cvMat( solver.param->rows, solver.param->cols, model->type, model->data.ptr );
    cvCopy( &modelPart, solver.param );

    for(;;)
wester committed
175
    {
wester committed
176 177 178
        const CvMat* _param = 0;
        CvMat *_JtJ = 0, *_JtErr = 0;
        double* _errNorm = 0;
wester committed
179

wester committed
180 181
        if( !solver.updateAlt( _param, _JtJ, _JtErr, _errNorm ))
            break;
wester committed
182 183 184

        for( i = 0; i < count; i++ )
        {
wester committed
185
            const double* h = _param->data.db;
wester committed
186 187 188
            double Mx = M[i].x, My = M[i].y;
            double ww = h[6]*Mx + h[7]*My + 1.;
            ww = fabs(ww) > DBL_EPSILON ? 1./ww : 0;
wester committed
189 190 191 192
            double _xi = (h[0]*Mx + h[1]*My + h[2])*ww;
            double _yi = (h[3]*Mx + h[4]*My + h[5])*ww;
            double err[] = { _xi - m[i].x, _yi - m[i].y };
            if( _JtJ || _JtErr )
wester committed
193
            {
wester committed
194 195 196 197 198 199 200 201 202 203 204 205
                double J[][8] =
                {
                    { Mx*ww, My*ww, ww, 0, 0, 0, -Mx*ww*_xi, -My*ww*_xi },
                    { 0, 0, 0, Mx*ww, My*ww, ww, -Mx*ww*_yi, -My*ww*_yi }
                };

                for( j = 0; j < 8; j++ )
                {
                    for( k = j; k < 8; k++ )
                        _JtJ->data.db[j*8+k] += J[0][j]*J[0][k] + J[1][j]*J[1][k];
                    _JtErr->data.db[j] += J[0][j]*err[0] + J[1][j]*err[1];
                }
wester committed
206
            }
wester committed
207 208
            if( _errNorm )
                *_errNorm += err[0]*err[0] + err[1]*err[1];
wester committed
209 210 211
        }
    }

wester committed
212 213
    cvCopy( solver.param, &modelPart );
    return true;
wester committed
214 215 216
}


wester committed
217 218 219 220
CV_IMPL int
cvFindHomography( const CvMat* objectPoints, const CvMat* imagePoints,
                  CvMat* __H, int method, double ransacReprojThreshold,
                  CvMat* mask )
wester committed
221
{
wester committed
222 223
    const double confidence = 0.995;
    const int maxIters = 2000;
wester committed
224 225
    const double defaultRANSACReprojThreshold = 3;
    bool result = false;
wester committed
226
    Ptr<CvMat> m, M, tempMask;
wester committed
227

wester committed
228 229 230
    double H[9];
    CvMat matH = cvMat( 3, 3, CV_64FC1, H );
    int count;
wester committed
231

wester committed
232
    CV_Assert( CV_IS_MAT(imagePoints) && CV_IS_MAT(objectPoints) );
wester committed
233

wester committed
234 235
    count = MAX(imagePoints->cols, imagePoints->rows);
    CV_Assert( count >= 4 );
wester committed
236 237 238
    if( ransacReprojThreshold <= 0 )
        ransacReprojThreshold = defaultRANSACReprojThreshold;

wester committed
239 240 241 242 243
    m = cvCreateMat( 1, count, CV_64FC2 );
    cvConvertPointsHomogeneous( imagePoints, m );

    M = cvCreateMat( 1, count, CV_64FC2 );
    cvConvertPointsHomogeneous( objectPoints, M );
wester committed
244

wester committed
245
    if( mask )
wester committed
246
    {
wester committed
247 248 249
        CV_Assert( CV_IS_MASK_ARR(mask) && CV_IS_MAT_CONT(mask->type) &&
            (mask->rows == 1 || mask->cols == 1) &&
            mask->rows*mask->cols == count );
wester committed
250
    }
wester committed
251 252 253 254 255 256 257 258 259 260 261 262
    if( mask || count > 4 )
        tempMask = cvCreateMat( 1, count, CV_8U );
    if( !tempMask.empty() )
        cvSet( tempMask, cvScalarAll(1.) );

    CvHomographyEstimator estimator(4);
    if( count == 4 )
        method = 0;
    if( method == CV_LMEDS )
        result = estimator.runLMeDS( M, m, &matH, tempMask, confidence, maxIters );
    else if( method == CV_RANSAC )
        result = estimator.runRANSAC( M, m, &matH, tempMask, ransacReprojThreshold, confidence, maxIters);
wester committed
263
    else
wester committed
264
        result = estimator.runKernel( M, m, &matH ) > 0;
wester committed
265

wester committed
266
    if( result && count > 4 )
wester committed
267
    {
wester committed
268 269 270 271 272 273
        icvCompressPoints( (CvPoint2D64f*)M->data.ptr, tempMask->data.ptr, 1, count );
        count = icvCompressPoints( (CvPoint2D64f*)m->data.ptr, tempMask->data.ptr, 1, count );
        M->cols = m->cols = count;
        if( method == CV_RANSAC )
            estimator.runKernel( M, m, &matH );
        estimator.refine( M, m, &matH, 10 );
wester committed
274 275 276
    }

    if( result )
wester committed
277 278 279
        cvConvert( &matH, __H );

    if( mask && tempMask )
wester committed
280
    {
wester committed
281 282 283 284
        if( CV_ARE_SIZES_EQ(mask, tempMask) )
           cvCopy( tempMask, mask );
        else
           cvTranspose( tempMask, mask );
wester committed
285 286
    }

wester committed
287
    return (int)result;
wester committed
288 289 290
}


wester committed
291
/* Evaluation of Fundamental Matrix from point correspondences.
wester committed
292 293 294 295 296 297 298 299
   The original code has been written by Valery Mosyagin */

/* The algorithms (except for RANSAC) and the notation have been taken from
   Zhengyou Zhang's research report
   "Determining the Epipolar Geometry and its Uncertainty: A Review"
   that can be found at http://www-sop.inria.fr/robotvis/personnel/zzhang/zzhang-eng.html */

/************************************** 7-point algorithm *******************************/
wester committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
class CvFMEstimator : public CvModelEstimator2
{
public:
    CvFMEstimator( int _modelPoints );

    virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model );
    virtual int run7Point( const CvMat* m1, const CvMat* m2, CvMat* model );
    virtual int run8Point( const CvMat* m1, const CvMat* m2, CvMat* model );
protected:
    virtual void computeReprojError( const CvMat* m1, const CvMat* m2,
                                     const CvMat* model, CvMat* error );
};

CvFMEstimator::CvFMEstimator( int _modelPoints )
: CvModelEstimator2( _modelPoints, cvSize(3,3), _modelPoints == 7 ? 3 : 1 )
wester committed
315
{
wester committed
316 317 318 319 320 321 322 323
    assert( _modelPoints == 7 || _modelPoints == 8 );
}


int CvFMEstimator::runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )
{
    return modelPoints == 7 ? run7Point( m1, m2, model ) : run8Point( m1, m2, model );
}
wester committed
324

wester committed
325
int CvFMEstimator::run7Point( const CvMat* _m1, const CvMat* _m2, CvMat* _fmatrix )
wester committed
326
{
wester committed
327
    double a[7*9], w[7], v[9*9], c[4], r[3];
wester committed
328 329
    double* f1, *f2;
    double t0, t1, t2;
wester committed
330 331 332 333 334 335 336 337
    CvMat A = cvMat( 7, 9, CV_64F, a );
    CvMat V = cvMat( 9, 9, CV_64F, v );
    CvMat W = cvMat( 7, 1, CV_64F, w );
    CvMat coeffs = cvMat( 1, 4, CV_64F, c );
    CvMat roots = cvMat( 1, 3, CV_64F, r );
    const CvPoint2D64f* m1 = (const CvPoint2D64f*)_m1->data.ptr;
    const CvPoint2D64f* m2 = (const CvPoint2D64f*)_m2->data.ptr;
    double* fmatrix = _fmatrix->data.db;
wester committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    int i, k, n;

    // form a linear system: i-th row of A(=a) represents
    // the equation: (m2[i], 1)'*F*(m1[i], 1) = 0
    for( i = 0; i < 7; i++ )
    {
        double x0 = m1[i].x, y0 = m1[i].y;
        double x1 = m2[i].x, y1 = m2[i].y;

        a[i*9+0] = x1*x0;
        a[i*9+1] = x1*y0;
        a[i*9+2] = x1;
        a[i*9+3] = y1*x0;
        a[i*9+4] = y1*y0;
        a[i*9+5] = y1;
        a[i*9+6] = x0;
        a[i*9+7] = y0;
        a[i*9+8] = 1;
    }

    // A*(f11 f12 ... f33)' = 0 is singular (7 equations for 9 variables), so
    // the solution is linear subspace of dimensionality 2.
    // => use the last two singular vectors as a basis of the space
    // (according to SVD properties)
wester committed
362
    cvSVD( &A, &W, 0, &V, CV_SVD_MODIFY_A + CV_SVD_V_T );
wester committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    f1 = v + 7*9;
    f2 = v + 8*9;

    // f1, f2 is a basis => lambda*f1 + mu*f2 is an arbitrary f. matrix.
    // as it is determined up to a scale, normalize lambda & mu (lambda + mu = 1),
    // so f ~ lambda*f1 + (1 - lambda)*f2.
    // use the additional constraint det(f) = det(lambda*f1 + (1-lambda)*f2) to find lambda.
    // it will be a cubic equation.
    // find c - polynomial coefficients.
    for( i = 0; i < 9; i++ )
        f1[i] -= f2[i];

    t0 = f2[4]*f2[8] - f2[5]*f2[7];
    t1 = f2[3]*f2[8] - f2[5]*f2[6];
    t2 = f2[3]*f2[7] - f2[4]*f2[6];

    c[3] = f2[0]*t0 - f2[1]*t1 + f2[2]*t2;

    c[2] = f1[0]*t0 - f1[1]*t1 + f1[2]*t2 -
wester committed
382 383 384 385 386 387
           f1[3]*(f2[1]*f2[8] - f2[2]*f2[7]) +
           f1[4]*(f2[0]*f2[8] - f2[2]*f2[6]) -
           f1[5]*(f2[0]*f2[7] - f2[1]*f2[6]) +
           f1[6]*(f2[1]*f2[5] - f2[2]*f2[4]) -
           f1[7]*(f2[0]*f2[5] - f2[2]*f2[3]) +
           f1[8]*(f2[0]*f2[4] - f2[1]*f2[3]);
wester committed
388 389 390 391 392 393

    t0 = f1[4]*f1[8] - f1[5]*f1[7];
    t1 = f1[3]*f1[8] - f1[5]*f1[6];
    t2 = f1[3]*f1[7] - f1[4]*f1[6];

    c[1] = f2[0]*t0 - f2[1]*t1 + f2[2]*t2 -
wester committed
394 395 396 397 398 399
           f2[3]*(f1[1]*f1[8] - f1[2]*f1[7]) +
           f2[4]*(f1[0]*f1[8] - f1[2]*f1[6]) -
           f2[5]*(f1[0]*f1[7] - f1[1]*f1[6]) +
           f2[6]*(f1[1]*f1[5] - f1[2]*f1[4]) -
           f2[7]*(f1[0]*f1[5] - f1[2]*f1[3]) +
           f2[8]*(f1[0]*f1[4] - f1[1]*f1[3]);
wester committed
400 401 402 403

    c[0] = f1[0]*t0 - f1[1]*t1 + f1[2]*t2;

    // solve the cubic equation; there can be 1 to 3 roots ...
wester committed
404
    n = cvSolveCubic( &coeffs, &roots );
wester committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

    if( n < 1 || n > 3 )
        return n;

    for( k = 0; k < n; k++, fmatrix += 9 )
    {
        // for each root form the fundamental matrix
        double lambda = r[k], mu = 1.;
        double s = f1[8]*r[k] + f2[8];

        // normalize each matrix, so that F(3,3) (~fmatrix[8]) == 1
        if( fabs(s) > DBL_EPSILON )
        {
            mu = 1./s;
            lambda *= mu;
            fmatrix[8] = 1.;
        }
        else
            fmatrix[8] = 0.;

        for( i = 0; i < 8; i++ )
            fmatrix[i] = f1[i]*lambda + f2[i]*mu;
    }

    return n;
}


wester committed
433
int CvFMEstimator::run8Point( const CvMat* _m1, const CvMat* _m2, CvMat* _fmatrix )
wester committed
434
{
wester committed
435 436 437 438 439
    double a[9*9], w[9], v[9*9];
    CvMat W = cvMat( 1, 9, CV_64F, w );
    CvMat V = cvMat( 9, 9, CV_64F, v );
    CvMat A = cvMat( 9, 9, CV_64F, a );
    CvMat U, F0, TF;
wester committed
440

wester committed
441 442 443 444 445 446 447 448
    CvPoint2D64f m0c = {0,0}, m1c = {0,0};
    double t, scale0 = 0, scale1 = 0;

    const CvPoint2D64f* m1 = (const CvPoint2D64f*)_m1->data.ptr;
    const CvPoint2D64f* m2 = (const CvPoint2D64f*)_m2->data.ptr;
    double* fmatrix = _fmatrix->data.db;
    CV_Assert( (_m1->cols == 1 || _m1->rows == 1) && CV_ARE_SIZES_EQ(_m1, _m2));
    int i, j, k, count = _m1->cols*_m1->rows;
wester committed
449 450 451 452

    // compute centers and average distances for each of the two point sets
    for( i = 0; i < count; i++ )
    {
wester committed
453 454 455 456 457
        double x = m1[i].x, y = m1[i].y;
        m0c.x += x; m0c.y += y;

        x = m2[i].x, y = m2[i].y;
        m1c.x += x; m1c.y += y;
wester committed
458 459 460 461 462 463
    }

    // calculate the normalizing transformations for each of the point sets:
    // after the transformation each set will have the mass center at the coordinate origin
    // and the average distance from the origin will be ~sqrt(2).
    t = 1./count;
wester committed
464 465
    m0c.x *= t; m0c.y *= t;
    m1c.x *= t; m1c.y *= t;
wester committed
466 467 468

    for( i = 0; i < count; i++ )
    {
wester committed
469 470 471 472 473
        double x = m1[i].x - m0c.x, y = m1[i].y - m0c.y;
        scale0 += sqrt(x*x + y*y);

        x = m2[i].x - m1c.x, y = m2[i].y - m1c.y;
        scale1 += sqrt(x*x + y*y);
wester committed
474 475
    }

wester committed
476
    scale0 *= t;
wester committed
477 478
    scale1 *= t;

wester committed
479
    if( scale0 < FLT_EPSILON || scale1 < FLT_EPSILON )
wester committed
480 481
        return 0;

wester committed
482 483
    scale0 = sqrt(2.)/scale0;
    scale1 = sqrt(2.)/scale1;
wester committed
484

wester committed
485
    cvZero( &A );
wester committed
486 487 488 489 490 491

    // form a linear system Ax=0: for each selected pair of points m1 & m2,
    // the row of A(=a) represents the coefficients of equation: (m2, 1)'*F*(m1, 1) = 0
    // to save computation time, we compute (At*A) instead of A and then solve (At*A)x=0.
    for( i = 0; i < count; i++ )
    {
wester committed
492 493 494 495 496 497 498 499
        double x0 = (m1[i].x - m0c.x)*scale0;
        double y0 = (m1[i].y - m0c.y)*scale0;
        double x1 = (m2[i].x - m1c.x)*scale1;
        double y1 = (m2[i].y - m1c.y)*scale1;
        double r[9] = { x1*x0, x1*y0, x1, y1*x0, y1*y0, y1, x0, y0, 1 };
        for( j = 0; j < 9; j++ )
            for( k = 0; k < 9; k++ )
                a[j*9+k] += r[j]*r[k];
wester committed
500 501
    }

wester committed
502
    cvEigenVV(&A, &V, &W);
wester committed
503 504 505

    for( i = 0; i < 9; i++ )
    {
wester committed
506
        if( fabs(w[i]) < DBL_EPSILON )
wester committed
507 508 509 510 511 512
            break;
    }

    if( i < 8 )
        return 0;

wester committed
513
    F0 = cvMat( 3, 3, CV_64F, v + 9*8 ); // take the last column of v as a solution of Af = 0
wester committed
514 515 516 517

    // make F0 singular (of rank 2) by decomposing it with SVD,
    // zeroing the last diagonal element of W and then composing the matrices back.

wester committed
518 519 520 521 522 523
    // use v as a temporary storage for different 3x3 matrices
    W = U = V = TF = F0;
    W.data.db = v;
    U.data.db = v + 9;
    V.data.db = v + 18;
    TF.data.db = v + 27;
wester committed
524

wester committed
525 526
    cvSVD( &F0, &W, &U, &V, CV_SVD_MODIFY_A + CV_SVD_U_T + CV_SVD_V_T );
    W.data.db[8] = 0.;
wester committed
527

wester committed
528 529 530
    // F0 <- U*diag([W(1), W(2), 0])*V'
    cvGEMM( &U, &W, 1., 0, 0., &TF, CV_GEMM_A_T );
    cvGEMM( &TF, &V, 1., 0, 0., &F0, 0/*CV_GEMM_B_T*/ );
wester committed
531 532 533

    // apply the transformation that is inverse
    // to what we used to normalize the point coordinates
wester committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    {
        double tt0[] = { scale0, 0, -scale0*m0c.x, 0, scale0, -scale0*m0c.y, 0, 0, 1 };
        double tt1[] = { scale1, 0, -scale1*m1c.x, 0, scale1, -scale1*m1c.y, 0, 0, 1 };
        CvMat T0, T1;
        T0 = T1 = F0;
        T0.data.db = tt0;
        T1.data.db = tt1;

        // F0 <- T1'*F0*T0
        cvGEMM( &T1, &F0, 1., 0, 0., &TF, CV_GEMM_A_T );
        F0.data.db = fmatrix;
        cvGEMM( &TF, &T0, 1., 0, 0., &F0, 0 );

        // make F(3,3) = 1
        if( fabs(F0.data.db[8]) > FLT_EPSILON )
            cvScale( &F0, &F0, 1./F0.data.db[8] );
    }
wester committed
551 552 553 554 555

    return 1;
}


wester committed
556 557
void CvFMEstimator::computeReprojError( const CvMat* _m1, const CvMat* _m2,
                                        const CvMat* model, CvMat* _err )
wester committed
558
{
wester committed
559 560 561 562 563
    int i, count = _m1->rows*_m1->cols;
    const CvPoint2D64f* m1 = (const CvPoint2D64f*)_m1->data.ptr;
    const CvPoint2D64f* m2 = (const CvPoint2D64f*)_m2->data.ptr;
    const double* F = model->data.db;
    float* err = _err->data.fl;
wester committed
564

wester committed
565
    for( i = 0; i < count; i++ )
wester committed
566
    {
wester committed
567
        double a, b, c, d1, d2, s1, s2;
wester committed
568

wester committed
569 570 571
        a = F[0]*m1[i].x + F[1]*m1[i].y + F[2];
        b = F[3]*m1[i].x + F[4]*m1[i].y + F[5];
        c = F[6]*m1[i].x + F[7]*m1[i].y + F[8];
wester committed
572

wester committed
573 574
        s2 = 1./(a*a + b*b);
        d2 = m2[i].x*a + m2[i].y*b + c;
wester committed
575

wester committed
576 577 578
        a = F[0]*m2[i].x + F[3]*m2[i].y + F[6];
        b = F[1]*m2[i].x + F[4]*m2[i].y + F[7];
        c = F[2]*m2[i].x + F[5]*m2[i].y + F[8];
wester committed
579

wester committed
580 581
        s1 = 1./(a*a + b*b);
        d1 = m1[i].x*a + m1[i].y*b + c;
wester committed
582

wester committed
583
        err[i] = (float)std::max(d1*d1*s1, d2*d2*s2);
wester committed
584 585 586
    }
}

wester committed
587 588 589 590

CV_IMPL int cvFindFundamentalMat( const CvMat* points1, const CvMat* points2,
                                  CvMat* fmatrix, int method,
                                  double param1, double param2, CvMat* mask )
wester committed
591
{
wester committed
592 593
    int result = 0;
    Ptr<CvMat> m1, m2, tempMask;
wester committed
594

wester committed
595 596 597 598 599 600 601
    double F[3*9];
    CvMat _F3x3 = cvMat( 3, 3, CV_64FC1, F ), _F9x3 = cvMat( 9, 3, CV_64FC1, F );
    int count;

    CV_Assert( CV_IS_MAT(points1) && CV_IS_MAT(points2) && CV_ARE_SIZES_EQ(points1, points2) );
    CV_Assert( CV_IS_MAT(fmatrix) && fmatrix->cols == 3 &&
        (fmatrix->rows == 3 || (fmatrix->rows == 9 && method == CV_FM_7POINT)) );
wester committed
602

wester committed
603 604 605
    count = MAX(points1->cols, points1->rows);
    if( count < 7 )
        return 0;
wester committed
606

wester committed
607 608
    m1 = cvCreateMat( 1, count, CV_64FC2 );
    cvConvertPointsHomogeneous( points1, m1 );
wester committed
609

wester committed
610 611
    m2 = cvCreateMat( 1, count, CV_64FC2 );
    cvConvertPointsHomogeneous( points2, m2 );
wester committed
612

wester committed
613
    if( mask )
wester committed
614
    {
wester committed
615 616 617
        CV_Assert( CV_IS_MASK_ARR(mask) && CV_IS_MAT_CONT(mask->type) &&
            (mask->rows == 1 || mask->cols == 1) &&
            mask->rows*mask->cols == count );
wester committed
618
    }
wester committed
619 620 621 622 623 624 625 626 627 628
    if( mask || count >= 8 )
        tempMask = cvCreateMat( 1, count, CV_8U );
    if( !tempMask.empty() )
        cvSet( tempMask, cvScalarAll(1.) );

    CvFMEstimator estimator(7);
    if( count == 7 )
        result = estimator.run7Point(m1, m2, &_F9x3);
    else if( method == CV_FM_8POINT )
        result = estimator.run8Point(m1, m2, &_F3x3);
wester committed
629 630 631 632 633 634 635
    else
    {
        if( param1 <= 0 )
            param1 = 3;
        if( param2 < DBL_EPSILON || param2 > 1 - DBL_EPSILON )
            param2 = 0.99;

wester committed
636 637
        if( (method & ~3) == CV_RANSAC && count >= 15 )
            result = estimator.runRANSAC(m1, m2, &_F3x3, tempMask, param1, param2 );
wester committed
638
        else
wester committed
639 640 641 642 643 644 645 646
            result = estimator.runLMeDS(m1, m2, &_F3x3, tempMask, param2 );
        if( result <= 0 )
            return 0;
        /*icvCompressPoints( (CvPoint2D64f*)m1->data.ptr, tempMask->data.ptr, 1, count );
        count = icvCompressPoints( (CvPoint2D64f*)m2->data.ptr, tempMask->data.ptr, 1, count );
        assert( count >= 8 );
        m1->cols = m2->cols = count;
        estimator.run8Point(m1, m2, &_F3x3);*/
wester committed
647 648
    }

wester committed
649 650
    if( result )
        cvConvert( fmatrix->rows == 3 ? &_F3x3 : &_F9x3, fmatrix );
wester committed
651

wester committed
652 653 654 655 656 657 658
    if( mask && tempMask )
    {
        if( CV_ARE_SIZES_EQ(mask, tempMask) )
            cvCopy( tempMask, mask );
        else
            cvTranspose( tempMask, mask );
    }
wester committed
659

wester committed
660
    return result;
wester committed
661 662 663
}


wester committed
664 665
CV_IMPL void cvComputeCorrespondEpilines( const CvMat* points, int pointImageID,
                                          const CvMat* fmatrix, CvMat* lines )
wester committed
666
{
wester committed
667 668 669 670 671
    int abc_stride, abc_plane_stride, abc_elem_size;
    int plane_stride, stride, elem_size;
    int i, dims, count, depth, cn, abc_dims, abc_count, abc_depth, abc_cn;
    uchar *ap, *bp, *cp;
    const uchar *xp, *yp, *zp;
a  
Kai Westerkamp committed
672
    double f[9];
wester committed
673
    CvMat F = cvMat( 3, 3, CV_64F, f );
wester committed
674

wester committed
675 676
    if( !CV_IS_MAT(points) )
        CV_Error( !points ? CV_StsNullPtr : CV_StsBadArg, "points parameter is not a valid matrix" );
wester committed
677

wester committed
678 679 680 681 682 683
    depth = CV_MAT_DEPTH(points->type);
    cn = CV_MAT_CN(points->type);
    if( (depth != CV_32F && depth != CV_64F) || (cn != 1 && cn != 2 && cn != 3) )
        CV_Error( CV_StsUnsupportedFormat, "The format of point matrix is unsupported" );

    if( cn > 1 )
wester committed
684
    {
wester committed
685 686 687
        dims = cn;
        CV_Assert( points->rows == 1 || points->cols == 1 );
        count = points->rows * points->cols;
wester committed
688
    }
wester committed
689 690 691 692 693 694
    else if( points->rows > points->cols )
    {
        dims = cn*points->cols;
        count = points->rows;
    }
    else
wester committed
695
    {
wester committed
696 697 698 699
        if( (points->rows > 1 && cn > 1) || (points->rows == 1 && cn == 1) )
            CV_Error( CV_StsBadSize, "The point matrix does not have a proper layout (2xn, 3xn, nx2 or nx3)" );
        dims = points->rows;
        count = points->cols;
wester committed
700 701
    }

wester committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    if( dims != 2 && dims != 3 )
        CV_Error( CV_StsOutOfRange, "The dimensionality of points must be 2 or 3" );

    if( !CV_IS_MAT(fmatrix) )
        CV_Error( !fmatrix ? CV_StsNullPtr : CV_StsBadArg, "fmatrix is not a valid matrix" );

    if( CV_MAT_TYPE(fmatrix->type) != CV_32FC1 && CV_MAT_TYPE(fmatrix->type) != CV_64FC1 )
        CV_Error( CV_StsUnsupportedFormat, "fundamental matrix must have 32fC1 or 64fC1 type" );

    if( fmatrix->cols != 3 || fmatrix->rows != 3 )
        CV_Error( CV_StsBadSize, "fundamental matrix must be 3x3" );

    if( !CV_IS_MAT(lines) )
        CV_Error( !lines ? CV_StsNullPtr : CV_StsBadArg, "lines parameter is not a valid matrix" );

    abc_depth = CV_MAT_DEPTH(lines->type);
    abc_cn = CV_MAT_CN(lines->type);
    if( (abc_depth != CV_32F && abc_depth != CV_64F) || (abc_cn != 1 && abc_cn != 3) )
        CV_Error( CV_StsUnsupportedFormat, "The format of the matrix of lines is unsupported" );

    if( abc_cn > 1 )
wester committed
723
    {
wester committed
724 725 726 727 728 729 730 731
        abc_dims = abc_cn;
        CV_Assert( lines->rows == 1 || lines->cols == 1 );
        abc_count = lines->rows * lines->cols;
    }
    else if( lines->rows > lines->cols )
    {
        abc_dims = abc_cn*lines->cols;
        abc_count = lines->rows;
wester committed
732 733 734
    }
    else
    {
wester committed
735 736 737 738
        if( (lines->rows > 1 && abc_cn > 1) || (lines->rows == 1 && abc_cn == 1) )
            CV_Error( CV_StsBadSize, "The lines matrix does not have a proper layout (3xn or nx3)" );
        abc_dims = lines->rows;
        abc_count = lines->cols;
wester committed
739 740
    }

wester committed
741 742 743 744 745 746 747 748 749 750
    if( abc_dims != 3 )
        CV_Error( CV_StsOutOfRange, "The lines matrix does not have a proper layout (3xn or nx3)" );

    if( abc_count != count )
        CV_Error( CV_StsUnmatchedSizes, "The numbers of points and lines are different" );

    elem_size = CV_ELEM_SIZE(depth);
    abc_elem_size = CV_ELEM_SIZE(abc_depth);

    if( cn == 1 && points->rows == dims )
wester committed
751
    {
wester committed
752 753
        plane_stride = points->step;
        stride = elem_size;
wester committed
754
    }
wester committed
755
    else
wester committed
756
    {
wester committed
757 758
        plane_stride = elem_size;
        stride = points->rows == 1 ? dims*elem_size : points->step;
wester committed
759 760
    }

wester committed
761
    if( abc_cn == 1 && lines->rows == 3 )
wester committed
762
    {
wester committed
763 764
        abc_plane_stride = lines->step;
        abc_stride = abc_elem_size;
wester committed
765
    }
wester committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    else
    {
        abc_plane_stride = abc_elem_size;
        abc_stride = lines->rows == 1 ? 3*abc_elem_size : lines->step;
    }

    cvConvert( fmatrix, &F );
    if( pointImageID == 2 )
        cvTranspose( &F, &F );

    xp = points->data.ptr;
    yp = xp + plane_stride;
    zp = dims == 3 ? yp + plane_stride : 0;

    ap = lines->data.ptr;
    bp = ap + abc_plane_stride;
    cp = bp + abc_plane_stride;

    for( i = 0; i < count; i++ )
wester committed
785
    {
wester committed
786 787 788 789
        double x, y, z = 1.;
        double a, b, c, nu;

        if( depth == CV_32F )
wester committed
790
        {
wester committed
791 792 793
            x = *(float*)xp; y = *(float*)yp;
            if( zp )
                z = *(float*)zp, zp += stride;
wester committed
794 795 796
        }
        else
        {
wester committed
797 798 799
            x = *(double*)xp; y = *(double*)yp;
            if( zp )
                z = *(double*)zp, zp += stride;
wester committed
800
        }
wester committed
801 802 803 804 805 806 807 808 809 810 811

        xp += stride; yp += stride;

        a = f[0]*x + f[1]*y + f[2]*z;
        b = f[3]*x + f[4]*y + f[5]*z;
        c = f[6]*x + f[7]*y + f[8]*z;
        nu = a*a + b*b;
        nu = nu ? 1./sqrt(nu) : 1.;
        a *= nu; b *= nu; c *= nu;

        if( abc_depth == CV_32F )
wester committed
812
        {
wester committed
813 814 815
            *(float*)ap = (float)a;
            *(float*)bp = (float)b;
            *(float*)cp = (float)c;
wester committed
816 817 818
        }
        else
        {
wester committed
819 820 821
            *(double*)ap = a;
            *(double*)bp = b;
            *(double*)cp = c;
wester committed
822
        }
wester committed
823 824 825 826

        ap += abc_stride;
        bp += abc_stride;
        cp += abc_stride;
wester committed
827 828 829 830
    }
}


wester committed
831
CV_IMPL void cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst )
wester committed
832
{
wester committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    Ptr<CvMat> temp, denom;

    int i, s_count, s_dims, d_count, d_dims;
    CvMat _src, _dst, _ones;
    CvMat* ones = 0;

    if( !CV_IS_MAT(src) )
        CV_Error( !src ? CV_StsNullPtr : CV_StsBadArg,
        "The input parameter is not a valid matrix" );

    if( !CV_IS_MAT(dst) )
        CV_Error( !dst ? CV_StsNullPtr : CV_StsBadArg,
        "The output parameter is not a valid matrix" );

    if( src == dst || src->data.ptr == dst->data.ptr )
wester committed
848
    {
wester committed
849 850 851
        if( src != dst && (!CV_ARE_TYPES_EQ(src, dst) || !CV_ARE_SIZES_EQ(src,dst)) )
            CV_Error( CV_StsBadArg, "Invalid inplace operation" );
        return;
wester committed
852 853
    }

wester committed
854
    if( src->rows > src->cols )
wester committed
855
    {
wester committed
856 857 858 859 860
        if( !((src->cols > 1) ^ (CV_MAT_CN(src->type) > 1)) )
            CV_Error( CV_StsBadSize, "Either the number of channels or columns or rows must be =1" );

        s_dims = CV_MAT_CN(src->type)*src->cols;
        s_count = src->rows;
wester committed
861
    }
wester committed
862 863 864 865
    else
    {
        if( !((src->rows > 1) ^ (CV_MAT_CN(src->type) > 1)) )
            CV_Error( CV_StsBadSize, "Either the number of channels or columns or rows must be =1" );
wester committed
866

wester committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        s_dims = CV_MAT_CN(src->type)*src->rows;
        s_count = src->cols;
    }

    if( src->rows == 1 || src->cols == 1 )
        src = cvReshape( src, &_src, 1, s_count );

    if( dst->rows > dst->cols )
    {
        if( !((dst->cols > 1) ^ (CV_MAT_CN(dst->type) > 1)) )
            CV_Error( CV_StsBadSize,
            "Either the number of channels or columns or rows in the input matrix must be =1" );

        d_dims = CV_MAT_CN(dst->type)*dst->cols;
        d_count = dst->rows;
    }
    else
wester committed
884
    {
wester committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
        if( !((dst->rows > 1) ^ (CV_MAT_CN(dst->type) > 1)) )
            CV_Error( CV_StsBadSize,
            "Either the number of channels or columns or rows in the output matrix must be =1" );

        d_dims = CV_MAT_CN(dst->type)*dst->rows;
        d_count = dst->cols;
    }

    if( dst->rows == 1 || dst->cols == 1 )
        dst = cvReshape( dst, &_dst, 1, d_count );

    if( s_count != d_count )
        CV_Error( CV_StsUnmatchedSizes, "Both matrices must have the same number of points" );

    if( CV_MAT_DEPTH(src->type) < CV_32F || CV_MAT_DEPTH(dst->type) < CV_32F )
        CV_Error( CV_StsUnsupportedFormat,
        "Both matrices must be floating-point (single or double precision)" );

    if( s_dims < 2 || s_dims > 4 || d_dims < 2 || d_dims > 4 )
        CV_Error( CV_StsOutOfRange,
        "Both input and output point dimensionality must be 2, 3 or 4" );

    if( s_dims < d_dims - 1 || s_dims > d_dims + 1 )
        CV_Error( CV_StsUnmatchedSizes,
        "The dimensionalities of input and output point sets differ too much" );

    if( s_dims == d_dims - 1 )
    {
        if( d_count == dst->rows )
wester committed
914
        {
wester committed
915 916
            ones = cvGetSubRect( dst, &_ones, cvRect( s_dims, 0, 1, d_count ));
            dst = cvGetSubRect( dst, &_dst, cvRect( 0, 0, s_dims, d_count ));
wester committed
917 918 919
        }
        else
        {
wester committed
920 921
            ones = cvGetSubRect( dst, &_ones, cvRect( 0, s_dims, d_count, 1 ));
            dst = cvGetSubRect( dst, &_dst, cvRect( 0, 0, d_count, s_dims ));
wester committed
922 923
        }
    }
wester committed
924 925

    if( s_dims <= d_dims )
wester committed
926
    {
wester committed
927
        if( src->rows == dst->rows && src->cols == dst->cols )
wester committed
928
        {
wester committed
929 930 931 932
            if( CV_ARE_TYPES_EQ( src, dst ) )
                cvCopy( src, dst );
            else
                cvConvert( src, dst );
wester committed
933 934 935
        }
        else
        {
wester committed
936 937 938 939 940 941 942
            if( !CV_ARE_TYPES_EQ( src, dst ))
            {
                temp = cvCreateMat( src->rows, src->cols, dst->type );
                cvConvert( src, temp );
                src = temp;
            }
            cvTranspose( src, dst );
wester committed
943
        }
wester committed
944 945 946

        if( ones )
            cvSet( ones, cvRealScalar(1.) );
wester committed
947
    }
wester committed
948
    else
wester committed
949
    {
wester committed
950 951 952
        int s_plane_stride, s_stride, d_plane_stride, d_stride, elem_size;

        if( !CV_ARE_TYPES_EQ( src, dst ))
wester committed
953
        {
wester committed
954 955 956
            temp = cvCreateMat( src->rows, src->cols, dst->type );
            cvConvert( src, temp );
            src = temp;
wester committed
957
        }
wester committed
958 959 960 961 962 963 964 965 966 967

        elem_size = CV_ELEM_SIZE(src->type);

        if( s_count == src->cols )
            s_plane_stride = src->step / elem_size, s_stride = 1;
        else
            s_stride = src->step / elem_size, s_plane_stride = 1;

        if( d_count == dst->cols )
            d_plane_stride = dst->step / elem_size, d_stride = 1;
wester committed
968
        else
wester committed
969 970 971 972 973
            d_stride = dst->step / elem_size, d_plane_stride = 1;

        denom = cvCreateMat( 1, d_count, dst->type );

        if( CV_MAT_DEPTH(dst->type) == CV_32F )
wester committed
974
        {
wester committed
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 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 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
            const float* xs = src->data.fl;
            const float* ys = xs + s_plane_stride;
            const float* zs = 0;
            const float* ws = xs + (s_dims - 1)*s_plane_stride;

            float* iw = denom->data.fl;

            float* xd = dst->data.fl;
            float* yd = xd + d_plane_stride;
            float* zd = 0;

            if( d_dims == 3 )
            {
                zs = ys + s_plane_stride;
                zd = yd + d_plane_stride;
            }

            for( i = 0; i < d_count; i++, ws += s_stride )
            {
                float t = *ws;
                iw[i] = fabs((double)t) > FLT_EPSILON ? t : 1.f;
            }

            cvDiv( 0, denom, denom );

            if( d_dims == 3 )
                for( i = 0; i < d_count; i++ )
                {
                    float w = iw[i];
                    float x = *xs * w, y = *ys * w, z = *zs * w;
                    xs += s_stride; ys += s_stride; zs += s_stride;
                    *xd = x; *yd = y; *zd = z;
                    xd += d_stride; yd += d_stride; zd += d_stride;
                }
            else
                for( i = 0; i < d_count; i++ )
                {
                    float w = iw[i];
                    float x = *xs * w, y = *ys * w;
                    xs += s_stride; ys += s_stride;
                    *xd = x; *yd = y;
                    xd += d_stride; yd += d_stride;
                }
        }
        else
        {
            const double* xs = src->data.db;
            const double* ys = xs + s_plane_stride;
            const double* zs = 0;
            const double* ws = xs + (s_dims - 1)*s_plane_stride;

            double* iw = denom->data.db;

            double* xd = dst->data.db;
            double* yd = xd + d_plane_stride;
            double* zd = 0;

            if( d_dims == 3 )
            {
                zs = ys + s_plane_stride;
                zd = yd + d_plane_stride;
            }

            for( i = 0; i < d_count; i++, ws += s_stride )
            {
                double t = *ws;
                iw[i] = fabs(t) > DBL_EPSILON ? t : 1.;
            }

            cvDiv( 0, denom, denom );

            if( d_dims == 3 )
                for( i = 0; i < d_count; i++ )
                {
                    double w = iw[i];
                    double x = *xs * w, y = *ys * w, z = *zs * w;
                    xs += s_stride; ys += s_stride; zs += s_stride;
                    *xd = x; *yd = y; *zd = z;
                    xd += d_stride; yd += d_stride; zd += d_stride;
                }
            else
                for( i = 0; i < d_count; i++ )
                {
                    double w = iw[i];
                    double x = *xs * w, y = *ys * w;
                    xs += s_stride; ys += s_stride;
                    *xd = x; *yd = y;
                    xd += d_stride; yd += d_stride;
                }
wester committed
1064 1065 1066 1067
        }
    }
}

wester committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
cv::Mat cv::findHomography( InputArray _points1, InputArray _points2,
                            int method, double ransacReprojThreshold, OutputArray _mask )
{
    Mat points1 = _points1.getMat(), points2 = _points2.getMat();
    int npoints = points1.checkVector(2);
    CV_Assert( npoints >= 0 && points2.checkVector(2) == npoints &&
               points1.type() == points2.type());

    Mat H(3, 3, CV_64F);
    CvMat _pt1 = points1, _pt2 = points2;
    CvMat matH = H, c_mask, *p_mask = 0;
    if( _mask.needed() )
    {
        _mask.create(npoints, 1, CV_8U, -1, true);
        p_mask = &(c_mask = _mask.getMat());
    }
    bool ok = cvFindHomography( &_pt1, &_pt2, &matH, method, ransacReprojThreshold, p_mask ) > 0;
    if( !ok )
        H = Scalar(0);
    return H;
}
wester committed
1089

wester committed
1090 1091
cv::Mat cv::findHomography( InputArray _points1, InputArray _points2,
                            OutputArray _mask, int method, double ransacReprojThreshold )
wester committed
1092
{
wester committed
1093 1094
    return cv::findHomography(_points1, _points2, method, ransacReprojThreshold, _mask);
}
wester committed
1095

wester committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
cv::Mat cv::findFundamentalMat( InputArray _points1, InputArray _points2,
                               int method, double param1, double param2,
                               OutputArray _mask )
{
    Mat points1 = _points1.getMat(), points2 = _points2.getMat();
    int npoints = points1.checkVector(2);
    CV_Assert( npoints >= 0 && points2.checkVector(2) == npoints &&
              points1.type() == points2.type());

    Mat F(method == CV_FM_7POINT ? 9 : 3, 3, CV_64F);
    CvMat _pt1 = points1, _pt2 = points2;
    CvMat matF = F, c_mask, *p_mask = 0;
    if( _mask.needed() )
    {
        _mask.create(npoints, 1, CV_8U, -1, true);
        p_mask = &(c_mask = _mask.getMat());
    }
    int n = cvFindFundamentalMat( &_pt1, &_pt2, &matF, method, param1, param2, p_mask );
    if( n <= 0 )
        F = Scalar(0);
    if( n == 1 )
        F = F.rowRange(0, 3);
    return F;
wester committed
1119 1120
}

wester committed
1121 1122 1123 1124 1125
cv::Mat cv::findFundamentalMat( InputArray _points1, InputArray _points2,
                                OutputArray _mask, int method, double param1, double param2 )
{
    return cv::findFundamentalMat(_points1, _points2, method, param1, param2, _mask);
}
wester committed
1126 1127


wester committed
1128 1129 1130 1131 1132 1133 1134 1135
void cv::computeCorrespondEpilines( InputArray _points, int whichImage,
                                    InputArray _Fmat, OutputArray _lines )
{
    Mat points = _points.getMat(), F = _Fmat.getMat();
    int npoints = points.checkVector(2);
    if( npoints < 0 )
        npoints = points.checkVector(3);
    CV_Assert( npoints >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S));
wester committed
1136

wester committed
1137 1138 1139 1140
    _lines.create(npoints, 1, CV_32FC3, -1, true);
    CvMat c_points = points, c_lines = _lines.getMat(), c_F = F;
    cvComputeCorrespondEpilines(&c_points, whichImage, &c_F, &c_lines);
}
wester committed
1141

wester committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
void cv::convertPointsFromHomogeneous( InputArray _src, OutputArray _dst )
{
    Mat src = _src.getMat();
    int npoints = src.checkVector(3), cn = 3;
    if( npoints < 0 )
    {
        npoints = src.checkVector(4);
        if( npoints >= 0 )
            cn = 4;
    }
    CV_Assert( npoints >= 0 && (src.depth() == CV_32F || src.depth() == CV_32S));
wester committed
1153

wester committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    _dst.create(npoints, 1, CV_MAKETYPE(CV_32F, cn-1));
    CvMat c_src = src, c_dst = _dst.getMat();
    cvConvertPointsHomogeneous(&c_src, &c_dst);
}

void cv::convertPointsToHomogeneous( InputArray _src, OutputArray _dst )
{
    Mat src = _src.getMat();
    int npoints = src.checkVector(2), cn = 2;
    if( npoints < 0 )
    {
        npoints = src.checkVector(3);
        if( npoints >= 0 )
            cn = 3;
    }
    CV_Assert( npoints >= 0 && (src.depth() == CV_32F || src.depth() == CV_32S));

    _dst.create(npoints, 1, CV_MAKETYPE(CV_32F, cn+1));
    CvMat c_src = src, c_dst = _dst.getMat();
    cvConvertPointsHomogeneous(&c_src, &c_dst);
}

void cv::convertPointsHomogeneous( InputArray _src, OutputArray _dst )
{
    int stype = _src.type(), dtype = _dst.type();
    CV_Assert( _dst.fixedType() );

    if( CV_MAT_CN(stype) > CV_MAT_CN(dtype) )
        convertPointsFromHomogeneous(_src, _dst);
    else
        convertPointsToHomogeneous(_src, _dst);
wester committed
1185 1186 1187
}

/* End of file. */