1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
43 #include "_cvmodelest.h"
51 CvModelEstimator2::CvModelEstimator2(int _modelPoints, CvSize _modelSize, int _maxBasicSolutions)
53 modelPoints = _modelPoints;
54 modelSize = _modelSize;
55 maxBasicSolutions = _maxBasicSolutions;
56 checkPartialSubsets = true;
60 CvModelEstimator2::~CvModelEstimator2()
64 void CvModelEstimator2::setSeed( int64 seed )
70 int CvModelEstimator2::findInliers( const CvMat* m1, const CvMat* m2,
71 const CvMat* model, CvMat* _err,
72 CvMat* _mask, double threshold )
74 int i, count = _err->rows*_err->cols, goodCount = 0;
75 const float* err = _err->data.fl;
76 uchar* mask = _mask->data.ptr;
78 computeReprojError( m1, m2, model, _err );
79 threshold *= threshold;
80 for( i = 0; i < count; i++ )
81 goodCount += mask[i] = err[i] <= threshold;
87 cvRANSACUpdateNumIters( double p, double ep,
88 int model_points, int max_iters )
90 if( model_points <= 0 )
91 CV_Error( CV_StsOutOfRange, "the number of model points should be positive" );
98 // avoid inf's & nan's
99 double num = MAX(1. - p, DBL_MIN);
100 double denom = 1. - pow(1. - ep,model_points);
101 if( denom < DBL_MIN )
107 return denom >= 0 || -num >= max_iters*(-denom) ?
108 max_iters : cvRound(num/denom);
111 bool CvModelEstimator2::runRANSAC( const CvMat* m1, const CvMat* m2, CvMat* model,
112 CvMat* mask0, double reprojThreshold,
113 double confidence, int maxIters )
116 cv::Ptr<CvMat> mask = cvCloneMat(mask0);
117 cv::Ptr<CvMat> models, err, tmask;
118 cv::Ptr<CvMat> ms1, ms2;
120 int iter, niters = maxIters;
121 int count = m1->rows*m1->cols, maxGoodCount = 0;
122 CV_Assert( CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask) );
124 if( count < modelPoints )
127 models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
128 err = cvCreateMat( 1, count, CV_32FC1 );
129 tmask = cvCreateMat( 1, count, CV_8UC1 );
131 if( count > modelPoints )
133 ms1 = cvCreateMat( 1, modelPoints, m1->type );
134 ms2 = cvCreateMat( 1, modelPoints, m2->type );
139 ms1 = cvCloneMat(m1);
140 ms2 = cvCloneMat(m2);
143 for( iter = 0; iter < niters; iter++ )
145 int i, goodCount, nmodels;
146 if( count > modelPoints )
148 bool found = getSubset( m1, m2, ms1, ms2, 300 );
157 nmodels = runKernel( ms1, ms2, models );
160 for( i = 0; i < nmodels; i++ )
163 cvGetRows( models, &model_i, i*modelSize.height, (i+1)*modelSize.height );
164 goodCount = findInliers( m1, m2, &model_i, err, tmask, reprojThreshold );
166 if( goodCount > MAX(maxGoodCount, modelPoints-1) )
168 std::swap(tmask, mask);
169 cvCopy( &model_i, model );
170 maxGoodCount = goodCount;
171 niters = cvRANSACUpdateNumIters( confidence,
172 (double)(count - goodCount)/count, modelPoints, niters );
177 if( maxGoodCount > 0 )
180 cvCopy( mask, mask0 );
188 static CV_IMPLEMENT_QSORT( icvSortDistances, int, CV_LT )
190 bool CvModelEstimator2::runLMeDS( const CvMat* m1, const CvMat* m2, CvMat* model,
191 CvMat* mask, double confidence, int maxIters )
193 const double outlierRatio = 0.45;
195 cv::Ptr<CvMat> models;
196 cv::Ptr<CvMat> ms1, ms2;
199 int iter, niters = maxIters;
200 int count = m1->rows*m1->cols;
201 double minMedian = DBL_MAX, sigma;
203 CV_Assert( CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask) );
205 if( count < modelPoints )
208 models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
209 err = cvCreateMat( 1, count, CV_32FC1 );
211 if( count > modelPoints )
213 ms1 = cvCreateMat( 1, modelPoints, m1->type );
214 ms2 = cvCreateMat( 1, modelPoints, m2->type );
219 ms1 = cvCloneMat(m1);
220 ms2 = cvCloneMat(m2);
223 niters = cvRound(log(1-confidence)/log(1-pow(1-outlierRatio,(double)modelPoints)));
224 niters = MIN( MAX(niters, 3), maxIters );
226 for( iter = 0; iter < niters; iter++ )
229 if( count > modelPoints )
231 bool found = getSubset( m1, m2, ms1, ms2, 300 );
240 nmodels = runKernel( ms1, ms2, models );
243 for( i = 0; i < nmodels; i++ )
246 cvGetRows( models, &model_i, i*modelSize.height, (i+1)*modelSize.height );
247 computeReprojError( m1, m2, &model_i, err );
248 icvSortDistances( err->data.i, count, 0 );
250 double median = count % 2 != 0 ?
251 err->data.fl[count/2] : (err->data.fl[count/2-1] + err->data.fl[count/2])*0.5;
253 if( median < minMedian )
256 cvCopy( &model_i, model );
261 if( minMedian < DBL_MAX )
263 sigma = 2.5*1.4826*(1 + 5./(count - modelPoints))*sqrt(minMedian);
264 sigma = MAX( sigma, FLT_EPSILON*100 );
266 count = findInliers( m1, m2, model, err, mask, sigma );
267 result = count >= modelPoints;
274 bool CvModelEstimator2::getSubset( const CvMat* m1, const CvMat* m2,
275 CvMat* ms1, CvMat* ms2, int maxAttempts )
277 int* idx = (int*)cvStackAlloc( modelPoints*sizeof(idx[0]) );
278 int i = 0, j, k, idx_i, iters = 0;
279 int type = CV_MAT_TYPE(m1->type), elemSize = CV_ELEM_SIZE(type);
280 const int *m1ptr = m1->data.i, *m2ptr = m2->data.i;
281 int *ms1ptr = ms1->data.i, *ms2ptr = ms2->data.i;
282 int count = m1->cols*m1->rows;
284 assert( CV_IS_MAT_CONT(m1->type & m2->type) && (elemSize % sizeof(int) == 0) );
285 elemSize /= sizeof(int);
287 for(; iters < maxAttempts; iters++)
289 for( i = 0; i < modelPoints && iters < maxAttempts; )
291 idx[i] = idx_i = cvRandInt(&rng) % count;
292 for( j = 0; j < i; j++ )
293 if( idx_i == idx[j] )
297 for( k = 0; k < elemSize; k++ )
299 ms1ptr[i*elemSize + k] = m1ptr[idx_i*elemSize + k];
300 ms2ptr[i*elemSize + k] = m2ptr[idx_i*elemSize + k];
302 if( checkPartialSubsets && (!checkSubset( ms1, i+1 ) || !checkSubset( ms2, i+1 )))
309 if( !checkPartialSubsets && i == modelPoints &&
310 (!checkSubset( ms1, i ) || !checkSubset( ms2, i )))
315 return i == modelPoints && iters < maxAttempts;
319 bool CvModelEstimator2::checkSubset( const CvMat* m, int count )
322 CvPoint2D64f* ptr = (CvPoint2D64f*)m->data.ptr;
324 assert( CV_MAT_TYPE(m->type) == CV_64FC2 );
326 if( checkPartialSubsets )
329 i0 = 0, i1 = count - 1;
331 for( i = i0; i <= i1; i++ )
333 // check that the i-th selected point does not belong
334 // to a line connecting some previously selected points
335 for( j = 0; j < i; j++ )
337 double dx1 = ptr[j].x - ptr[i].x;
338 double dy1 = ptr[j].y - ptr[i].y;
339 for( k = 0; k < j; k++ )
341 double dx2 = ptr[k].x - ptr[i].x;
342 double dy2 = ptr[k].y - ptr[i].y;
343 if( fabs(dx2*dy1 - dy2*dx1) <= FLT_EPSILON*(fabs(dx1) + fabs(dy1) + fabs(dx2) + fabs(dy2)))
360 class Affine3DEstimator : public CvModelEstimator2
363 Affine3DEstimator() : CvModelEstimator2(4, cvSize(4, 3), 1) {}
364 virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model );
366 virtual void computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error );
367 virtual bool checkSubset( const CvMat* ms1, int count );
372 int cv::Affine3DEstimator::runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )
374 const Point3d* from = reinterpret_cast<const Point3d*>(m1->data.ptr);
375 const Point3d* to = reinterpret_cast<const Point3d*>(m2->data.ptr);
377 Mat A(12, 12, CV_64F);
378 Mat B(12, 1, CV_64F);
381 for(int i = 0; i < modelPoints; ++i)
383 *B.ptr<Point3d>(3*i) = to[i];
385 double *aptr = A.ptr<double>(3*i);
386 for(int k = 0; k < 3; ++k)
389 *reinterpret_cast<Point3d*>(aptr) = from[i];
397 cvReshape(model, &cvX, 1, 12);
398 cvSolve(&cvA, &cvB, &cvX, CV_SVD );
403 void cv::Affine3DEstimator::computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error )
405 int count = m1->rows * m1->cols;
406 const Point3d* from = reinterpret_cast<const Point3d*>(m1->data.ptr);
407 const Point3d* to = reinterpret_cast<const Point3d*>(m2->data.ptr);
408 const double* F = model->data.db;
409 float* err = error->data.fl;
411 for(int i = 0; i < count; i++ )
413 const Point3d& f = from[i];
414 const Point3d& t = to[i];
416 double a = F[0]*f.x + F[1]*f.y + F[ 2]*f.z + F[ 3] - t.x;
417 double b = F[4]*f.x + F[5]*f.y + F[ 6]*f.z + F[ 7] - t.y;
418 double c = F[8]*f.x + F[9]*f.y + F[10]*f.z + F[11] - t.z;
420 err[i] = (float)sqrt(a*a + b*b + c*c);
424 bool cv::Affine3DEstimator::checkSubset( const CvMat* ms1, int count )
426 CV_Assert( CV_MAT_TYPE(ms1->type) == CV_64FC3 );
428 int j, k, i = count - 1;
429 const Point3d* ptr = reinterpret_cast<const Point3d*>(ms1->data.ptr);
431 // check that the i-th selected point does not belong
432 // to a line connecting some previously selected points
434 for(j = 0; j < i; ++j)
436 Point3d d1 = ptr[j] - ptr[i];
437 double n1 = norm(d1);
439 for(k = 0; k < j; ++k)
441 Point3d d2 = ptr[k] - ptr[i];
442 double n = norm(d2) * n1;
444 if (fabs(d1.dot(d2) / n) > 0.996)
454 int cv::estimateAffine3D(const Mat& from, const Mat& to, Mat& out, vector<uchar>& outliers, double param1, double param2)
456 size_t count = from.cols*from.rows*from.channels()/3;
458 CV_Assert( count >= 4 && from.isContinuous() && to.isContinuous() &&
459 from.depth() == CV_32F && to.depth() == CV_32F &&
460 ((from.rows == 1 && from.channels() == 3) || from.cols*from.channels() == 3) &&
461 ((to.rows == 1 && to.channels() == 3) || to.cols*to.channels() == 3) &&
462 count == (size_t)to.cols*to.rows*to.channels()/3);
464 out.create(3, 4, CV_64F);
465 outliers.resize(count);
466 fill(outliers.begin(), outliers.end(), (uchar)1);
468 vector<Point3d> dFrom;
471 copy(from.ptr<Point3f>(), from.ptr<Point3f>() + count, back_inserter(dFrom));
472 copy(to.ptr<Point3f>(), to.ptr<Point3f>() + count, back_inserter(dTo));
475 CvMat mask = cvMat( 1, count, CV_8U, &outliers[0] );
476 CvMat m1 = cvMat( 1, count, CV_64FC3, &dFrom[0] );
477 CvMat m2 = cvMat( 1, count, CV_64FC3, &dTo[0] );
479 const double epsilon = numeric_limits<double>::epsilon();
480 param1 = param1 <= 0 ? 3 : param1;
481 param2 = (param2 < epsilon) ? 0.99 : (param2 > 1 - epsilon) ? 0.99 : param2;
483 return Affine3DEstimator().runRANSAC(&m1,& m2, &F3x4, &mask, param1, param2 );