]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/src/cv/cvmodelest.cpp
fixed output mask in RANSAC (this repairs cvFindHomography & find_obj.cpp)
[opencv.git] / opencv / src / cv / cvmodelest.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
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.
25 //
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.
28 //
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.
39 //
40 //M*/
41
42 #include "_cv.h"
43 #include "_cvmodelest.h"
44 #include <algorithm>
45 #include <iterator>
46 #include <limits>
47
48 using namespace std;
49
50
51 CvModelEstimator2::CvModelEstimator2(int _modelPoints, CvSize _modelSize, int _maxBasicSolutions)
52 {
53     modelPoints = _modelPoints;
54     modelSize = _modelSize;
55     maxBasicSolutions = _maxBasicSolutions;
56     checkPartialSubsets = true;
57     rng = cvRNG(-1);
58 }
59
60 CvModelEstimator2::~CvModelEstimator2()
61 {
62 }
63
64 void CvModelEstimator2::setSeed( int64 seed )
65 {
66     rng = cvRNG(seed);
67 }
68
69
70 int CvModelEstimator2::findInliers( const CvMat* m1, const CvMat* m2,
71                                     const CvMat* model, CvMat* _err,
72                                     CvMat* _mask, double threshold )
73 {
74     int i, count = _err->rows*_err->cols, goodCount = 0;
75     const float* err = _err->data.fl;
76     uchar* mask = _mask->data.ptr;
77
78     computeReprojError( m1, m2, model, _err );
79     threshold *= threshold;
80     for( i = 0; i < count; i++ )
81         goodCount += mask[i] = err[i] <= threshold;
82     return goodCount;
83 }
84
85
86 CV_IMPL int
87 cvRANSACUpdateNumIters( double p, double ep,
88                         int model_points, int max_iters )
89 {
90     if( model_points <= 0 )
91         CV_Error( CV_StsOutOfRange, "the number of model points should be positive" );
92
93     p = MAX(p, 0.);
94     p = MIN(p, 1.);
95     ep = MAX(ep, 0.);
96     ep = MIN(ep, 1.);
97
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 )
102         return 0;
103
104     num = log(num);
105     denom = log(denom);
106     
107     return denom >= 0 || -num >= max_iters*(-denom) ?
108         max_iters : cvRound(num/denom);
109 }
110
111 bool CvModelEstimator2::runRANSAC( const CvMat* m1, const CvMat* m2, CvMat* model,
112                                     CvMat* mask0, double reprojThreshold,
113                                     double confidence, int maxIters )
114 {
115     bool result = false;
116     cv::Ptr<CvMat> mask = cvCloneMat(mask0);
117     cv::Ptr<CvMat> models, err, tmask;
118     cv::Ptr<CvMat> ms1, ms2;
119
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) );
123
124     if( count < modelPoints )
125         return false;
126
127     models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
128     err = cvCreateMat( 1, count, CV_32FC1 );
129     tmask = cvCreateMat( 1, count, CV_8UC1 );
130     
131     if( count > modelPoints )
132     {
133         ms1 = cvCreateMat( 1, modelPoints, m1->type );
134         ms2 = cvCreateMat( 1, modelPoints, m2->type );
135     }
136     else
137     {
138         niters = 1;
139         ms1 = cvCloneMat(m1);
140         ms2 = cvCloneMat(m2);
141     }
142
143     for( iter = 0; iter < niters; iter++ )
144     {
145         int i, goodCount, nmodels;
146         if( count > modelPoints )
147         {
148             bool found = getSubset( m1, m2, ms1, ms2, 300 );
149             if( !found )
150             {
151                 if( iter == 0 )
152                     return false;
153                 break;
154             }
155         }
156
157         nmodels = runKernel( ms1, ms2, models );
158         if( nmodels <= 0 )
159             continue;
160         for( i = 0; i < nmodels; i++ )
161         {
162             CvMat model_i;
163             cvGetRows( models, &model_i, i*modelSize.height, (i+1)*modelSize.height );
164             goodCount = findInliers( m1, m2, &model_i, err, tmask, reprojThreshold );
165
166             if( goodCount > MAX(maxGoodCount, modelPoints-1) )
167             {
168                 std::swap(tmask, mask);
169                 cvCopy( &model_i, model );
170                 maxGoodCount = goodCount;
171                 niters = cvRANSACUpdateNumIters( confidence,
172                     (double)(count - goodCount)/count, modelPoints, niters );
173             }
174         }
175     }
176
177     if( maxGoodCount > 0 )
178     {
179         if( mask != mask0 )
180             cvCopy( mask, mask0 );
181         result = true;
182     }
183
184     return result;
185 }
186
187
188 static CV_IMPLEMENT_QSORT( icvSortDistances, int, CV_LT )
189
190 bool CvModelEstimator2::runLMeDS( const CvMat* m1, const CvMat* m2, CvMat* model,
191                                   CvMat* mask, double confidence, int maxIters )
192 {
193     const double outlierRatio = 0.45;
194     bool result = false;
195     cv::Ptr<CvMat> models;
196     cv::Ptr<CvMat> ms1, ms2;
197     cv::Ptr<CvMat> err;
198
199     int iter, niters = maxIters;
200     int count = m1->rows*m1->cols;
201     double minMedian = DBL_MAX, sigma;
202
203     CV_Assert( CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask) );
204
205     if( count < modelPoints )
206         return false;
207
208     models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
209     err = cvCreateMat( 1, count, CV_32FC1 );
210     
211     if( count > modelPoints )
212     {
213         ms1 = cvCreateMat( 1, modelPoints, m1->type );
214         ms2 = cvCreateMat( 1, modelPoints, m2->type );
215     }
216     else
217     {
218         niters = 1;
219         ms1 = cvCloneMat(m1);
220         ms2 = cvCloneMat(m2);
221     }
222
223     niters = cvRound(log(1-confidence)/log(1-pow(1-outlierRatio,(double)modelPoints)));
224     niters = MIN( MAX(niters, 3), maxIters );
225
226     for( iter = 0; iter < niters; iter++ )
227     {
228         int i, nmodels;
229         if( count > modelPoints )
230         {
231             bool found = getSubset( m1, m2, ms1, ms2, 300 );
232             if( !found )
233             {
234                 if( iter == 0 )
235                     return false;
236                 break;
237             }
238         }
239
240         nmodels = runKernel( ms1, ms2, models );
241         if( nmodels <= 0 )
242             continue;
243         for( i = 0; i < nmodels; i++ )
244         {
245             CvMat model_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 );
249
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;
252
253             if( median < minMedian )
254             {
255                 minMedian = median;
256                 cvCopy( &model_i, model );
257             }
258         }
259     }
260
261     if( minMedian < DBL_MAX )
262     {
263         sigma = 2.5*1.4826*(1 + 5./(count - modelPoints))*sqrt(minMedian);
264         sigma = MAX( sigma, FLT_EPSILON*100 );
265
266         count = findInliers( m1, m2, model, err, mask, sigma );
267         result = count >= modelPoints;
268     }
269
270     return result;
271 }
272
273
274 bool CvModelEstimator2::getSubset( const CvMat* m1, const CvMat* m2,
275                                    CvMat* ms1, CvMat* ms2, int maxAttempts )
276 {
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;
283
284     assert( CV_IS_MAT_CONT(m1->type & m2->type) && (elemSize % sizeof(int) == 0) );
285     elemSize /= sizeof(int);
286
287     for(; iters < maxAttempts; iters++)
288     {
289         for( i = 0; i < modelPoints && iters < maxAttempts; )
290         {
291             idx[i] = idx_i = cvRandInt(&rng) % count;
292             for( j = 0; j < i; j++ )
293                 if( idx_i == idx[j] )
294                     break;
295             if( j < i )
296                 continue;
297             for( k = 0; k < elemSize; k++ )
298             {
299                 ms1ptr[i*elemSize + k] = m1ptr[idx_i*elemSize + k];
300                 ms2ptr[i*elemSize + k] = m2ptr[idx_i*elemSize + k];
301             }
302             if( checkPartialSubsets && (!checkSubset( ms1, i+1 ) || !checkSubset( ms2, i+1 )))
303             {
304                 iters++;
305                 continue;
306             }
307             i++;
308         }
309         if( !checkPartialSubsets && i == modelPoints &&
310             (!checkSubset( ms1, i ) || !checkSubset( ms2, i )))
311             continue;
312         break;
313     }
314
315     return i == modelPoints && iters < maxAttempts;
316 }
317
318
319 bool CvModelEstimator2::checkSubset( const CvMat* m, int count )
320 {
321     int j, k, i, i0, i1;
322     CvPoint2D64f* ptr = (CvPoint2D64f*)m->data.ptr;
323
324     assert( CV_MAT_TYPE(m->type) == CV_64FC2 );
325     
326     if( checkPartialSubsets )
327         i0 = i1 = count - 1;
328     else
329         i0 = 0, i1 = count - 1;
330     
331     for( i = i0; i <= i1; i++ )
332     {
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++ )
336         {
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++ )
340             {
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)))
344                     break;
345             }
346             if( k < j )
347                 break;
348         }
349         if( j < i )
350             break;
351     }
352
353     return i >= i1;
354 }
355
356
357 namespace cv
358 {
359
360 class Affine3DEstimator : public CvModelEstimator2
361 {
362 public:
363     Affine3DEstimator() : CvModelEstimator2(4, cvSize(4, 3), 1) {}
364     virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model );     
365 protected:
366     virtual void computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error );      
367     virtual bool checkSubset( const CvMat* ms1, int count );
368 };
369
370 }
371
372 int cv::Affine3DEstimator::runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )
373 {    
374     const Point3d* from = reinterpret_cast<const Point3d*>(m1->data.ptr);
375     const Point3d* to   = reinterpret_cast<const Point3d*>(m2->data.ptr);
376
377     Mat A(12, 12, CV_64F);
378     Mat B(12, 1, CV_64F);
379     A = Scalar(0.0);
380
381     for(int i = 0; i < modelPoints; ++i)
382     {
383         *B.ptr<Point3d>(3*i) = to[i];
384
385         double *aptr = A.ptr<double>(3*i);
386         for(int k = 0; k < 3; ++k)
387         {
388             aptr[3] = 1.0;
389             *reinterpret_cast<Point3d*>(aptr) = from[i];
390             aptr += 16;
391         }                
392     }
393
394     CvMat cvA = A;
395     CvMat cvB = B;
396     CvMat cvX;
397     cvReshape(model, &cvX, 1, 12);
398     cvSolve(&cvA, &cvB, &cvX, CV_SVD );
399     
400     return 1;
401 }
402
403 void cv::Affine3DEstimator::computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error )
404 {
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;
410     
411     for(int i = 0; i < count; i++ )
412     {
413         const Point3d& f = from[i];
414         const Point3d& t = to[i];
415
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;
419
420         err[i] = (float)sqrt(a*a + b*b + c*c);       
421     }
422 }
423
424 bool cv::Affine3DEstimator::checkSubset( const CvMat* ms1, int count )
425 {
426     CV_Assert( CV_MAT_TYPE(ms1->type) == CV_64FC3 );
427
428     int j, k, i = count - 1;
429     const Point3d* ptr = reinterpret_cast<const Point3d*>(ms1->data.ptr);    
430     
431     // check that the i-th selected point does not belong
432     // to a line connecting some previously selected points
433     
434     for(j = 0; j < i; ++j)
435     {
436         Point3d d1 = ptr[j] - ptr[i];
437         double n1 = norm(d1);
438         
439         for(k = 0; k < j; ++k)
440         {
441             Point3d d2 = ptr[k] - ptr[i];            
442             double n = norm(d2) * n1;
443
444             if (fabs(d1.dot(d2) / n) > 0.996)
445                 break;            
446         }
447         if( k < j )
448             break;
449     }
450
451     return j == i;
452 }
453
454 int cv::estimateAffine3D(const Mat& from, const Mat& to, Mat& out, vector<uchar>& outliers, double param1, double param2)
455 {
456     size_t count = from.cols*from.rows*from.channels()/3;
457     
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);
463
464     out.create(3, 4, CV_64F); 
465     outliers.resize(count);
466     fill(outliers.begin(), outliers.end(), (uchar)1);
467
468     vector<Point3d> dFrom;
469     vector<Point3d> dTo;    
470
471     copy(from.ptr<Point3f>(), from.ptr<Point3f>() + count, back_inserter(dFrom));
472     copy(to.ptr<Point3f>(), to.ptr<Point3f>() + count, back_inserter(dTo));
473     
474     CvMat F3x4 = out;
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] );
478     
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;
482             
483     return Affine3DEstimator().runRANSAC(&m1,& m2, &F3x4, &mask, param1, param2 );    
484 }