mirror of
https://github.com/opencv/opencv.git
synced 2024-11-25 11:40:44 +08:00
rewritten several functions from calib3d: findhomography, findfundamentalmat, findessentialmat, estimateaffine3d, computecorrespondepilines, convert points{to/from}homogeneous to C++.
This commit is contained in:
parent
891d7da6ee
commit
374e3a0890
@ -7,10 +7,11 @@
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
|
||||
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
@ -23,7 +24,7 @@
|
||||
// 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
|
||||
// * The name of the copyright holders 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
|
||||
@ -39,44 +40,27 @@
|
||||
//
|
||||
//M*/
|
||||
|
||||
#include "precomp.hpp"
|
||||
|
||||
#ifndef _CV_MODEL_EST_H_
|
||||
#define _CV_MODEL_EST_H_
|
||||
using namespace cv;
|
||||
|
||||
#include "opencv2/calib3d/calib3d.hpp"
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
class CV_EXPORTS CvModelEstimator2
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#if 0
|
||||
bool cv::initModule_calib3d(void)
|
||||
{
|
||||
public:
|
||||
CvModelEstimator2(int _modelPoints, CvSize _modelSize, int _maxBasicSolutions);
|
||||
virtual ~CvModelEstimator2();
|
||||
|
||||
virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )=0;
|
||||
virtual bool runLMeDS( const CvMat* m1, const CvMat* m2, CvMat* model,
|
||||
CvMat* mask, double confidence=0.99, int maxIters=2000 );
|
||||
virtual bool runRANSAC( const CvMat* m1, const CvMat* m2, CvMat* model,
|
||||
CvMat* mask, double threshold,
|
||||
double confidence=0.99, int maxIters=2000 );
|
||||
virtual bool refine( const CvMat*, const CvMat*, CvMat*, int ) { return true; }
|
||||
virtual void setSeed( int64 seed );
|
||||
|
||||
protected:
|
||||
virtual void computeReprojError( const CvMat* m1, const CvMat* m2,
|
||||
const CvMat* model, CvMat* error ) = 0;
|
||||
virtual int findInliers( const CvMat* m1, const CvMat* m2,
|
||||
const CvMat* model, CvMat* error,
|
||||
CvMat* mask, double threshold );
|
||||
virtual bool getSubset( const CvMat* m1, const CvMat* m2,
|
||||
CvMat* ms1, CvMat* ms2, int maxAttempts=1000 );
|
||||
virtual bool checkSubset( const CvMat* ms1, int count );
|
||||
virtual bool isMinimalSetConsistent( const CvMat* /*m1*/, const CvMat* /*m2*/ ) { return true; };
|
||||
|
||||
CvRNG rng;
|
||||
int modelPoints;
|
||||
CvSize modelSize;
|
||||
int maxBasicSolutions;
|
||||
bool checkPartialSubsets;
|
||||
};
|
||||
|
||||
#endif // _CV_MODEL_EST_H_
|
||||
bool all = true;
|
||||
all &= !RANSACPointSetRegistrator_info_auto.name().empty();
|
||||
all &= !LMeDSPointSetRegistrator_info_auto.name().empty();
|
||||
all &= !LMSolverImpl_info_auto.name().empty();
|
||||
|
||||
return all;
|
||||
}
|
||||
#endif
|
@ -55,247 +55,6 @@
|
||||
|
||||
using namespace cv;
|
||||
|
||||
CvLevMarq::CvLevMarq()
|
||||
{
|
||||
mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr<CvMat>();
|
||||
lambdaLg10 = 0; state = DONE;
|
||||
criteria = cvTermCriteria(0,0,0);
|
||||
iters = 0;
|
||||
completeSymmFlag = false;
|
||||
}
|
||||
|
||||
CvLevMarq::CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria0, bool _completeSymmFlag )
|
||||
{
|
||||
mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr<CvMat>();
|
||||
init(nparams, nerrs, criteria0, _completeSymmFlag);
|
||||
}
|
||||
|
||||
void CvLevMarq::clear()
|
||||
{
|
||||
mask.release();
|
||||
prevParam.release();
|
||||
param.release();
|
||||
J.release();
|
||||
err.release();
|
||||
JtJ.release();
|
||||
JtJN.release();
|
||||
JtErr.release();
|
||||
JtJV.release();
|
||||
JtJW.release();
|
||||
}
|
||||
|
||||
CvLevMarq::~CvLevMarq()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
void CvLevMarq::init( int nparams, int nerrs, CvTermCriteria criteria0, bool _completeSymmFlag )
|
||||
{
|
||||
if( !param || param->rows != nparams || nerrs != (err ? err->rows : 0) )
|
||||
clear();
|
||||
mask = cvCreateMat( nparams, 1, CV_8U );
|
||||
cvSet(mask, cvScalarAll(1));
|
||||
prevParam = cvCreateMat( nparams, 1, CV_64F );
|
||||
param = cvCreateMat( nparams, 1, CV_64F );
|
||||
JtJ = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJN = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJV = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJW = cvCreateMat( nparams, 1, CV_64F );
|
||||
JtErr = cvCreateMat( nparams, 1, CV_64F );
|
||||
if( nerrs > 0 )
|
||||
{
|
||||
J = cvCreateMat( nerrs, nparams, CV_64F );
|
||||
err = cvCreateMat( nerrs, 1, CV_64F );
|
||||
}
|
||||
prevErrNorm = DBL_MAX;
|
||||
lambdaLg10 = -3;
|
||||
criteria = criteria0;
|
||||
if( criteria.type & CV_TERMCRIT_ITER )
|
||||
criteria.max_iter = MIN(MAX(criteria.max_iter,1),1000);
|
||||
else
|
||||
criteria.max_iter = 30;
|
||||
if( criteria.type & CV_TERMCRIT_EPS )
|
||||
criteria.epsilon = MAX(criteria.epsilon, 0);
|
||||
else
|
||||
criteria.epsilon = DBL_EPSILON;
|
||||
state = STARTED;
|
||||
iters = 0;
|
||||
completeSymmFlag = _completeSymmFlag;
|
||||
}
|
||||
|
||||
bool CvLevMarq::update( const CvMat*& _param, CvMat*& matJ, CvMat*& _err )
|
||||
{
|
||||
double change;
|
||||
|
||||
matJ = _err = 0;
|
||||
|
||||
assert( !err.empty() );
|
||||
if( state == DONE )
|
||||
{
|
||||
_param = param;
|
||||
return false;
|
||||
}
|
||||
|
||||
if( state == STARTED )
|
||||
{
|
||||
_param = param;
|
||||
cvZero( J );
|
||||
cvZero( err );
|
||||
matJ = J;
|
||||
_err = err;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
if( state == CALC_J )
|
||||
{
|
||||
cvMulTransposed( J, JtJ, 1 );
|
||||
cvGEMM( J, err, 1, 0, 0, JtErr, CV_GEMM_A_T );
|
||||
cvCopy( param, prevParam );
|
||||
step();
|
||||
if( iters == 0 )
|
||||
prevErrNorm = cvNorm(err, 0, CV_L2);
|
||||
_param = param;
|
||||
cvZero( err );
|
||||
_err = err;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert( state == CHECK_ERR );
|
||||
errNorm = cvNorm( err, 0, CV_L2 );
|
||||
if( errNorm > prevErrNorm )
|
||||
{
|
||||
if( ++lambdaLg10 <= 16 )
|
||||
{
|
||||
step();
|
||||
_param = param;
|
||||
cvZero( err );
|
||||
_err = err;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
lambdaLg10 = MAX(lambdaLg10-1, -16);
|
||||
if( ++iters >= criteria.max_iter ||
|
||||
(change = cvNorm(param, prevParam, CV_RELATIVE_L2)) < criteria.epsilon )
|
||||
{
|
||||
_param = param;
|
||||
state = DONE;
|
||||
return true;
|
||||
}
|
||||
|
||||
prevErrNorm = errNorm;
|
||||
_param = param;
|
||||
cvZero(J);
|
||||
matJ = J;
|
||||
_err = err;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool CvLevMarq::updateAlt( const CvMat*& _param, CvMat*& _JtJ, CvMat*& _JtErr, double*& _errNorm )
|
||||
{
|
||||
double change;
|
||||
|
||||
CV_Assert( err.empty() );
|
||||
if( state == DONE )
|
||||
{
|
||||
_param = param;
|
||||
return false;
|
||||
}
|
||||
|
||||
if( state == STARTED )
|
||||
{
|
||||
_param = param;
|
||||
cvZero( JtJ );
|
||||
cvZero( JtErr );
|
||||
errNorm = 0;
|
||||
_JtJ = JtJ;
|
||||
_JtErr = JtErr;
|
||||
_errNorm = &errNorm;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
if( state == CALC_J )
|
||||
{
|
||||
cvCopy( param, prevParam );
|
||||
step();
|
||||
_param = param;
|
||||
prevErrNorm = errNorm;
|
||||
errNorm = 0;
|
||||
_errNorm = &errNorm;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert( state == CHECK_ERR );
|
||||
if( errNorm > prevErrNorm )
|
||||
{
|
||||
if( ++lambdaLg10 <= 16 )
|
||||
{
|
||||
step();
|
||||
_param = param;
|
||||
errNorm = 0;
|
||||
_errNorm = &errNorm;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
lambdaLg10 = MAX(lambdaLg10-1, -16);
|
||||
if( ++iters >= criteria.max_iter ||
|
||||
(change = cvNorm(param, prevParam, CV_RELATIVE_L2)) < criteria.epsilon )
|
||||
{
|
||||
_param = param;
|
||||
state = DONE;
|
||||
return false;
|
||||
}
|
||||
|
||||
prevErrNorm = errNorm;
|
||||
cvZero( JtJ );
|
||||
cvZero( JtErr );
|
||||
_param = param;
|
||||
_JtJ = JtJ;
|
||||
_JtErr = JtErr;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CvLevMarq::step()
|
||||
{
|
||||
const double LOG10 = log(10.);
|
||||
double lambda = exp(lambdaLg10*LOG10);
|
||||
int i, j, nparams = param->rows;
|
||||
|
||||
for( i = 0; i < nparams; i++ )
|
||||
if( mask->data.ptr[i] == 0 )
|
||||
{
|
||||
double *row = JtJ->data.db + i*nparams, *col = JtJ->data.db + i;
|
||||
for( j = 0; j < nparams; j++ )
|
||||
row[j] = col[j*nparams] = 0;
|
||||
JtErr->data.db[i] = 0;
|
||||
}
|
||||
|
||||
if( !err )
|
||||
cvCompleteSymm( JtJ, completeSymmFlag );
|
||||
#if 1
|
||||
cvCopy( JtJ, JtJN );
|
||||
for( i = 0; i < nparams; i++ )
|
||||
JtJN->data.db[(nparams+1)*i] *= 1. + lambda;
|
||||
#else
|
||||
cvSetIdentity(JtJN, cvRealScalar(lambda));
|
||||
cvAdd( JtJ, JtJN, JtJN );
|
||||
#endif
|
||||
cvSVD( JtJN, JtJW, 0, JtJV, CV_SVD_MODIFY_A + CV_SVD_U_T + CV_SVD_V_T );
|
||||
cvSVBkSb( JtJW, JtJV, JtJV, JtErr, param, CV_SVD_U_T + CV_SVD_V_T );
|
||||
for( i = 0; i < nparams; i++ )
|
||||
param->data.db[i] = prevParam->data.db[i] - (mask->data.ptr[i] ? param->data.db[i] : 0);
|
||||
}
|
||||
|
||||
// reimplementation of dAB.m
|
||||
CV_IMPL void cvCalcMatMulDeriv( const CvMat* A, const CvMat* B, CvMat* dABdA, CvMat* dABdB )
|
||||
{
|
||||
|
@ -402,14 +402,16 @@ void CirclesGridClusterFinder::parsePatternPoints(const std::vector<cv::Point2f>
|
||||
else
|
||||
idealPt = Point2f(j*squareSize, i*squareSize);
|
||||
|
||||
std::vector<float> query = Mat(idealPt);
|
||||
Mat query(1, 2, CV_32F, &idealPt);
|
||||
int knn = 1;
|
||||
std::vector<int> indices(knn);
|
||||
std::vector<float> dists(knn);
|
||||
int indicesbuf = 0;
|
||||
float distsbuf = 0.f;
|
||||
Mat indices(1, knn, CV_32S, &indicesbuf);
|
||||
Mat dists(1, knn, CV_32F, &distsbuf);
|
||||
flannIndex.knnSearch(query, indices, dists, knn, flann::SearchParams());
|
||||
centers.push_back(patternPoints.at(indices[0]));
|
||||
centers.push_back(patternPoints.at(indicesbuf));
|
||||
|
||||
if(dists[0] > maxRectifiedDistance)
|
||||
if(distsbuf > maxRectifiedDistance)
|
||||
{
|
||||
#ifdef DEBUG_CIRCLES
|
||||
cout << "Pattern not detected: too large rectified distance" << endl;
|
||||
|
430
modules/calib3d/src/compat_ptsetreg.cpp
Normal file
430
modules/calib3d/src/compat_ptsetreg.cpp
Normal file
@ -0,0 +1,430 @@
|
||||
/*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.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Copyright (C) 2013, OpenCV Foundation, 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 the copyright holders 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"
|
||||
|
||||
/************************************************************************************\
|
||||
Some backward compatibility stuff, to be moved to legacy or compat module
|
||||
\************************************************************************************/
|
||||
|
||||
using cv::Ptr;
|
||||
|
||||
////////////////// Levenberg-Marquardt engine (the old variant) ////////////////////////
|
||||
|
||||
CvLevMarq::CvLevMarq()
|
||||
{
|
||||
mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr<CvMat>();
|
||||
lambdaLg10 = 0; state = DONE;
|
||||
criteria = cvTermCriteria(0,0,0);
|
||||
iters = 0;
|
||||
completeSymmFlag = false;
|
||||
}
|
||||
|
||||
CvLevMarq::CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria0, bool _completeSymmFlag )
|
||||
{
|
||||
mask = prevParam = param = J = err = JtJ = JtJN = JtErr = JtJV = JtJW = Ptr<CvMat>();
|
||||
init(nparams, nerrs, criteria0, _completeSymmFlag);
|
||||
}
|
||||
|
||||
void CvLevMarq::clear()
|
||||
{
|
||||
mask.release();
|
||||
prevParam.release();
|
||||
param.release();
|
||||
J.release();
|
||||
err.release();
|
||||
JtJ.release();
|
||||
JtJN.release();
|
||||
JtErr.release();
|
||||
JtJV.release();
|
||||
JtJW.release();
|
||||
}
|
||||
|
||||
CvLevMarq::~CvLevMarq()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
void CvLevMarq::init( int nparams, int nerrs, CvTermCriteria criteria0, bool _completeSymmFlag )
|
||||
{
|
||||
if( !param || param->rows != nparams || nerrs != (err ? err->rows : 0) )
|
||||
clear();
|
||||
mask = cvCreateMat( nparams, 1, CV_8U );
|
||||
cvSet(mask, cvScalarAll(1));
|
||||
prevParam = cvCreateMat( nparams, 1, CV_64F );
|
||||
param = cvCreateMat( nparams, 1, CV_64F );
|
||||
JtJ = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJN = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJV = cvCreateMat( nparams, nparams, CV_64F );
|
||||
JtJW = cvCreateMat( nparams, 1, CV_64F );
|
||||
JtErr = cvCreateMat( nparams, 1, CV_64F );
|
||||
if( nerrs > 0 )
|
||||
{
|
||||
J = cvCreateMat( nerrs, nparams, CV_64F );
|
||||
err = cvCreateMat( nerrs, 1, CV_64F );
|
||||
}
|
||||
prevErrNorm = DBL_MAX;
|
||||
lambdaLg10 = -3;
|
||||
criteria = criteria0;
|
||||
if( criteria.type & CV_TERMCRIT_ITER )
|
||||
criteria.max_iter = MIN(MAX(criteria.max_iter,1),1000);
|
||||
else
|
||||
criteria.max_iter = 30;
|
||||
if( criteria.type & CV_TERMCRIT_EPS )
|
||||
criteria.epsilon = MAX(criteria.epsilon, 0);
|
||||
else
|
||||
criteria.epsilon = DBL_EPSILON;
|
||||
state = STARTED;
|
||||
iters = 0;
|
||||
completeSymmFlag = _completeSymmFlag;
|
||||
}
|
||||
|
||||
bool CvLevMarq::update( const CvMat*& _param, CvMat*& matJ, CvMat*& _err )
|
||||
{
|
||||
double change;
|
||||
|
||||
matJ = _err = 0;
|
||||
|
||||
assert( !err.empty() );
|
||||
if( state == DONE )
|
||||
{
|
||||
_param = param;
|
||||
return false;
|
||||
}
|
||||
|
||||
if( state == STARTED )
|
||||
{
|
||||
_param = param;
|
||||
cvZero( J );
|
||||
cvZero( err );
|
||||
matJ = J;
|
||||
_err = err;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
if( state == CALC_J )
|
||||
{
|
||||
cvMulTransposed( J, JtJ, 1 );
|
||||
cvGEMM( J, err, 1, 0, 0, JtErr, CV_GEMM_A_T );
|
||||
cvCopy( param, prevParam );
|
||||
step();
|
||||
if( iters == 0 )
|
||||
prevErrNorm = cvNorm(err, 0, CV_L2);
|
||||
_param = param;
|
||||
cvZero( err );
|
||||
_err = err;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert( state == CHECK_ERR );
|
||||
errNorm = cvNorm( err, 0, CV_L2 );
|
||||
if( errNorm > prevErrNorm )
|
||||
{
|
||||
if( ++lambdaLg10 <= 16 )
|
||||
{
|
||||
step();
|
||||
_param = param;
|
||||
cvZero( err );
|
||||
_err = err;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
lambdaLg10 = MAX(lambdaLg10-1, -16);
|
||||
if( ++iters >= criteria.max_iter ||
|
||||
(change = cvNorm(param, prevParam, CV_RELATIVE_L2)) < criteria.epsilon )
|
||||
{
|
||||
_param = param;
|
||||
state = DONE;
|
||||
return true;
|
||||
}
|
||||
|
||||
prevErrNorm = errNorm;
|
||||
_param = param;
|
||||
cvZero(J);
|
||||
matJ = J;
|
||||
_err = err;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool CvLevMarq::updateAlt( const CvMat*& _param, CvMat*& _JtJ, CvMat*& _JtErr, double*& _errNorm )
|
||||
{
|
||||
double change;
|
||||
|
||||
CV_Assert( err.empty() );
|
||||
if( state == DONE )
|
||||
{
|
||||
_param = param;
|
||||
return false;
|
||||
}
|
||||
|
||||
if( state == STARTED )
|
||||
{
|
||||
_param = param;
|
||||
cvZero( JtJ );
|
||||
cvZero( JtErr );
|
||||
errNorm = 0;
|
||||
_JtJ = JtJ;
|
||||
_JtErr = JtErr;
|
||||
_errNorm = &errNorm;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
if( state == CALC_J )
|
||||
{
|
||||
cvCopy( param, prevParam );
|
||||
step();
|
||||
_param = param;
|
||||
prevErrNorm = errNorm;
|
||||
errNorm = 0;
|
||||
_errNorm = &errNorm;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert( state == CHECK_ERR );
|
||||
if( errNorm > prevErrNorm )
|
||||
{
|
||||
if( ++lambdaLg10 <= 16 )
|
||||
{
|
||||
step();
|
||||
_param = param;
|
||||
errNorm = 0;
|
||||
_errNorm = &errNorm;
|
||||
state = CHECK_ERR;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
lambdaLg10 = MAX(lambdaLg10-1, -16);
|
||||
if( ++iters >= criteria.max_iter ||
|
||||
(change = cvNorm(param, prevParam, CV_RELATIVE_L2)) < criteria.epsilon )
|
||||
{
|
||||
_param = param;
|
||||
state = DONE;
|
||||
return false;
|
||||
}
|
||||
|
||||
prevErrNorm = errNorm;
|
||||
cvZero( JtJ );
|
||||
cvZero( JtErr );
|
||||
_param = param;
|
||||
_JtJ = JtJ;
|
||||
_JtErr = JtErr;
|
||||
state = CALC_J;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CvLevMarq::step()
|
||||
{
|
||||
const double LOG10 = log(10.);
|
||||
double lambda = exp(lambdaLg10*LOG10);
|
||||
int i, j, nparams = param->rows;
|
||||
|
||||
for( i = 0; i < nparams; i++ )
|
||||
if( mask->data.ptr[i] == 0 )
|
||||
{
|
||||
double *row = JtJ->data.db + i*nparams, *col = JtJ->data.db + i;
|
||||
for( j = 0; j < nparams; j++ )
|
||||
row[j] = col[j*nparams] = 0;
|
||||
JtErr->data.db[i] = 0;
|
||||
}
|
||||
|
||||
if( !err )
|
||||
cvCompleteSymm( JtJ, completeSymmFlag );
|
||||
#if 1
|
||||
cvCopy( JtJ, JtJN );
|
||||
for( i = 0; i < nparams; i++ )
|
||||
JtJN->data.db[(nparams+1)*i] *= 1. + lambda;
|
||||
#else
|
||||
cvSetIdentity(JtJN, cvRealScalar(lambda));
|
||||
cvAdd( JtJ, JtJN, JtJN );
|
||||
#endif
|
||||
cvSVD( JtJN, JtJW, 0, JtJV, CV_SVD_MODIFY_A + CV_SVD_U_T + CV_SVD_V_T );
|
||||
cvSVBkSb( JtJW, JtJV, JtJV, JtErr, param, CV_SVD_U_T + CV_SVD_V_T );
|
||||
for( i = 0; i < nparams; i++ )
|
||||
param->data.db[i] = prevParam->data.db[i] - (mask->data.ptr[i] ? param->data.db[i] : 0);
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL int cvRANSACUpdateNumIters( double p, double ep, int modelPoints, int maxIters )
|
||||
{
|
||||
return cv::RANSACUpdateNumIters(p, ep, modelPoints, maxIters);
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL int cvFindHomography( const CvMat* _src, const CvMat* _dst, CvMat* __H, int method,
|
||||
double ransacReprojThreshold, CvMat* _mask )
|
||||
{
|
||||
cv::Mat src = cv::cvarrToMat(_src), dst = cv::cvarrToMat(_dst);
|
||||
|
||||
if( src.channels() == 1 && (src.rows == 2 || src.rows == 3) && src.cols > 3 )
|
||||
cv::transpose(src, src);
|
||||
if( dst.channels() == 1 && (dst.rows == 2 || dst.rows == 3) && dst.cols > 3 )
|
||||
cv::transpose(dst, dst);
|
||||
|
||||
const cv::Mat H = cv::cvarrToMat(__H), mask = cv::cvarrToMat(_mask);
|
||||
cv::Mat H0 = cv::findHomography(src, dst, method, ransacReprojThreshold,
|
||||
_mask ? cv::_OutputArray(mask) : cv::_OutputArray());
|
||||
|
||||
if( H0.empty() )
|
||||
{
|
||||
cv::Mat Hz = cv::cvarrToMat(__H);
|
||||
Hz.setTo(cv::Scalar::all(0));
|
||||
return 0;
|
||||
}
|
||||
H0.convertTo(H, H.type());
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL int cvFindFundamentalMat( const CvMat* points1, const CvMat* points2,
|
||||
CvMat* fmatrix, int method,
|
||||
double param1, double param2, CvMat* _mask )
|
||||
{
|
||||
cv::Mat m1 = cv::cvarrToMat(points1), m2 = cv::cvarrToMat(points2);
|
||||
|
||||
if( m1.channels() == 1 && (m1.rows == 2 || m1.rows == 3) && m1.cols > 3 )
|
||||
cv::transpose(m1, m1);
|
||||
if( m2.channels() == 1 && (m2.rows == 2 || m2.rows == 3) && m2.cols > 3 )
|
||||
cv::transpose(m2, m2);
|
||||
|
||||
const cv::Mat FM = cv::cvarrToMat(fmatrix), mask = cv::cvarrToMat(_mask);
|
||||
cv::Mat FM0 = cv::findFundamentalMat(m1, m2, method, param1, param2,
|
||||
_mask ? cv::_OutputArray(mask) : cv::_OutputArray());
|
||||
|
||||
if( FM0.empty() )
|
||||
{
|
||||
cv::Mat FM0z = cv::cvarrToMat(fmatrix);
|
||||
FM0z.setTo(cv::Scalar::all(0));
|
||||
return 0;
|
||||
}
|
||||
|
||||
CV_Assert( FM0.cols == 3 && FM0.rows % 3 == 0 && FM.cols == 3 && FM.rows % 3 == 0 && FM.channels() == 1 );
|
||||
cv::Mat FM1 = FM.rowRange(0, MIN(FM0.rows, FM.rows));
|
||||
FM0.rowRange(0, FM1.rows).convertTo(FM1, FM1.type());
|
||||
return FM1.rows / 3;
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL void cvComputeCorrespondEpilines( const CvMat* points, int pointImageID,
|
||||
const CvMat* fmatrix, CvMat* _lines )
|
||||
{
|
||||
cv::Mat pt = cv::cvarrToMat(points), fm = cv::cvarrToMat(fmatrix);
|
||||
cv::Mat lines = cv::cvarrToMat(_lines);
|
||||
const cv::Mat lines0 = lines;
|
||||
|
||||
if( pt.channels() == 1 && (pt.rows == 2 || pt.rows == 3) && pt.cols > 3 )
|
||||
cv::transpose(pt, pt);
|
||||
|
||||
cv::computeCorrespondEpilines(pt, pointImageID, fm, lines);
|
||||
|
||||
bool tflag = lines0.channels() == 1 && lines0.rows == 3 && lines0.cols > 3;
|
||||
lines = lines.reshape(lines0.channels(), (tflag ? lines0.cols : lines0.rows));
|
||||
|
||||
if( tflag )
|
||||
{
|
||||
CV_Assert( lines.rows == lines0.cols && lines.cols == lines0.rows );
|
||||
if( lines0.type() == lines.type() )
|
||||
transpose( lines, lines0 );
|
||||
else
|
||||
{
|
||||
transpose( lines, lines );
|
||||
lines.convertTo( lines0, lines0.type() );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CV_Assert( lines.size() == lines0.size() );
|
||||
if( lines.data != lines0.data )
|
||||
lines.convertTo(lines0, lines0.type());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL void cvConvertPointsHomogeneous( const CvMat* _src, CvMat* _dst )
|
||||
{
|
||||
cv::Mat src = cv::cvarrToMat(_src), dst = cv::cvarrToMat(_dst);
|
||||
const cv::Mat dst0 = dst;
|
||||
|
||||
int d0 = src.channels() > 1 ? src.channels() : MIN(src.cols, src.rows);
|
||||
|
||||
if( src.channels() == 1 && src.cols > d0 )
|
||||
cv::transpose(src, src);
|
||||
|
||||
int d1 = dst.channels() > 1 ? dst.channels() : MIN(dst.cols, dst.rows);
|
||||
|
||||
if( d0 == d1 )
|
||||
src.copyTo(dst);
|
||||
else if( d0 < d1 )
|
||||
cv::convertPointsToHomogeneous(src, dst);
|
||||
else
|
||||
cv::convertPointsFromHomogeneous(src, dst);
|
||||
|
||||
bool tflag = dst0.channels() == 1 && dst0.cols > d1;
|
||||
dst = dst.reshape(dst0.channels(), (tflag ? dst0.cols : dst0.rows));
|
||||
|
||||
if( tflag )
|
||||
{
|
||||
CV_Assert( dst.rows == dst0.cols && dst.cols == dst0.rows );
|
||||
if( dst0.type() == dst.type() )
|
||||
transpose( dst, dst0 );
|
||||
else
|
||||
{
|
||||
transpose( dst, dst );
|
||||
dst.convertTo( dst0, dst0.type() );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CV_Assert( dst.size() == dst0.size() );
|
||||
if( dst.data != dst0.data )
|
||||
dst.convertTo(dst0, dst0.type());
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
226
modules/calib3d/src/levmarq.cpp
Normal file
226
modules/calib3d/src/levmarq.cpp
Normal file
@ -0,0 +1,226 @@
|
||||
/*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.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Copyright (C) 2013, OpenCV Foundation, 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 the copyright holders 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 <stdio.h>
|
||||
|
||||
/*
|
||||
This is translation to C++ of the Matlab's LMSolve package by Miroslav Balda.
|
||||
Here is the original copyright:
|
||||
============================================================================
|
||||
|
||||
Copyright (c) 2007, Miroslav Balda
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions 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
|
||||
|
||||
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 COPYRIGHT OWNER 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.
|
||||
*/
|
||||
|
||||
namespace cv
|
||||
{
|
||||
|
||||
class LMSolverImpl : public LMSolver
|
||||
{
|
||||
public:
|
||||
LMSolverImpl() : maxIters(100) { init(); };
|
||||
LMSolverImpl(const Ptr<LMSolver::Callback>& _cb, int _maxIters) : cb(_cb), maxIters(_maxIters) { init(); }
|
||||
|
||||
void init()
|
||||
{
|
||||
epsx = epsf = FLT_EPSILON;
|
||||
printInterval = 0;
|
||||
}
|
||||
|
||||
int run(InputOutputArray _param0) const
|
||||
{
|
||||
Mat param0 = _param0.getMat(), x, xd, r, rd, J, A, Ap, v, temp_d, d;
|
||||
int ptype = param0.type();
|
||||
|
||||
CV_Assert( (param0.cols == 1 || param0.rows == 1) && (ptype == CV_32F || ptype == CV_64F));
|
||||
CV_Assert( !cb.empty() );
|
||||
|
||||
int lx = param0.rows + param0.cols - 1;
|
||||
param0.convertTo(x, CV_64F);
|
||||
|
||||
if( x.cols != 1 )
|
||||
transpose(x, x);
|
||||
|
||||
if( !cb->compute(x, r, J) )
|
||||
return -1;
|
||||
double S = norm(r, NORM_L2SQR);
|
||||
int nfJ = 2;
|
||||
|
||||
mulTransposed(J, A, true);
|
||||
gemm(J, r, 1, noArray(), 0, v, GEMM_1_T);
|
||||
|
||||
Mat D = A.diag().clone();
|
||||
|
||||
const double Rlo = 0.25, Rhi = 0.75;
|
||||
double lambda = 1, lc = 0.75;
|
||||
int i, iter = 0;
|
||||
|
||||
if( printInterval != 0 )
|
||||
{
|
||||
printf("************************************************************************************\n");
|
||||
printf("\titr\tnfJ\t\tSUM(r^2)\t\tx\t\tdx\t\tl\t\tlc\n");
|
||||
printf("************************************************************************************\n");
|
||||
}
|
||||
|
||||
for( ;; )
|
||||
{
|
||||
CV_Assert( A.type() == CV_64F && A.rows == lx );
|
||||
A.copyTo(Ap);
|
||||
for( i = 0; i < lx; i++ )
|
||||
Ap.at<double>(i, i) += lambda*D.at<double>(i);
|
||||
solve(Ap, v, d, DECOMP_EIG);
|
||||
subtract(x, d, xd);
|
||||
if( !cb->compute(xd, rd, noArray()) )
|
||||
return -1;
|
||||
nfJ++;
|
||||
double Sd = norm(rd, NORM_L2SQR);
|
||||
gemm(A, d, -1, v, 2, temp_d);
|
||||
double dS = d.dot(temp_d);
|
||||
double R = (S - Sd)/(fabs(dS) > DBL_EPSILON ? dS : 1);
|
||||
|
||||
if( R > Rhi )
|
||||
{
|
||||
lambda *= 0.5;
|
||||
if( lambda < lc )
|
||||
lambda = 0;
|
||||
}
|
||||
else if( R < Rlo )
|
||||
{
|
||||
// find new nu if R too low
|
||||
double t = d.dot(v);
|
||||
double nu = (Sd - S)/(fabs(t) > DBL_EPSILON ? t : 1) + 2;
|
||||
nu = std::min(std::max(nu, 2.), 10.);
|
||||
if( lambda == 0 )
|
||||
{
|
||||
invert(A, Ap, DECOMP_EIG);
|
||||
double maxval = DBL_EPSILON;
|
||||
for( i = 0; i < lx; i++ )
|
||||
maxval = std::max(maxval, std::abs(Ap.at<double>(i,i)));
|
||||
lambda = lc = 1./maxval;
|
||||
nu *= 0.5;
|
||||
}
|
||||
lambda *= nu;
|
||||
}
|
||||
|
||||
if( Sd < S )
|
||||
{
|
||||
nfJ++;
|
||||
S = Sd;
|
||||
std::swap(x, xd);
|
||||
if( !cb->compute(x, r, J) )
|
||||
return -1;
|
||||
mulTransposed(J, A, true);
|
||||
gemm(J, r, 1, noArray(), 0, v, GEMM_1_T);
|
||||
}
|
||||
|
||||
iter++;
|
||||
bool proceed = iter < maxIters && norm(d, NORM_INF) >= epsx && norm(r, NORM_INF) >= epsf;
|
||||
|
||||
if( printInterval != 0 && (iter % printInterval == 0 || iter == 1 || !proceed) )
|
||||
{
|
||||
printf("%c%10d %10d %15.4e %16.4e %17.4e %16.4e %17.4e\n",
|
||||
(proceed ? ' ' : '*'), iter, nfJ, S, x.at<double>(0), d.at<double>(0), lambda, lc);
|
||||
}
|
||||
|
||||
if(!proceed)
|
||||
break;
|
||||
}
|
||||
|
||||
if( param0.size != x.size )
|
||||
transpose(x, x);
|
||||
|
||||
x.convertTo(param0, ptype);
|
||||
if( iter == maxIters )
|
||||
iter = -iter;
|
||||
|
||||
return iter;
|
||||
}
|
||||
|
||||
void setCallback(const Ptr<LMSolver::Callback>& _cb) { cb = _cb; }
|
||||
|
||||
AlgorithmInfo* info() const;
|
||||
|
||||
Ptr<LMSolver::Callback> cb;
|
||||
|
||||
double epsx;
|
||||
double epsf;
|
||||
int maxIters;
|
||||
int printInterval;
|
||||
};
|
||||
|
||||
|
||||
CV_INIT_ALGORITHM(LMSolverImpl, "LMSolver",
|
||||
obj.info()->addParam(obj, "epsx", obj.epsx);
|
||||
obj.info()->addParam(obj, "epsf", obj.epsf);
|
||||
obj.info()->addParam(obj, "maxIters", obj.maxIters);
|
||||
obj.info()->addParam(obj, "printInterval", obj.printInterval));
|
||||
|
||||
CV_EXPORTS Ptr<LMSolver> createLMSolver(const Ptr<LMSolver::Callback>& cb, int maxIters)
|
||||
{
|
||||
CV_Assert( !LMSolverImpl_info_auto.name().empty() );
|
||||
return new LMSolverImpl(cb, maxIters);
|
||||
}
|
||||
|
||||
}
|
@ -1,502 +0,0 @@
|
||||
/*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 "_modelest.h"
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
|
||||
CvModelEstimator2::CvModelEstimator2(int _modelPoints, CvSize _modelSize, int _maxBasicSolutions)
|
||||
{
|
||||
modelPoints = _modelPoints;
|
||||
modelSize = _modelSize;
|
||||
maxBasicSolutions = _maxBasicSolutions;
|
||||
checkPartialSubsets = true;
|
||||
rng = cvRNG(-1);
|
||||
}
|
||||
|
||||
CvModelEstimator2::~CvModelEstimator2()
|
||||
{
|
||||
}
|
||||
|
||||
void CvModelEstimator2::setSeed( int64 seed )
|
||||
{
|
||||
rng = cvRNG(seed);
|
||||
}
|
||||
|
||||
|
||||
int CvModelEstimator2::findInliers( const CvMat* m1, const CvMat* m2,
|
||||
const CvMat* model, CvMat* _err,
|
||||
CvMat* _mask, double threshold )
|
||||
{
|
||||
int i, count = _err->rows*_err->cols, goodCount = 0;
|
||||
const float* err = _err->data.fl;
|
||||
uchar* mask = _mask->data.ptr;
|
||||
|
||||
computeReprojError( m1, m2, model, _err );
|
||||
threshold *= threshold;
|
||||
for( i = 0; i < count; i++ )
|
||||
goodCount += mask[i] = err[i] <= threshold;
|
||||
return goodCount;
|
||||
}
|
||||
|
||||
|
||||
CV_IMPL int
|
||||
cvRANSACUpdateNumIters( double p, double ep,
|
||||
int model_points, int max_iters )
|
||||
{
|
||||
if( model_points <= 0 )
|
||||
CV_Error( CV_StsOutOfRange, "the number of model points should be positive" );
|
||||
|
||||
p = MAX(p, 0.);
|
||||
p = MIN(p, 1.);
|
||||
ep = MAX(ep, 0.);
|
||||
ep = MIN(ep, 1.);
|
||||
|
||||
// avoid inf's & nan's
|
||||
double num = MAX(1. - p, DBL_MIN);
|
||||
double denom = 1. - pow(1. - ep,model_points);
|
||||
if( denom < DBL_MIN )
|
||||
return 0;
|
||||
|
||||
num = log(num);
|
||||
denom = log(denom);
|
||||
|
||||
return denom >= 0 || -num >= max_iters*(-denom) ?
|
||||
max_iters : cvRound(num/denom);
|
||||
}
|
||||
|
||||
bool CvModelEstimator2::runRANSAC( const CvMat* m1, const CvMat* m2, CvMat* model,
|
||||
CvMat* mask0, double reprojThreshold,
|
||||
double confidence, int maxIters )
|
||||
{
|
||||
bool result = false;
|
||||
cv::Ptr<CvMat> mask = cvCloneMat(mask0);
|
||||
cv::Ptr<CvMat> models, err, tmask;
|
||||
cv::Ptr<CvMat> ms1, ms2;
|
||||
|
||||
int iter, niters = maxIters;
|
||||
int count = m1->rows*m1->cols, maxGoodCount = 0;
|
||||
CV_Assert( CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask) );
|
||||
|
||||
if( count < modelPoints )
|
||||
return false;
|
||||
|
||||
models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
|
||||
err = cvCreateMat( 1, count, CV_32FC1 );
|
||||
tmask = cvCreateMat( 1, count, CV_8UC1 );
|
||||
|
||||
if( count > modelPoints )
|
||||
{
|
||||
ms1 = cvCreateMat( 1, modelPoints, m1->type );
|
||||
ms2 = cvCreateMat( 1, modelPoints, m2->type );
|
||||
}
|
||||
else
|
||||
{
|
||||
niters = 1;
|
||||
ms1 = cvCloneMat(m1);
|
||||
ms2 = cvCloneMat(m2);
|
||||
}
|
||||
|
||||
for( iter = 0; iter < niters; iter++ )
|
||||
{
|
||||
int i, goodCount, nmodels;
|
||||
if( count > modelPoints )
|
||||
{
|
||||
bool found = getSubset( m1, m2, ms1, ms2, 300 );
|
||||
if( !found )
|
||||
{
|
||||
if( iter == 0 )
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Here we check for model specific geometrical
|
||||
// constraints that allow to avoid "runKernel"
|
||||
// and not checking for inliers if not fulfilled.
|
||||
//
|
||||
// The usefullness of this constraint for homographies is explained in the paper:
|
||||
//
|
||||
// "Speeding-up homography estimation in mobile devices"
|
||||
// Journal of Real-Time Image Processing. 2013. DOI: 10.1007/s11554-012-0314-1
|
||||
// Pablo Márquez-Neila, Javier López-Alberca, José M. Buenaposada, Luis Baumela
|
||||
if ( !isMinimalSetConsistent( ms1, ms2 ) )
|
||||
continue;
|
||||
}
|
||||
|
||||
nmodels = runKernel( ms1, ms2, models );
|
||||
if( nmodels <= 0 )
|
||||
continue;
|
||||
for( i = 0; i < nmodels; i++ )
|
||||
{
|
||||
CvMat model_i;
|
||||
cvGetRows( models, &model_i, i*modelSize.height, (i+1)*modelSize.height );
|
||||
goodCount = findInliers( m1, m2, &model_i, err, tmask, reprojThreshold );
|
||||
|
||||
if( goodCount > MAX(maxGoodCount, modelPoints-1) )
|
||||
{
|
||||
std::swap(tmask, mask);
|
||||
cvCopy( &model_i, model );
|
||||
maxGoodCount = goodCount;
|
||||
niters = cvRANSACUpdateNumIters( confidence,
|
||||
(double)(count - goodCount)/count, modelPoints, niters );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( maxGoodCount > 0 )
|
||||
{
|
||||
if( mask != mask0 )
|
||||
cvCopy( mask, mask0 );
|
||||
result = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
static CV_IMPLEMENT_QSORT( icvSortDistances, int, CV_LT )
|
||||
|
||||
bool CvModelEstimator2::runLMeDS( const CvMat* m1, const CvMat* m2, CvMat* model,
|
||||
CvMat* mask, double confidence, int maxIters )
|
||||
{
|
||||
const double outlierRatio = 0.45;
|
||||
bool result = false;
|
||||
cv::Ptr<CvMat> models;
|
||||
cv::Ptr<CvMat> ms1, ms2;
|
||||
cv::Ptr<CvMat> err;
|
||||
|
||||
int iter, niters = maxIters;
|
||||
int count = m1->rows*m1->cols;
|
||||
double minMedian = DBL_MAX, sigma;
|
||||
|
||||
CV_Assert( CV_ARE_SIZES_EQ(m1, m2) && CV_ARE_SIZES_EQ(m1, mask) );
|
||||
|
||||
if( count < modelPoints )
|
||||
return false;
|
||||
|
||||
models = cvCreateMat( modelSize.height*maxBasicSolutions, modelSize.width, CV_64FC1 );
|
||||
err = cvCreateMat( 1, count, CV_32FC1 );
|
||||
|
||||
if( count > modelPoints )
|
||||
{
|
||||
ms1 = cvCreateMat( 1, modelPoints, m1->type );
|
||||
ms2 = cvCreateMat( 1, modelPoints, m2->type );
|
||||
}
|
||||
else
|
||||
{
|
||||
niters = 1;
|
||||
ms1 = cvCloneMat(m1);
|
||||
ms2 = cvCloneMat(m2);
|
||||
}
|
||||
|
||||
niters = cvRound(log(1-confidence)/log(1-pow(1-outlierRatio,(double)modelPoints)));
|
||||
niters = MIN( MAX(niters, 3), maxIters );
|
||||
|
||||
for( iter = 0; iter < niters; iter++ )
|
||||
{
|
||||
int i, nmodels;
|
||||
if( count > modelPoints )
|
||||
{
|
||||
bool found = getSubset( m1, m2, ms1, ms2, 300 );
|
||||
if( !found )
|
||||
{
|
||||
if( iter == 0 )
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
nmodels = runKernel( ms1, ms2, models );
|
||||
if( nmodels <= 0 )
|
||||
continue;
|
||||
for( i = 0; i < nmodels; i++ )
|
||||
{
|
||||
CvMat model_i;
|
||||
cvGetRows( models, &model_i, i*modelSize.height, (i+1)*modelSize.height );
|
||||
computeReprojError( m1, m2, &model_i, err );
|
||||
icvSortDistances( err->data.i, count, 0 );
|
||||
|
||||
double median = count % 2 != 0 ?
|
||||
err->data.fl[count/2] : (err->data.fl[count/2-1] + err->data.fl[count/2])*0.5;
|
||||
|
||||
if( median < minMedian )
|
||||
{
|
||||
minMedian = median;
|
||||
cvCopy( &model_i, model );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( minMedian < DBL_MAX )
|
||||
{
|
||||
sigma = 2.5*1.4826*(1 + 5./(count - modelPoints))*std::sqrt(minMedian);
|
||||
sigma = MAX( sigma, 0.001 );
|
||||
|
||||
count = findInliers( m1, m2, model, err, mask, sigma );
|
||||
result = count >= modelPoints;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
bool CvModelEstimator2::getSubset( const CvMat* m1, const CvMat* m2,
|
||||
CvMat* ms1, CvMat* ms2, int maxAttempts )
|
||||
{
|
||||
cv::AutoBuffer<int> _idx(modelPoints);
|
||||
int* idx = _idx;
|
||||
int i = 0, j, k, idx_i, iters = 0;
|
||||
int type = CV_MAT_TYPE(m1->type), elemSize = CV_ELEM_SIZE(type);
|
||||
const int *m1ptr = m1->data.i, *m2ptr = m2->data.i;
|
||||
int *ms1ptr = ms1->data.i, *ms2ptr = ms2->data.i;
|
||||
int count = m1->cols*m1->rows;
|
||||
|
||||
assert( CV_IS_MAT_CONT(m1->type & m2->type) && (elemSize % sizeof(int) == 0) );
|
||||
elemSize /= sizeof(int);
|
||||
|
||||
for(; iters < maxAttempts; iters++)
|
||||
{
|
||||
for( i = 0; i < modelPoints && iters < maxAttempts; )
|
||||
{
|
||||
idx[i] = idx_i = cvRandInt(&rng) % count;
|
||||
for( j = 0; j < i; j++ )
|
||||
if( idx_i == idx[j] )
|
||||
break;
|
||||
if( j < i )
|
||||
continue;
|
||||
for( k = 0; k < elemSize; k++ )
|
||||
{
|
||||
ms1ptr[i*elemSize + k] = m1ptr[idx_i*elemSize + k];
|
||||
ms2ptr[i*elemSize + k] = m2ptr[idx_i*elemSize + k];
|
||||
}
|
||||
if( checkPartialSubsets && (!checkSubset( ms1, i+1 ) || !checkSubset( ms2, i+1 )))
|
||||
{
|
||||
iters++;
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if( !checkPartialSubsets && i == modelPoints &&
|
||||
(!checkSubset( ms1, i ) || !checkSubset( ms2, i )))
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
|
||||
return i == modelPoints && iters < maxAttempts;
|
||||
}
|
||||
|
||||
|
||||
bool CvModelEstimator2::checkSubset( const CvMat* m, int count )
|
||||
{
|
||||
if( count <= 2 )
|
||||
return true;
|
||||
|
||||
int j, k, i, i0, i1;
|
||||
CvPoint2D64f* ptr = (CvPoint2D64f*)m->data.ptr;
|
||||
|
||||
assert( CV_MAT_TYPE(m->type) == CV_64FC2 );
|
||||
|
||||
if( checkPartialSubsets )
|
||||
i0 = i1 = count - 1;
|
||||
else
|
||||
i0 = 0, i1 = count - 1;
|
||||
|
||||
for( i = i0; i <= i1; i++ )
|
||||
{
|
||||
// check that the i-th selected point does not belong
|
||||
// to a line connecting some previously selected points
|
||||
for( j = 0; j < i; j++ )
|
||||
{
|
||||
double dx1 = ptr[j].x - ptr[i].x;
|
||||
double dy1 = ptr[j].y - ptr[i].y;
|
||||
for( k = 0; k < j; k++ )
|
||||
{
|
||||
double dx2 = ptr[k].x - ptr[i].x;
|
||||
double dy2 = ptr[k].y - ptr[i].y;
|
||||
if( fabs(dx2*dy1 - dy2*dx1) <= FLT_EPSILON*(fabs(dx1) + fabs(dy1) + fabs(dx2) + fabs(dy2)))
|
||||
break;
|
||||
}
|
||||
if( k < j )
|
||||
break;
|
||||
}
|
||||
if( j < i )
|
||||
break;
|
||||
}
|
||||
|
||||
return i > i1;
|
||||
}
|
||||
|
||||
|
||||
namespace cv
|
||||
{
|
||||
|
||||
class Affine3DEstimator : public CvModelEstimator2
|
||||
{
|
||||
public:
|
||||
Affine3DEstimator() : CvModelEstimator2(4, cvSize(4, 3), 1) {}
|
||||
virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model );
|
||||
protected:
|
||||
virtual void computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error );
|
||||
virtual bool checkSubset( const CvMat* ms1, int count );
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
int cv::Affine3DEstimator::runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )
|
||||
{
|
||||
const Point3d* from = reinterpret_cast<const Point3d*>(m1->data.ptr);
|
||||
const Point3d* to = reinterpret_cast<const Point3d*>(m2->data.ptr);
|
||||
|
||||
Mat A(12, 12, CV_64F);
|
||||
Mat B(12, 1, CV_64F);
|
||||
A = Scalar(0.0);
|
||||
|
||||
for(int i = 0; i < modelPoints; ++i)
|
||||
{
|
||||
*B.ptr<Point3d>(3*i) = to[i];
|
||||
|
||||
double *aptr = A.ptr<double>(3*i);
|
||||
for(int k = 0; k < 3; ++k)
|
||||
{
|
||||
aptr[3] = 1.0;
|
||||
*reinterpret_cast<Point3d*>(aptr) = from[i];
|
||||
aptr += 16;
|
||||
}
|
||||
}
|
||||
|
||||
CvMat cvA = A;
|
||||
CvMat cvB = B;
|
||||
CvMat cvX;
|
||||
cvReshape(model, &cvX, 1, 12);
|
||||
cvSolve(&cvA, &cvB, &cvX, CV_SVD );
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
void cv::Affine3DEstimator::computeReprojError( const CvMat* m1, const CvMat* m2, const CvMat* model, CvMat* error )
|
||||
{
|
||||
int count = m1->rows * m1->cols;
|
||||
const Point3d* from = reinterpret_cast<const Point3d*>(m1->data.ptr);
|
||||
const Point3d* to = reinterpret_cast<const Point3d*>(m2->data.ptr);
|
||||
const double* F = model->data.db;
|
||||
float* err = error->data.fl;
|
||||
|
||||
for(int i = 0; i < count; i++ )
|
||||
{
|
||||
const Point3d& f = from[i];
|
||||
const Point3d& t = to[i];
|
||||
|
||||
double a = F[0]*f.x + F[1]*f.y + F[ 2]*f.z + F[ 3] - t.x;
|
||||
double b = F[4]*f.x + F[5]*f.y + F[ 6]*f.z + F[ 7] - t.y;
|
||||
double c = F[8]*f.x + F[9]*f.y + F[10]*f.z + F[11] - t.z;
|
||||
|
||||
err[i] = (float)std::sqrt(a*a + b*b + c*c);
|
||||
}
|
||||
}
|
||||
|
||||
bool cv::Affine3DEstimator::checkSubset( const CvMat* ms1, int count )
|
||||
{
|
||||
CV_Assert( CV_MAT_TYPE(ms1->type) == CV_64FC3 );
|
||||
|
||||
int j, k, i = count - 1;
|
||||
const Point3d* ptr = reinterpret_cast<const Point3d*>(ms1->data.ptr);
|
||||
|
||||
// check that the i-th selected point does not belong
|
||||
// to a line connecting some previously selected points
|
||||
|
||||
for(j = 0; j < i; ++j)
|
||||
{
|
||||
Point3d d1 = ptr[j] - ptr[i];
|
||||
double n1 = norm(d1);
|
||||
|
||||
for(k = 0; k < j; ++k)
|
||||
{
|
||||
Point3d d2 = ptr[k] - ptr[i];
|
||||
double n = norm(d2) * n1;
|
||||
|
||||
if (fabs(d1.dot(d2) / n) > 0.996)
|
||||
break;
|
||||
}
|
||||
if( k < j )
|
||||
break;
|
||||
}
|
||||
|
||||
return j == i;
|
||||
}
|
||||
|
||||
int cv::estimateAffine3D(InputArray _from, InputArray _to,
|
||||
OutputArray _out, OutputArray _inliers,
|
||||
double param1, double param2)
|
||||
{
|
||||
Mat from = _from.getMat(), to = _to.getMat();
|
||||
int count = from.checkVector(3);
|
||||
|
||||
CV_Assert( count >= 0 && to.checkVector(3) == count );
|
||||
|
||||
_out.create(3, 4, CV_64F);
|
||||
Mat out = _out.getMat();
|
||||
|
||||
Mat inliers(1, count, CV_8U);
|
||||
inliers = Scalar::all(1);
|
||||
|
||||
Mat dFrom, dTo;
|
||||
from.convertTo(dFrom, CV_64F);
|
||||
to.convertTo(dTo, CV_64F);
|
||||
dFrom = dFrom.reshape(3, 1);
|
||||
dTo = dTo.reshape(3, 1);
|
||||
|
||||
CvMat F3x4 = out;
|
||||
CvMat mask = inliers;
|
||||
CvMat m1 = dFrom;
|
||||
CvMat m2 = dTo;
|
||||
|
||||
const double epsilon = std::numeric_limits<double>::epsilon();
|
||||
param1 = param1 <= 0 ? 3 : param1;
|
||||
param2 = (param2 < epsilon) ? 0.99 : (param2 > 1 - epsilon) ? 0.99 : param2;
|
||||
|
||||
int ok = Affine3DEstimator().runRANSAC(&m1, &m2, &F3x4, &mask, param1, param2 );
|
||||
if( _inliers.needed() )
|
||||
transpose(inliers, _inliers);
|
||||
|
||||
return ok;
|
||||
}
|
@ -59,4 +59,51 @@
|
||||
#define GET_OPTIMIZED(func) (func)
|
||||
#endif
|
||||
|
||||
|
||||
namespace cv
|
||||
{
|
||||
|
||||
int RANSACUpdateNumIters( double p, double ep, int modelPoints, int maxIters );
|
||||
|
||||
class CV_EXPORTS LMSolver : public Algorithm
|
||||
{
|
||||
public:
|
||||
class CV_EXPORTS Callback
|
||||
{
|
||||
public:
|
||||
virtual ~Callback() {}
|
||||
virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0;
|
||||
};
|
||||
|
||||
virtual void setCallback(const Ptr<LMSolver::Callback>& cb) = 0;
|
||||
virtual int run(InputOutputArray _param0) const = 0;
|
||||
};
|
||||
|
||||
CV_EXPORTS Ptr<LMSolver> createLMSolver(const Ptr<LMSolver::Callback>& cb, int maxIters);
|
||||
|
||||
class PointSetRegistrator : public Algorithm
|
||||
{
|
||||
public:
|
||||
class CV_EXPORTS Callback
|
||||
{
|
||||
public:
|
||||
virtual ~Callback() {}
|
||||
virtual int runKernel(InputArray m1, InputArray m2, OutputArray model) const = 0;
|
||||
virtual void computeError(InputArray m1, InputArray m2, InputArray model, OutputArray err) const = 0;
|
||||
virtual bool checkSubset(InputArray, InputArray, int) const { return true; }
|
||||
};
|
||||
|
||||
virtual void setCallback(const Ptr<PointSetRegistrator::Callback>& cb) = 0;
|
||||
virtual bool run(InputArray m1, InputArray m2, OutputArray model, OutputArray mask) const = 0;
|
||||
};
|
||||
|
||||
CV_EXPORTS Ptr<PointSetRegistrator> createRANSACPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& cb,
|
||||
int modelPoints, double threshold,
|
||||
double confidence=0.99, int maxIters=1000 );
|
||||
|
||||
CV_EXPORTS Ptr<PointSetRegistrator> createLMeDSPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& cb,
|
||||
int modelPoints, double confidence=0.99, int maxIters=1000 );
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
|
545
modules/calib3d/src/ptsetreg.cpp
Normal file
545
modules/calib3d/src/ptsetreg.cpp
Normal file
@ -0,0 +1,545 @@
|
||||
/*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.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
|
||||
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
|
||||
// Copyright (C) 2013, OpenCV Foundation, 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 the copyright holders 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 <algorithm>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
|
||||
namespace cv
|
||||
{
|
||||
|
||||
int RANSACUpdateNumIters( double p, double ep, int modelPoints, int maxIters )
|
||||
{
|
||||
if( modelPoints <= 0 )
|
||||
CV_Error( CV_StsOutOfRange, "the number of model points should be positive" );
|
||||
|
||||
p = MAX(p, 0.);
|
||||
p = MIN(p, 1.);
|
||||
ep = MAX(ep, 0.);
|
||||
ep = MIN(ep, 1.);
|
||||
|
||||
// avoid inf's & nan's
|
||||
double num = MAX(1. - p, DBL_MIN);
|
||||
double denom = 1. - std::pow(1. - ep, modelPoints);
|
||||
if( denom < DBL_MIN )
|
||||
return 0;
|
||||
|
||||
num = std::log(num);
|
||||
denom = std::log(denom);
|
||||
|
||||
return denom >= 0 || -num >= maxIters*(-denom) ? maxIters : cvRound(num/denom);
|
||||
}
|
||||
|
||||
|
||||
class RANSACPointSetRegistrator : public PointSetRegistrator
|
||||
{
|
||||
public:
|
||||
RANSACPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& _cb=Ptr<PointSetRegistrator::Callback>(),
|
||||
int _modelPoints=0, double _threshold=0, double _confidence=0.99, int _maxIters=1000)
|
||||
: cb(_cb), modelPoints(_modelPoints), threshold(_threshold), confidence(_confidence), maxIters(_maxIters)
|
||||
{
|
||||
checkPartialSubsets = true;
|
||||
}
|
||||
|
||||
virtual ~RANSACPointSetRegistrator() {}
|
||||
|
||||
int findInliers( const Mat& m1, const Mat& m2, const Mat& model, Mat& err, Mat& mask, double thresh ) const
|
||||
{
|
||||
cb->computeError( m1, m2, model, err );
|
||||
mask.create(err.size(), CV_8U);
|
||||
|
||||
CV_Assert( err.isContinuous() && err.type() == CV_32F && mask.isContinuous() && mask.type() == CV_8U);
|
||||
const float* errptr = err.ptr<float>();
|
||||
uchar* maskptr = mask.ptr<uchar>();
|
||||
float t = (float)(thresh*thresh);
|
||||
int i, n = (int)err.total(), nz = 0;
|
||||
for( i = 0; i < n; i++ )
|
||||
{
|
||||
int f = errptr[i] <= t;
|
||||
maskptr[i] = (uchar)f;
|
||||
nz += f;
|
||||
}
|
||||
return nz;
|
||||
}
|
||||
|
||||
bool getSubset( const Mat& m1, const Mat& m2,
|
||||
Mat& ms1, Mat& ms2, RNG& rng,
|
||||
int maxAttempts=1000 ) const
|
||||
{
|
||||
cv::AutoBuffer<int> _idx(modelPoints);
|
||||
int* idx = _idx;
|
||||
int i = 0, j, k, iters = 0;
|
||||
int esz1 = (int)m1.elemSize(), esz2 = (int)m2.elemSize();
|
||||
int d1 = m1.channels() > 1 ? m1.channels() : m1.cols;
|
||||
int d2 = m2.channels() > 1 ? m2.channels() : m2.cols;
|
||||
int count = m1.checkVector(d1), count2 = m2.checkVector(d2);
|
||||
const int *m1ptr = (const int*)m1.data, *m2ptr = (const int*)m2.data;
|
||||
|
||||
ms1.create(modelPoints, 1, CV_MAKETYPE(m1.depth(), d1));
|
||||
ms2.create(modelPoints, 1, CV_MAKETYPE(m2.depth(), d2));
|
||||
|
||||
int *ms1ptr = (int*)ms1.data, *ms2ptr = (int*)ms2.data;
|
||||
|
||||
CV_Assert( count >= modelPoints && count == count2 );
|
||||
CV_Assert( (esz1 % sizeof(int)) == 0 && (esz2 % sizeof(int)) == 0 );
|
||||
esz1 /= sizeof(int);
|
||||
esz2 /= sizeof(int);
|
||||
|
||||
for(; iters < maxAttempts; iters++)
|
||||
{
|
||||
for( i = 0; i < modelPoints && iters < maxAttempts; )
|
||||
{
|
||||
int idx_i = 0;
|
||||
for(;;)
|
||||
{
|
||||
idx_i = idx[i] = rng.uniform(0, count);
|
||||
for( j = 0; j < i; j++ )
|
||||
if( idx_i == idx[j] )
|
||||
break;
|
||||
if( j == i )
|
||||
break;
|
||||
}
|
||||
for( k = 0; k < esz1; k++ )
|
||||
ms1ptr[i*esz1 + k] = m1ptr[idx_i*esz1 + k];
|
||||
for( k = 0; k < esz2; k++ )
|
||||
ms2ptr[i*esz2 + k] = m2ptr[idx_i*esz2 + k];
|
||||
if( checkPartialSubsets && !cb->checkSubset( ms1, ms2, i+1 ))
|
||||
{
|
||||
iters++;
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if( !checkPartialSubsets && i == modelPoints && !cb->checkSubset(ms1, ms2, i))
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
|
||||
return i == modelPoints && iters < maxAttempts;
|
||||
}
|
||||
|
||||
bool run(InputArray _m1, InputArray _m2, OutputArray _model, OutputArray _mask) const
|
||||
{
|
||||
bool result = false;
|
||||
Mat m1 = _m1.getMat(), m2 = _m2.getMat();
|
||||
Mat err, mask, model, bestModel, ms1, ms2;
|
||||
|
||||
int iter, niters = MAX(maxIters, 1);
|
||||
int d1 = m1.channels() > 1 ? m1.channels() : m1.cols;
|
||||
int d2 = m2.channels() > 1 ? m2.channels() : m2.cols;
|
||||
int count = m1.checkVector(d1), count2 = m2.checkVector(d2), maxGoodCount = 0;
|
||||
|
||||
RNG rng((uint64)-1);
|
||||
|
||||
CV_Assert( !cb.empty() );
|
||||
CV_Assert( confidence > 0 && confidence < 1 );
|
||||
|
||||
CV_Assert( count >= 0 && count2 == count );
|
||||
if( count < modelPoints )
|
||||
return false;
|
||||
|
||||
Mat bestMask0, bestMask;
|
||||
|
||||
if( _mask.needed() )
|
||||
{
|
||||
if( !_mask.fixedSize() )
|
||||
_mask.create(count, 1, CV_8U);
|
||||
bestMask0 = bestMask = _mask.getMat();
|
||||
CV_Assert( (bestMask.cols == 1 || bestMask.rows == 1) && (int)bestMask.total() == count );
|
||||
}
|
||||
else
|
||||
{
|
||||
bestMask.create(count, 1, CV_8U);
|
||||
bestMask0 = bestMask;
|
||||
}
|
||||
|
||||
if( count == modelPoints )
|
||||
{
|
||||
if( cb->runKernel(m1, m2, bestModel) <= 0 )
|
||||
return false;
|
||||
bestModel.copyTo(_model);
|
||||
bestMask.setTo(Scalar::all(1));
|
||||
return true;
|
||||
}
|
||||
|
||||
for( iter = 0; iter < niters; iter++ )
|
||||
{
|
||||
int i, goodCount, nmodels;
|
||||
if( count > modelPoints )
|
||||
{
|
||||
bool found = getSubset( m1, m2, ms1, ms2, rng );
|
||||
if( !found )
|
||||
{
|
||||
if( iter == 0 )
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
nmodels = cb->runKernel( ms1, ms2, model );
|
||||
if( nmodels <= 0 )
|
||||
continue;
|
||||
CV_Assert( model.rows % nmodels == 0 );
|
||||
Size modelSize(model.cols, model.rows/nmodels);
|
||||
|
||||
for( i = 0; i < nmodels; i++ )
|
||||
{
|
||||
Mat model_i = model.rowRange( i*modelSize.height, (i+1)*modelSize.height );
|
||||
goodCount = findInliers( m1, m2, model_i, err, mask, threshold );
|
||||
|
||||
if( goodCount > MAX(maxGoodCount, modelPoints-1) )
|
||||
{
|
||||
std::swap(mask, bestMask);
|
||||
model_i.copyTo(bestModel);
|
||||
maxGoodCount = goodCount;
|
||||
niters = RANSACUpdateNumIters( confidence, (double)(count - goodCount)/count, modelPoints, niters );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( maxGoodCount > 0 )
|
||||
{
|
||||
if( bestMask.data != bestMask0.data )
|
||||
{
|
||||
if( bestMask.size() == bestMask0.size() )
|
||||
bestMask.copyTo(bestMask0);
|
||||
else
|
||||
transpose(bestMask, bestMask0);
|
||||
}
|
||||
bestModel.copyTo(_model);
|
||||
result = true;
|
||||
}
|
||||
else
|
||||
_model.release();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void setCallback(const Ptr<PointSetRegistrator::Callback>& _cb) { cb = _cb; }
|
||||
|
||||
AlgorithmInfo* info() const;
|
||||
|
||||
Ptr<PointSetRegistrator::Callback> cb;
|
||||
int modelPoints;
|
||||
int maxBasicSolutions;
|
||||
bool checkPartialSubsets;
|
||||
double threshold;
|
||||
double confidence;
|
||||
int maxIters;
|
||||
};
|
||||
|
||||
|
||||
static CV_IMPLEMENT_QSORT( sortDistances, int, CV_LT )
|
||||
|
||||
class LMeDSPointSetRegistrator : public RANSACPointSetRegistrator
|
||||
{
|
||||
public:
|
||||
LMeDSPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& _cb=Ptr<PointSetRegistrator::Callback>(),
|
||||
int _modelPoints=0, double _confidence=0.99, int _maxIters=1000)
|
||||
: RANSACPointSetRegistrator(_cb, _modelPoints, 0, _confidence, _maxIters) {}
|
||||
|
||||
bool run(InputArray _m1, InputArray _m2, OutputArray _model, OutputArray _mask) const
|
||||
{
|
||||
const double outlierRatio = 0.45;
|
||||
bool result = false;
|
||||
Mat m1 = _m1.getMat(), m2 = _m2.getMat();
|
||||
Mat ms1, ms2, err, errf, model, bestModel, mask, mask0;
|
||||
|
||||
int d1 = m1.channels() > 1 ? m1.channels() : m1.cols;
|
||||
int d2 = m2.channels() > 1 ? m2.channels() : m2.cols;
|
||||
int count = m1.checkVector(d1), count2 = m2.checkVector(d2);
|
||||
double minMedian = DBL_MAX, sigma;
|
||||
|
||||
RNG rng((uint64)-1);
|
||||
|
||||
CV_Assert( !cb.empty() );
|
||||
CV_Assert( confidence > 0 && confidence < 1 );
|
||||
|
||||
CV_Assert( count >= 0 && count2 == count );
|
||||
if( count < modelPoints )
|
||||
return false;
|
||||
|
||||
if( _mask.needed() )
|
||||
{
|
||||
if( !_mask.fixedSize() )
|
||||
_mask.create(count, 1, CV_8U);
|
||||
mask0 = mask = _mask.getMat();
|
||||
CV_Assert( (mask.cols == 1 || mask.rows == 1) && (int)mask.total() == count );
|
||||
}
|
||||
|
||||
if( count == modelPoints )
|
||||
{
|
||||
if( cb->runKernel(m1, m2, bestModel) <= 0 )
|
||||
return false;
|
||||
bestModel.copyTo(_model);
|
||||
mask.setTo(Scalar::all(1));
|
||||
return true;
|
||||
}
|
||||
|
||||
int iter, niters = cvRound(std::log(1-confidence)/
|
||||
std::log(1-std::pow(1-outlierRatio,(double)modelPoints)));
|
||||
niters = MIN( MAX(niters, 3), maxIters );
|
||||
|
||||
for( iter = 0; iter < niters; iter++ )
|
||||
{
|
||||
int i, nmodels;
|
||||
if( count > modelPoints )
|
||||
{
|
||||
bool found = getSubset( m1, m2, ms1, ms2, rng );
|
||||
if( !found )
|
||||
{
|
||||
if( iter == 0 )
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
nmodels = cb->runKernel( ms1, ms2, model );
|
||||
if( nmodels <= 0 )
|
||||
continue;
|
||||
|
||||
CV_Assert( model.rows % nmodels == 0 );
|
||||
Size modelSize(model.cols, model.rows/nmodels);
|
||||
|
||||
for( i = 0; i < nmodels; i++ )
|
||||
{
|
||||
Mat model_i = model.rowRange( i*modelSize.height, (i+1)*modelSize.height );
|
||||
cb->computeError( m1, m2, model_i, err );
|
||||
if( err.depth() != CV_32F )
|
||||
err.convertTo(errf, CV_32F);
|
||||
else
|
||||
errf = err;
|
||||
CV_Assert( errf.isContinuous() && errf.type() == CV_32F && (int)errf.total() == count );
|
||||
sortDistances( (int*)errf.data, count, 0 );
|
||||
|
||||
double median = count % 2 != 0 ?
|
||||
errf.at<float>(count/2) : (errf.at<float>(count/2-1) + errf.at<float>(count/2))*0.5;
|
||||
|
||||
if( median < minMedian )
|
||||
{
|
||||
minMedian = median;
|
||||
model_i.copyTo(bestModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( minMedian < DBL_MAX )
|
||||
{
|
||||
sigma = 2.5*1.4826*(1 + 5./(count - modelPoints))*std::sqrt(minMedian);
|
||||
sigma = MAX( sigma, 0.001 );
|
||||
|
||||
count = findInliers( m1, m2, bestModel, err, mask, sigma );
|
||||
if( _mask.needed() && mask0.data != mask.data )
|
||||
{
|
||||
if( mask0.size() == mask.size() )
|
||||
mask.copyTo(mask0);
|
||||
else
|
||||
transpose(mask, mask0);
|
||||
}
|
||||
bestModel.copyTo(_model);
|
||||
result = count >= modelPoints;
|
||||
}
|
||||
else
|
||||
_model.release();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
AlgorithmInfo* info() const;
|
||||
};
|
||||
|
||||
|
||||
CV_INIT_ALGORITHM(RANSACPointSetRegistrator, "PointSetRegistrator.RANSAC",
|
||||
obj.info()->addParam(obj, "threshold", obj.threshold);
|
||||
obj.info()->addParam(obj, "confidence", obj.confidence);
|
||||
obj.info()->addParam(obj, "maxIters", obj.maxIters));
|
||||
|
||||
CV_INIT_ALGORITHM(LMeDSPointSetRegistrator, "PointSetRegistrator.LMeDS",
|
||||
obj.info()->addParam(obj, "confidence", obj.confidence);
|
||||
obj.info()->addParam(obj, "maxIters", obj.maxIters));
|
||||
|
||||
Ptr<PointSetRegistrator> createRANSACPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& _cb,
|
||||
int _modelPoints, double _threshold,
|
||||
double _confidence, int _maxIters)
|
||||
{
|
||||
CV_Assert( !RANSACPointSetRegistrator_info_auto.name().empty() );
|
||||
return new RANSACPointSetRegistrator(_cb, _modelPoints, _threshold, _confidence, _maxIters);
|
||||
}
|
||||
|
||||
|
||||
Ptr<PointSetRegistrator> createLMeDSPointSetRegistrator(const Ptr<PointSetRegistrator::Callback>& _cb,
|
||||
int _modelPoints, double _confidence, int _maxIters)
|
||||
{
|
||||
CV_Assert( !LMeDSPointSetRegistrator_info_auto.name().empty() );
|
||||
return new LMeDSPointSetRegistrator(_cb, _modelPoints, _confidence, _maxIters);
|
||||
}
|
||||
|
||||
class Affine3DEstimatorCallback : public PointSetRegistrator::Callback
|
||||
{
|
||||
public:
|
||||
int runKernel( InputArray _m1, InputArray _m2, OutputArray _model ) const
|
||||
{
|
||||
Mat m1 = _m1.getMat(), m2 = _m2.getMat();
|
||||
const Point3f* from = m1.ptr<Point3f>();
|
||||
const Point3f* to = m2.ptr<Point3f>();
|
||||
|
||||
const int N = 12;
|
||||
double buf[N*N + N + N];
|
||||
Mat A(N, N, CV_64F, &buf[0]);
|
||||
Mat B(N, 1, CV_64F, &buf[0] + N*N);
|
||||
Mat X(N, 1, CV_64F, &buf[0] + N*N + N);
|
||||
double* Adata = A.ptr<double>();
|
||||
double* Bdata = B.ptr<double>();
|
||||
A = Scalar::all(0);
|
||||
|
||||
for( int i = 0; i < (N/3); i++ )
|
||||
{
|
||||
Bdata[i*3] = to[i].x;
|
||||
Bdata[i*3+1] = to[i].y;
|
||||
Bdata[i*3+2] = to[i].z;
|
||||
|
||||
double *aptr = Adata + i*3*N;
|
||||
for(int k = 0; k < 3; ++k)
|
||||
{
|
||||
aptr[0] = from[i].x;
|
||||
aptr[1] = from[i].y;
|
||||
aptr[2] = from[i].z;
|
||||
aptr[3] = 1.0;
|
||||
aptr += 16;
|
||||
}
|
||||
}
|
||||
|
||||
solve(A, B, X, DECOMP_SVD);
|
||||
X.reshape(1, 3).copyTo(_model);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
void computeError( InputArray _m1, InputArray _m2, InputArray _model, OutputArray _err ) const
|
||||
{
|
||||
Mat m1 = _m1.getMat(), m2 = _m2.getMat(), model = _model.getMat();
|
||||
const Point3f* from = m1.ptr<Point3f>();
|
||||
const Point3f* to = m2.ptr<Point3f>();
|
||||
const double* F = model.ptr<double>();
|
||||
|
||||
int count = m1.checkVector(3);
|
||||
CV_Assert( count > 0 );
|
||||
|
||||
_err.create(count, 1, CV_32F);
|
||||
Mat err = _err.getMat();
|
||||
float* errptr = err.ptr<float>();
|
||||
|
||||
for(int i = 0; i < count; i++ )
|
||||
{
|
||||
const Point3f& f = from[i];
|
||||
const Point3f& t = to[i];
|
||||
|
||||
double a = F[0]*f.x + F[1]*f.y + F[ 2]*f.z + F[ 3] - t.x;
|
||||
double b = F[4]*f.x + F[5]*f.y + F[ 6]*f.z + F[ 7] - t.y;
|
||||
double c = F[8]*f.x + F[9]*f.y + F[10]*f.z + F[11] - t.z;
|
||||
|
||||
errptr[i] = (float)std::sqrt(a*a + b*b + c*c);
|
||||
}
|
||||
}
|
||||
|
||||
bool checkSubset( InputArray _ms1, InputArray _ms2, int count ) const
|
||||
{
|
||||
const float threshold = 0.996f;
|
||||
Mat ms1 = _ms1.getMat(), ms2 = _ms2.getMat();
|
||||
|
||||
for( int inp = 1; inp <= 2; inp++ )
|
||||
{
|
||||
int j, k, i = count - 1;
|
||||
const Mat* msi = inp == 1 ? &ms1 : &ms2;
|
||||
const Point3f* ptr = msi->ptr<Point3f>();
|
||||
|
||||
CV_Assert( count <= msi->rows );
|
||||
|
||||
// check that the i-th selected point does not belong
|
||||
// to a line connecting some previously selected points
|
||||
for(j = 0; j < i; ++j)
|
||||
{
|
||||
Point3f d1 = ptr[j] - ptr[i];
|
||||
float n1 = d1.x*d1.x + d1.y*d1.y;
|
||||
|
||||
for(k = 0; k < j; ++k)
|
||||
{
|
||||
Point3f d2 = ptr[k] - ptr[i];
|
||||
float denom = (d2.x*d2.x + d2.y*d2.y)*n1;
|
||||
float num = d1.x*d2.x + d1.y*d2.y;
|
||||
|
||||
if( num*num > threshold*threshold*denom )
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
int cv::estimateAffine3D(InputArray _from, InputArray _to,
|
||||
OutputArray _out, OutputArray _inliers,
|
||||
double param1, double param2)
|
||||
{
|
||||
Mat from = _from.getMat(), to = _to.getMat();
|
||||
int count = from.checkVector(3);
|
||||
|
||||
CV_Assert( count >= 0 && to.checkVector(3) == count );
|
||||
|
||||
Mat dFrom, dTo;
|
||||
from.convertTo(dFrom, CV_32F);
|
||||
to.convertTo(dTo, CV_32F);
|
||||
dFrom = dFrom.reshape(3, count);
|
||||
dTo = dTo.reshape(3, count);
|
||||
|
||||
const double epsilon = DBL_EPSILON;
|
||||
param1 = param1 <= 0 ? 3 : param1;
|
||||
param2 = (param2 < epsilon) ? 0.99 : (param2 > 1 - epsilon) ? 0.99 : param2;
|
||||
|
||||
return createRANSACPointSetRegistrator(new Affine3DEstimatorCallback, 4, param1, param2)->run(dFrom, dTo, _out, _inliers);
|
||||
}
|
||||
|
@ -163,6 +163,8 @@ bool CV_Affine3D_EstTest::testNPoints()
|
||||
const double thres = 1e-4;
|
||||
if (norm(aff_est, aff, NORM_INF) > thres)
|
||||
{
|
||||
cout << "aff est: " << aff_est << endl;
|
||||
cout << "aff ref: " << aff << endl;
|
||||
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
|
||||
return false;
|
||||
}
|
||||
|
@ -1020,7 +1020,7 @@ void CV_FundamentalMatTest::prepare_to_validation( int test_case_idx )
|
||||
F0 *= 1./f0[8];
|
||||
|
||||
uchar* status = test_mat[TEMP][1].data;
|
||||
double err_level = get_success_error_level( test_case_idx, OUTPUT, 1 );
|
||||
double err_level = method <= CV_FM_8POINT ? 1 : get_success_error_level( test_case_idx, OUTPUT, 1 );
|
||||
uchar* mtfm1 = test_mat[REF_OUTPUT][1].data;
|
||||
uchar* mtfm2 = test_mat[OUTPUT][1].data;
|
||||
double* f_prop1 = (double*)test_mat[REF_OUTPUT][0].data;
|
||||
|
@ -40,6 +40,8 @@
|
||||
//M*/
|
||||
|
||||
#include "test_precomp.hpp"
|
||||
|
||||
#if 0
|
||||
#include "_modelest.h"
|
||||
|
||||
using namespace std;
|
||||
@ -225,3 +227,6 @@ void CV_ModelEstimator2_Test::run_func()
|
||||
}
|
||||
|
||||
TEST(Calib3d_ModelEstimator2, accuracy) { CV_ModelEstimator2_Test test; test.safe_run(); }
|
||||
|
||||
#endif
|
||||
|
||||
|
@ -1145,7 +1145,7 @@ Size _InputArray::size(int i) const
|
||||
const std::vector<uchar>& v = *(const std::vector<uchar>*)obj;
|
||||
const std::vector<int>& iv = *(const std::vector<int>*)obj;
|
||||
size_t szb = v.size(), szi = iv.size();
|
||||
return szb == szi ? Size((int)szb, 1) : Size((int)(szb/CV_ELEM_SIZE(flags)), 1);
|
||||
return szb == szi ? Size(1, (int)szb) : Size(1, (int)(szb/CV_ELEM_SIZE(flags)));
|
||||
}
|
||||
|
||||
if( k == NONE )
|
||||
@ -1155,19 +1155,19 @@ Size _InputArray::size(int i) const
|
||||
{
|
||||
const std::vector<std::vector<uchar> >& vv = *(const std::vector<std::vector<uchar> >*)obj;
|
||||
if( i < 0 )
|
||||
return vv.empty() ? Size() : Size((int)vv.size(), 1);
|
||||
return vv.empty() ? Size() : Size(1, (int)vv.size());
|
||||
CV_Assert( i < (int)vv.size() );
|
||||
const std::vector<std::vector<int> >& ivv = *(const std::vector<std::vector<int> >*)obj;
|
||||
|
||||
size_t szb = vv[i].size(), szi = ivv[i].size();
|
||||
return szb == szi ? Size((int)szb, 1) : Size((int)(szb/CV_ELEM_SIZE(flags)), 1);
|
||||
return szb == szi ? Size(1, (int)szb) : Size(1, (int)(szb/CV_ELEM_SIZE(flags)));
|
||||
}
|
||||
|
||||
if( k == STD_VECTOR_MAT )
|
||||
{
|
||||
const std::vector<Mat>& vv = *(const std::vector<Mat>*)obj;
|
||||
if( i < 0 )
|
||||
return vv.empty() ? Size() : Size((int)vv.size(), 1);
|
||||
return vv.empty() ? Size() : Size(1, (int)vv.size());
|
||||
CV_Assert( i < (int)vv.size() );
|
||||
|
||||
return vv[i].size();
|
||||
|
@ -487,7 +487,7 @@ bool CV_OperationsTest::TestSubMatAccess()
|
||||
coords.push_back(T_bs(i));
|
||||
//std::cout << T_bs1(i) << std::endl;
|
||||
}
|
||||
CV_Assert( norm(coords, T_bs.reshape(1,1), NORM_INF) == 0 );
|
||||
CV_Assert( norm(coords, T_bs.reshape(1,1).t(), NORM_INF) == 0 );
|
||||
}
|
||||
catch (const test_excep& e)
|
||||
{
|
||||
|
Loading…
Reference in New Issue
Block a user