]> rtime.felk.cvut.cz Git - opencv.git/blobdiff - opencv/src/cv/cvlkpyramid.cpp
renamed all the _[A-Z] variables to avoid possible name conflicts.
[opencv.git] / opencv / src / cv / cvlkpyramid.cpp
index fac3dee71d37010c64f53c79ab6d80370199fe2f..8b3bb932a5b8ce93462390c447c864428b8705fd 100644 (file)
 #include <float.h>
 #include <stdio.h>
 
+namespace cv
+{
+
+void calcOpticalFlowPyrLK( const Mat& prevImg, const Mat& nextImg,
+                           const vector<Point2f>& prevPts,
+                           vector<Point2f>& nextPts,
+                           vector<uchar>& status, vector<float>& err,
+                           Size winSize, int maxLevel,
+                           TermCriteria criteria,
+                           double derivLambda,
+                           int flags )
+{
+    derivLambda = std::min(std::max(derivLambda, 0.), 1.);
+    double lambda1 = 1. - derivLambda, lambda2 = derivLambda;
+    const int derivKernelSize = 3;
+    const float deriv1Scale = 0.5f/4.f;
+    const float deriv2Scale = 0.25f/4.f;
+    const int derivDepth = CV_32F;
+    Point2f halfWin((winSize.width-1)*0.5f, (winSize.height-1)*0.5f);
+
+    CV_Assert( maxLevel >= 0 && winSize.width > 2 && winSize.height > 2 );
+    CV_Assert( prevImg.size() == nextImg.size() &&
+        prevImg.type() == nextImg.type() );
+
+    size_t npoints = prevPts.size();
+    nextPts.resize(npoints);
+    status.resize(npoints);
+    for( size_t i = 0; i < npoints; i++ )
+        status[i] = true;
+    err.resize(npoints);
+
+    if( npoints == 0 )
+        return;
+    
+    vector<Mat> prevPyr, nextPyr;
+
+    int cn = prevImg.channels();
+    buildPyramid( prevImg, prevPyr, maxLevel );
+    buildPyramid( nextImg, nextPyr, maxLevel );
+    // I, dI/dx ~ Ix, dI/dy ~ Iy, d2I/dx2 ~ Ixx, d2I/dxdy ~ Ixy, d2I/dy2 ~ Iyy
+    Mat derivIBuf((prevImg.rows + winSize.height*2),
+                  (prevImg.cols + winSize.width*2),
+                  CV_MAKETYPE(derivDepth, cn*6));
+    // J, dJ/dx ~ Jx, dJ/dy ~ Jy
+    Mat derivJBuf((prevImg.rows + winSize.height*2),
+                  (prevImg.cols + winSize.width*2),
+                  CV_MAKETYPE(derivDepth, cn*3));
+    Mat tempDerivBuf(prevImg.size(), CV_MAKETYPE(derivIBuf.type(), cn));
+    Mat derivIWinBuf(winSize, derivIBuf.type());
+
+    if( (criteria.type & TermCriteria::COUNT) == 0 )
+        criteria.maxCount = 30;
+    else
+        criteria.maxCount = std::min(std::max(criteria.maxCount, 0), 100);
+    if( (criteria.type & TermCriteria::EPS) == 0 )
+        criteria.epsilon = 0.01;
+    else
+        criteria.epsilon = std::min(std::max(criteria.epsilon, 0.), 10.);
+    criteria.epsilon *= criteria.epsilon;
+
+    for( int level = maxLevel; level >= 0; level-- )
+    {
+        int k;
+        Size imgSize = prevPyr[level].size();
+        Mat tempDeriv( imgSize, tempDerivBuf.type(), tempDerivBuf.data );
+        Mat _derivI( imgSize.height + winSize.height*2,
+            imgSize.width + winSize.width*2,
+            derivIBuf.type(), derivIBuf.data );
+        Mat _derivJ( imgSize.height + winSize.height*2,
+            imgSize.width + winSize.width*2,
+            derivJBuf.type(), derivJBuf.data );
+        Mat derivI(_derivI, Rect(winSize.width, winSize.height, imgSize.width, imgSize.height));
+        Mat derivJ(_derivJ, Rect(winSize.width, winSize.height, imgSize.width, imgSize.height));
+        CvMat cvderivI = _derivI;
+        cvZero(&cvderivI);
+        CvMat cvderivJ = _derivJ;
+        cvZero(&cvderivJ);
+
+        vector<int> fromTo(cn*2);
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2] = k;
+
+        prevPyr[level].convertTo(tempDeriv, derivDepth);
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        // compute spatial derivatives and merge them together
+        Sobel(prevPyr[level], tempDeriv, derivDepth, 1, 0, derivKernelSize, deriv1Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6 + 1;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        Sobel(prevPyr[level], tempDeriv, derivDepth, 0, 1, derivKernelSize, deriv1Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6 + 2;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        Sobel(prevPyr[level], tempDeriv, derivDepth, 2, 0, derivKernelSize, deriv2Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6 + 3;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        Sobel(prevPyr[level], tempDeriv, derivDepth, 1, 1, derivKernelSize, deriv2Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6 + 4;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        Sobel(prevPyr[level], tempDeriv, derivDepth, 0, 2, derivKernelSize, deriv2Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*6 + 5;
+        mixChannels(&tempDeriv, 1, &derivI, 1, &fromTo[0], cn);
+
+        nextPyr[level].convertTo(tempDeriv, derivDepth);
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*3;
+        mixChannels(&tempDeriv, 1, &derivJ, 1, &fromTo[0], cn);
+
+        Sobel(nextPyr[level], tempDeriv, derivDepth, 1, 0, derivKernelSize, deriv1Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*3 + 1;
+        mixChannels(&tempDeriv, 1, &derivJ, 1, &fromTo[0], cn);
+
+        Sobel(nextPyr[level], tempDeriv, derivDepth, 0, 1, derivKernelSize, deriv1Scale );
+        for( k = 0; k < cn; k++ )
+            fromTo[k*2+1] = k*3 + 2;
+        mixChannels(&tempDeriv, 1, &derivJ, 1, &fromTo[0], cn);
+
+        /*copyMakeBorder( derivI, _derivI, winSize.height, winSize.height,
+            winSize.width, winSize.width, BORDER_CONSTANT );
+        copyMakeBorder( derivJ, _derivJ, winSize.height, winSize.height,
+            winSize.width, winSize.width, BORDER_CONSTANT );*/
+
+        for( size_t ptidx = 0; ptidx < npoints; ptidx++ )
+        {
+            Point2f prevPt = prevPts[ptidx]*(float)(1./(1 << level));
+            Point2f nextPt;
+            if( level == maxLevel )
+            {
+                if( flags & OPTFLOW_USE_INITIAL_FLOW )
+                    nextPt = nextPts[ptidx]*(float)(1./(1 << level));
+                else
+                    nextPt = prevPt;
+            }
+            else
+                nextPt = nextPts[ptidx]*2.f;
+            nextPts[ptidx] = nextPt;
+            
+            Point2i iprevPt, inextPt;
+            prevPt -= halfWin;
+            iprevPt.x = cvFloor(prevPt.x);
+            iprevPt.y = cvFloor(prevPt.y);
+
+            if( iprevPt.x < -winSize.width || iprevPt.x >= derivI.cols ||
+                iprevPt.y < -winSize.height || iprevPt.y >= derivI.rows )
+            {
+                if( level == 0 )
+                {
+                    status[ptidx] = false;
+                    err[ptidx] = FLT_MAX;
+                }
+                continue;
+            }
+            
+            float a = prevPt.x - iprevPt.x;
+            float b = prevPt.y - iprevPt.y;
+            float w00 = (1.f - a)*(1.f - b), w01 = a*(1.f - b);
+            float w10 = (1.f - a)*b, w11 = a*b;
+            size_t stepI = derivI.step/derivI.elemSize1();
+            size_t stepJ = derivJ.step/derivJ.elemSize1();
+            int cnI = cn*6, cnJ = cn*3;
+            double A11 = 0, A12 = 0, A22 = 0;
+            double iA11 = 0, iA12 = 0, iA22 = 0;
+            
+            // extract the patch from the first image
+            int x, y;
+            for( y = 0; y < winSize.height; y++ )
+            {
+                const float* src = (const float*)(derivI.data +
+                    (y + iprevPt.y)*derivI.step) + iprevPt.x*cnI;
+                float* dst = (float*)(derivIWinBuf.data + y*derivIWinBuf.step);
+
+                for( x = 0; x < winSize.width*cnI; x += cnI, src += cnI )
+                {
+                    float I = src[0]*w00 + src[cnI]*w01 + src[stepI]*w10 + src[stepI+cnI]*w11;
+                    dst[x] = I;
+                    
+                    float Ix = src[1]*w00 + src[cnI+1]*w01 + src[stepI+1]*w10 + src[stepI+cnI+1]*w11;
+                    float Iy = src[2]*w00 + src[cnI+2]*w01 + src[stepI+2]*w10 + src[stepI+cnI+2]*w11;
+                    dst[x+1] = Ix; dst[x+2] = Iy;
+                    
+                    float Ixx = src[3]*w00 + src[cnI+3]*w01 + src[stepI+3]*w10 + src[stepI+cnI+3]*w11;
+                    float Ixy = src[4]*w00 + src[cnI+4]*w01 + src[stepI+4]*w10 + src[stepI+cnI+4]*w11;
+                    float Iyy = src[5]*w00 + src[cnI+5]*w01 + src[stepI+5]*w10 + src[stepI+cnI+5]*w11;
+                    dst[x+3] = Ixx; dst[x+4] = Ixy; dst[x+5] = Iyy;
+
+                    iA11 += (double)Ix*Ix;
+                    iA12 += (double)Ix*Iy;
+                    iA22 += (double)Iy*Iy;
+
+                    A11 += (double)Ixx*Ixx + (double)Ixy*Ixy;
+                    A12 += Ixy*((double)Ixx + Iyy);
+                    A22 += (double)Ixy*Ixy + (double)Iyy*Iyy;
+                }
+            }
+
+            A11 = lambda1*iA11 + lambda2*A11;
+            A12 = lambda1*iA12 + lambda2*A12;
+            A22 = lambda1*iA22 + lambda2*A22;
+
+            double D = A11*A22 - A12*A12;
+            double minEig = (A22 + A11 - std::sqrt((A11-A22)*(A11-A22) +
+                4.*A12*A12))/(2*winSize.width*winSize.height);
+            err[ptidx] = (float)minEig;
+
+            if( D < DBL_EPSILON )
+            {
+                if( level == 0 )
+                    status[ptidx] = false;
+                continue;
+            }
+            
+            D = 1./D;
+
+            nextPt -= halfWin;
+            Point2f prevDelta;
+
+            for( int j = 0; j < criteria.maxCount; j++ )
+            {
+                inextPt.x = cvFloor(nextPt.x);
+                inextPt.y = cvFloor(nextPt.y);
+
+                if( inextPt.x < -winSize.width || inextPt.x >= derivJ.cols ||
+                    inextPt.y < -winSize.height || inextPt.y >= derivJ.rows )
+                {
+                    if( level == 0 )
+                        status[ptidx] = false;
+                    break;
+                }
+
+                a = nextPt.x - inextPt.x;
+                b = nextPt.y - inextPt.y;
+                w00 = (1.f - a)*(1.f - b); w01 = a*(1.f - b);
+                w10 = (1.f - a)*b; w11 = a*b;
+
+                double b1 = 0, b2 = 0, ib1 = 0, ib2 = 0;
+
+                for( y = 0; y < winSize.height; y++ )
+                {
+                    const float* src = (const float*)(derivJ.data +
+                        (y + inextPt.y)*derivJ.step) + inextPt.x*cnJ;
+                    const float* Ibuf = (float*)(derivIWinBuf.data + y*derivIWinBuf.step);
+
+                    for( x = 0; x < winSize.width; x++, src += cnJ, Ibuf += cnI )
+                    {
+                        double It = src[0]*w00 + src[cnJ]*w01 + src[stepJ]*w10 +
+                                    src[stepJ+cnJ]*w11 - Ibuf[0];
+                        double Ixt = src[1]*w00 + src[cnJ+1]*w01 + src[stepJ+1]*w10 +
+                                     src[stepJ+cnJ+1]*w11 - Ibuf[1];
+                        double Iyt = src[2]*w00 + src[cnJ+2]*w01 + src[stepJ+2]*w10 +
+                                     src[stepJ+cnJ+2]*w11 - Ibuf[2];
+                        b1 += Ixt*Ibuf[3] + Iyt*Ibuf[4];
+                        b2 += Ixt*Ibuf[4] + Iyt*Ibuf[5];
+                        ib1 += It*Ibuf[1];
+                        ib2 += It*Ibuf[2];
+                    }
+                }
+
+                b1 = lambda1*ib1 + lambda2*b1;
+                b2 = lambda1*ib2 + lambda2*b2;
+                Point2f delta( (float)((A12*b2 - A22*b1) * D),
+                               (float)((A12*b1 - A11*b2) * D));
+                //delta = -delta;
+
+                nextPt += delta;
+                nextPts[ptidx] = nextPt + halfWin;
+
+                if( delta.ddot(delta) <= criteria.epsilon )
+                    break;
+
+                if( j > 0 && std::abs(delta.x + prevDelta.x) < 0.01 &&
+                    std::abs(delta.y + prevDelta.y) < 0.01 )
+                {
+                    nextPts[ptidx] -= delta*0.5f;
+                    break;
+                }
+                prevDelta = delta;
+            }
+        }
+    }
+}
+
+}
+
 static void
 intersect( CvPoint2D32f pt, CvSize win_size, CvSize imgSize,
            CvPoint* min_pt, CvPoint* max_pt )
@@ -77,12 +371,8 @@ icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
                            int max_iters, int flags,
                            uchar *** imgI, uchar *** imgJ,
                            int **step, CvSize** size,
-                           double **scale, uchar ** buffer )
+                           double **scale, cv::AutoBuffer<uchar>* buffer )
 {
-    CV_FUNCNAME( "icvInitPyramidalAlgorithm" );
-
-    __BEGIN__;
-
     const int ALIGN = 8;
     int pyrBytes, bufferBytes = 0, elem_size;
     int level1 = level + 1;
@@ -90,19 +380,18 @@ icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
     int i;
     CvSize imgSize, levelSize;
 
-    *buffer = 0;
     *imgI = *imgJ = 0;
     *step = 0;
     *scale = 0;
     *size = 0;
 
     /* check input arguments */
-    if( (flags & CV_LKFLOW_PYR_A_READY) != 0 && !pyrA ||
-        (flags & CV_LKFLOW_PYR_B_READY) != 0 && !pyrB )
-        CV_ERROR( CV_StsNullPtr, "Some of the precomputed pyramids are missing" );
+    if( ((flags & CV_LKFLOW_PYR_A_READY) != 0 && !pyrA) ||
+        ((flags & CV_LKFLOW_PYR_B_READY) != 0 && !pyrB) )
+        CV_Error( CV_StsNullPtr, "Some of the precomputed pyramids are missing" );
 
     if( level < 0 )
-        CV_ERROR( CV_StsOutOfRange, "The number of pyramid layers is negative" );
+        CV_Error( CV_StsOutOfRange, "The number of pyramid levels is negative" );
 
     switch( criteria->type )
     {
@@ -116,7 +405,7 @@ icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
         break;
     default:
         assert( 0 );
-        CV_ERROR( CV_StsBadArg, "Invalid termination criteria" );
+        CV_Error( CV_StsBadArg, "Invalid termination criteria" );
     }
 
     /* compare squared values */
@@ -146,9 +435,9 @@ icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
         (sizeof(imgI[0][0]) * 2 + sizeof(step[0][0]) +
          sizeof(size[0][0]) + sizeof(scale[0][0])) * level1);
 
-    CV_CALL( *buffer = (uchar *)cvAlloc( bufferBytes ));
+    buffer->allocate( bufferBytes );
 
-    *imgI = (uchar **) buffer[0];
+    *imgI = (uchar **) (uchar*)(*buffer);
     *imgJ = *imgI + level1;
     *step = (int *) (*imgJ + level1);
     *scale = (double *) (*step + level1);
@@ -216,8 +505,6 @@ icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
             }
         }
     }
-
-    __END__;
 }
 
 
@@ -255,196 +542,50 @@ icvCalcIxIy_32f( const float* src, int src_step, float* dstX, float* dstY, int d
 }
 
 
-icvOpticalFlowPyrLKInitAlloc_8u_C1R_t icvOpticalFlowPyrLKInitAlloc_8u_C1R_p = 0;
-icvOpticalFlowPyrLKFree_8u_C1R_t icvOpticalFlowPyrLKFree_8u_C1R_p = 0;
-icvOpticalFlowPyrLK_8u_C1R_t icvOpticalFlowPyrLK_8u_C1R_p = 0;
-
-
-CV_IMPL void
-cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
-                        void* pyrarrA, void* pyrarrB,
-                        const CvPoint2D32f * featuresA,
-                        CvPoint2D32f * featuresB,
-                        int count, CvSize winSize, int level,
-                        char *status, float *error,
-                        CvTermCriteria criteria, int flags )
+namespace cv
 {
-    uchar *pyrBuffer = 0;
-    uchar *buffer = 0;
-    float* _error = 0;
-    char* _status = 0;
-
-    void* ipp_optflow_state = 0;
-    
-    CV_FUNCNAME( "cvCalcOpticalFlowPyrLK" );
-
-    __BEGIN__;
-
-    const int MAX_ITERS = 100;
-
-    CvMat stubA, *imgA = (CvMat*)arrA;
-    CvMat stubB, *imgB = (CvMat*)arrB;
-    CvMat pstubA, *pyrA = (CvMat*)pyrarrA;
-    CvMat pstubB, *pyrB = (CvMat*)pyrarrB;
-    CvSize imgSize;
-    static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 };  /* 3/32, 10/32, 3/32 */
-    
-    int bufferBytes = 0;
-    uchar **imgI = 0;
-    uchar **imgJ = 0;
-    int *step = 0;
-    double *scale = 0;
-    CvSize* size = 0;
-
-    int threadCount = cvGetNumThreads();
-    float* _patchI[CV_MAX_THREADS];
-    float* _patchJ[CV_MAX_THREADS];
-    float* _Ix[CV_MAX_THREADS];
-    float* _Iy[CV_MAX_THREADS];
-
-    int i, l;
-
-    CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 );
-    int patchLen = patchSize.width * patchSize.height;
-    int srcPatchLen = (patchSize.width + 2)*(patchSize.height + 2);
-
-    CV_CALL( imgA = cvGetMat( imgA, &stubA ));
-    CV_CALL( imgB = cvGetMat( imgB, &stubB ));
-
-    if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
-        CV_ERROR( CV_StsUnsupportedFormat, "" );
-
-    if( !CV_ARE_TYPES_EQ( imgA, imgB ))
-        CV_ERROR( CV_StsUnmatchedFormats, "" );
-
-    if( !CV_ARE_SIZES_EQ( imgA, imgB ))
-        CV_ERROR( CV_StsUnmatchedSizes, "" );
-
-    if( imgA->step != imgB->step )
-        CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
-
-    imgSize = cvGetMatSize( imgA );
-
-    if( pyrA )
-    {
-        CV_CALL( pyrA = cvGetMat( pyrA, &pstubA ));
-
-        if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
-            CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" );
-    }
-    else
-    {
-        pyrA = &pstubA;
-        pyrA->data.ptr = 0;
-    }
-
-    if( pyrB )
-    {
-        CV_CALL( pyrB = cvGetMat( pyrB, &pstubB ));
-
-        if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
-            CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" );
-    }
-    else
-    {
-        pyrB = &pstubB;
-        pyrB->data.ptr = 0;
-    }
-
-    if( count == 0 )
-        EXIT;
-
-    if( !featuresA || !featuresB )
-        CV_ERROR( CV_StsNullPtr, "Some of arrays of point coordinates are missing" );
-
-    if( count < 0 )
-        CV_ERROR( CV_StsOutOfRange, "The number of tracked points is negative or zero" );
-
-    if( winSize.width <= 1 || winSize.height <= 1 )
-        CV_ERROR( CV_StsBadSize, "Invalid search window size" );
-
-    for( i = 0; i < threadCount; i++ )
-        _patchI[i] = _patchJ[i] = _Ix[i] = _Iy[i] = 0;
-
-    CV_CALL( icvInitPyramidalAlgorithm( imgA, imgB, pyrA, pyrB,
-        level, &criteria, MAX_ITERS, flags,
-        &imgI, &imgJ, &step, &size, &scale, &pyrBuffer ));
-
-    if( !status )
-        CV_CALL( status = _status = (char*)cvAlloc( count*sizeof(_status[0]) ));
-
-#if 0
-    if( icvOpticalFlowPyrLKInitAlloc_8u_C1R_p &&
-        icvOpticalFlowPyrLKFree_8u_C1R_p &&
-        icvOpticalFlowPyrLK_8u_C1R_p &&
-        winSize.width == winSize.height &&
-        icvOpticalFlowPyrLKInitAlloc_8u_C1R_p( &ipp_optflow_state, imgSize,
-                                               winSize.width*2+1, cvAlgHintAccurate ) >= 0 )
-    {
-        CvPyramid ipp_pyrA, ipp_pyrB;
-        static const double rate[] = { 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125,
-                                       0.00390625, 0.001953125, 0.0009765625, 0.00048828125, 0.000244140625,
-                                       0.0001220703125 };
-        // initialize pyramid structures
-        assert( level < 14 );
-        ipp_pyrA.ptr = imgI;
-        ipp_pyrB.ptr = imgJ;
-        ipp_pyrA.sz = ipp_pyrB.sz = size;
-        ipp_pyrA.rate = ipp_pyrB.rate = (double*)rate;
-        ipp_pyrA.step = ipp_pyrB.step = step;
-        ipp_pyrA.state = ipp_pyrB.state = 0;
-        ipp_pyrA.level = ipp_pyrB.level = level;
-
-        if( !error )
-            CV_CALL( error = _error = (float*)cvAlloc( count*sizeof(_error[0]) ));
-
-        for( i = 0; i < count; i++ )
-            featuresB[i] = featuresA[i];
-
-        if( icvOpticalFlowPyrLK_8u_C1R_p( &ipp_pyrA, &ipp_pyrB,
-            (const float*)featuresA, (float*)featuresB, status, error, count,
-            winSize.width*2 + 1, level, criteria.max_iter,
-            (float)criteria.epsilon, ipp_optflow_state ) >= 0 )
-        {
-            for( i = 0; i < count; i++ )
-                status[i] = status[i] == 0;
-            EXIT;
-        }
-    }
-#endif
 
-    /* buffer_size = <size for patches> + <size for pyramids> */
-    bufferBytes = (srcPatchLen + patchLen * 3) * sizeof( _patchI[0][0] ) * threadCount;
-    CV_CALL( buffer = (uchar*)cvAlloc( bufferBytes ));
-
-    for( i = 0; i < threadCount; i++ )
+struct LKTrackerInvoker
+{
+    LKTrackerInvoker( const CvMat* _imgI, const CvMat* _imgJ,
+                      const CvPoint2D32f* _featuresA,
+                      CvPoint2D32f* _featuresB,
+                      char* _status, float* _error,
+                      CvTermCriteria _criteria,
+                      CvSize _winSize, int _level, int _flags )
     {
-        _patchI[i] = i == 0 ? (float*)buffer : _Iy[i-1] + patchLen;
-        _patchJ[i] = _patchI[i] + srcPatchLen;
-        _Ix[i] = _patchJ[i] + patchLen;
-        _Iy[i] = _Ix[i] + patchLen;
+        imgI = _imgI;
+        imgJ = _imgJ;
+        featuresA = _featuresA;
+        featuresB = _featuresB;
+        status = _status;
+        error = _error;
+        criteria = _criteria;
+        winSize = _winSize;
+        level = _level;
+        flags = _flags;
     }
-
-    memset( status, 1, count );
-    if( error )
-        memset( error, 0, count*sizeof(error[0]) );
-
-    if( !(flags & CV_LKFLOW_INITIAL_GUESSES) )
-        memcpy( featuresB, featuresA, count*sizeof(featuresA[0]));
-
-    /* do processing from top pyramid level (smallest image)
-       to the bottom (original image) */
-    for( l = level; l >= 0; l-- )
+    
+    void operator()(const BlockedRange& range) const
     {
-        CvSize levelSize = size[l];
-        int levelStep = step[l];
-
-        {
-#ifdef _OPENMP
-        #pragma omp parallel for num_threads(threadCount), schedule(dynamic) 
-#endif // _OPENMP
-        /* find flow for each given point */
-        for( i = 0; i < count; i++ )
+        static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 };  // 3/32, 10/32, 3/32
+        
+        int i, i1 = range.begin(), i2 = range.end();
+        
+        CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 );
+        int patchLen = patchSize.width * patchSize.height;
+        int srcPatchLen = (patchSize.width + 2)*(patchSize.height + 2);
+        
+        AutoBuffer<float> buf(patchLen*3 + srcPatchLen);
+        float* patchI = buf;
+        float* patchJ = patchI + srcPatchLen;
+        float* Ix = patchJ + patchLen;
+        float* Iy = Ix + patchLen;
+        float scaleL = 1.f/(1 << level);
+        CvSize levelSize = cvGetMatSize(imgI);
+        
+        // find flow for each given point
+        for( i = i1; i < i2; i++ )
         {
             CvPoint2D32f v;
             CvPoint minI, maxI, minJ, maxJ;
@@ -452,94 +593,79 @@ cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
             int pt_status;
             CvPoint2D32f u;
             CvPoint prev_minJ = { -1, -1 }, prev_maxJ = { -1, -1 };
-            double Gxx = 0, Gxy = 0, Gyy = 0, D = 0;
+            double Gxx = 0, Gxy = 0, Gyy = 0, D = 0, minEig = 0;
             float prev_mx = 0, prev_my = 0;
             int j, x, y;
-            int threadIdx = cvGetThreadNum();
-            float* patchI = _patchI[threadIdx];
-            float* patchJ = _patchJ[threadIdx];
-            float* Ix = _Ix[threadIdx];
-            float* Iy = _Iy[threadIdx];
-
-            v.x = featuresB[i].x;
-            v.y = featuresB[i].y;
-            if( l < level )
-            {
-                v.x += v.x;
-                v.y += v.y;
-            }
-            else
-            {
-                v.x = (float)(v.x * scale[l]);
-                v.y = (float)(v.y * scale[l]);
-            }
-
+            
+            v.x = featuresB[i].x*2;
+            v.y = featuresB[i].y*2;
+            
             pt_status = status[i];
             if( !pt_status )
                 continue;
-
-            minI = maxI = minJ = maxJ = cvPoint( 0, 0 );
-
-            u.x = (float) (featuresA[i].x * scale[l]);
-            u.y = (float) (featuresA[i].y * scale[l]);
-
+            
+            minI = maxI = minJ = maxJ = cvPoint(0, 0);
+            
+            u.x = featuresA[i].x * scaleL;
+            u.y = featuresA[i].y * scaleL;
+            
             intersect( u, winSize, levelSize, &minI, &maxI );
             isz = jsz = cvSize(maxI.x - minI.x + 2, maxI.y - minI.y + 2);
             u.x += (minI.x - (patchSize.width - maxI.x + 1))*0.5f;
             u.y += (minI.y - (patchSize.height - maxI.y + 1))*0.5f;
-
+            
             if( isz.width < 3 || isz.height < 3 ||
-                icvGetRectSubPix_8u32f_C1R( imgI[l], levelStep, levelSize,
-                    patchI, isz.width*sizeof(patchI[0]), isz, u ) < 0 )
+                icvGetRectSubPix_8u32f_C1R( imgI->data.ptr, imgI->step, levelSize,
+                                            patchI, isz.width*sizeof(patchI[0]), isz, u ) < 0 )
             {
-                /* point is outside the image. take the next */
+                // point is outside the first image. take the next
                 status[i] = 0;
                 continue;
             }
-
+            
             icvCalcIxIy_32f( patchI, isz.width*sizeof(patchI[0]), Ix, Iy,
-                (isz.width-2)*sizeof(patchI[0]), isz, smoothKernel, patchJ );
-
+                             (isz.width-2)*sizeof(patchI[0]), isz, smoothKernel, patchJ );
+            
             for( j = 0; j < criteria.max_iter; j++ )
             {
                 double bx = 0, by = 0;
                 float mx, my;
                 CvPoint2D32f _v;
-
+                
                 intersect( v, winSize, levelSize, &minJ, &maxJ );
-
+                
                 minJ.x = MAX( minJ.x, minI.x );
                 minJ.y = MAX( minJ.y, minI.y );
-
+                
                 maxJ.x = MIN( maxJ.x, maxI.x );
                 maxJ.y = MIN( maxJ.y, maxI.y );
-
+                
                 jsz = cvSize(maxJ.x - minJ.x, maxJ.y - minJ.y);
-
+                
                 _v.x = v.x + (minJ.x - (patchSize.width - maxJ.x + 1))*0.5f;
                 _v.y = v.y + (minJ.y - (patchSize.height - maxJ.y + 1))*0.5f;
-
+                
                 if( jsz.width < 1 || jsz.height < 1 ||
-                    icvGetRectSubPix_8u32f_C1R( imgJ[l], levelStep, levelSize, patchJ,
+                    icvGetRectSubPix_8u32f_C1R( imgJ->data.ptr, imgJ->step, levelSize, patchJ,
                                                 jsz.width*sizeof(patchJ[0]), jsz, _v ) < 0 )
                 {
-                    /* point is outside image. take the next */
+                    // point is outside of the second image. take the next
                     pt_status = 0;
                     break;
                 }
-
+                
                 if( maxJ.x == prev_maxJ.x && maxJ.y == prev_maxJ.y &&
                     minJ.x == prev_minJ.x && minJ.y == prev_minJ.y )
                 {
                     for( y = 0; y < jsz.height; y++ )
                     {
                         const float* pi = patchI +
-                            (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
+                        (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
                         const float* pj = patchJ + y*jsz.width;
                         const float* ix = Ix +
-                            (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
+                        (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
                         const float* iy = Iy + (ix - Ix);
-
+                        
                         for( x = 0; x < jsz.width; x++ )
                         {
                             double t0 = pi[x] - pj[x];
@@ -554,12 +680,12 @@ cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
                     for( y = 0; y < jsz.height; y++ )
                     {
                         const float* pi = patchI +
-                            (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
+                        (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
                         const float* pj = patchJ + y*jsz.width;
                         const float* ix = Ix +
-                            (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
+                        (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
                         const float* iy = Iy + (ix - Ix);
-
+                        
                         for( x = 0; x < jsz.width; x++ )
                         {
                             double t = pi[x] - pj[x];
@@ -570,28 +696,33 @@ cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
                             Gyy += iy[x] * iy[x];
                         }
                     }
-
+                    
                     D = Gxx * Gyy - Gxy * Gxy;
                     if( D < DBL_EPSILON )
                     {
                         pt_status = 0;
                         break;
                     }
+                    
+                    // Adi Shavit - 2008.05
+                    if( flags & CV_LKFLOW_GET_MIN_EIGENVALS )
+                        minEig = (Gyy + Gxx - sqrt((Gxx-Gyy)*(Gxx-Gyy) + 4.*Gxy*Gxy))/(2*jsz.height*jsz.width);
+                        
                     D = 1. / D;
-
+                        
                     prev_minJ = minJ;
                     prev_maxJ = maxJ;
                 }
-
+                
                 mx = (float) ((Gyy * bx - Gxy * by) * D);
                 my = (float) ((Gxx * by - Gxy * bx) * D);
-
+                
                 v.x += mx;
                 v.y += my;
-
+                
                 if( mx * mx + my * my < criteria.epsilon )
                     break;
-
+                
                 if( j > 0 && fabs(mx + prev_mx) < 0.01 && fabs(my + prev_my) < 0.01 )
                 {
                     v.x -= mx*0.5f;
@@ -601,41 +732,172 @@ cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
                 prev_mx = mx;
                 prev_my = my;
             }
-
+            
             featuresB[i] = v;
             status[i] = (char)pt_status;
-            if( l == 0 && error && pt_status )
+            if( level == 0 && error && pt_status )
             {
-                /* calc error */
+                // calc error
                 double err = 0;
-
-                for( y = 0; y < jsz.height; y++ )
+                if( flags & CV_LKFLOW_GET_MIN_EIGENVALS )
+                    err = minEig;
+                else
                 {
-                    const float* pi = patchI +
-                        (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
-                    const float* pj = patchJ + y*jsz.width;
-
-                    for( x = 0; x < jsz.width; x++ )
+                    for( y = 0; y < jsz.height; y++ )
                     {
-                        double t = pi[x] - pj[x];
-                        err += t * t;
+                        const float* pi = patchI +
+                        (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
+                        const float* pj = patchJ + y*jsz.width;
+                        
+                        for( x = 0; x < jsz.width; x++ )
+                        {
+                            double t = pi[x] - pj[x];
+                            err += t * t;
+                        }
                     }
+                    err = sqrt(err);
                 }
-                error[i] = (float)sqrt(err);
+                error[i] = (float)err;
             }
         } // end of point processing loop (i)
-        }
-    } // end of pyramid levels loop (l)
+    }
+    
+    const CvMat* imgI;
+    const CvMat* imgJ;
+    const CvPoint2D32f* featuresA;
+    CvPoint2D32f* featuresB;
+    char* status;
+    float* error;
+    CvTermCriteria criteria;
+    CvSize winSize;
+    int level;
+    int flags;
+};
+    
+    
+}
 
-    __END__;
 
-    if( ipp_optflow_state )
-        icvOpticalFlowPyrLKFree_8u_C1R_p( ipp_optflow_state );
+CV_IMPL void
+cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
+                        void* pyrarrA, void* pyrarrB,
+                        const CvPoint2D32f * featuresA,
+                        CvPoint2D32f * featuresB,
+                        int count, CvSize winSize, int level,
+                        char *status, float *error,
+                        CvTermCriteria criteria, int flags )
+{
+    cv::AutoBuffer<uchar> pyrBuffer;
+    cv::AutoBuffer<uchar> buffer;
+    cv::AutoBuffer<char> _status;
+
+    const int MAX_ITERS = 100;
 
-    cvFree( &pyrBuffer );
-    cvFree( &buffer );
-    cvFree( &_error );
-    cvFree( &_status );
+    CvMat stubA, *imgA = (CvMat*)arrA;
+    CvMat stubB, *imgB = (CvMat*)arrB;
+    CvMat pstubA, *pyrA = (CvMat*)pyrarrA;
+    CvMat pstubB, *pyrB = (CvMat*)pyrarrB;
+    CvSize imgSize;
+    
+    uchar **imgI = 0;
+    uchar **imgJ = 0;
+    int *step = 0;
+    double *scale = 0;
+    CvSize* size = 0;
+
+    int i, l;
+
+    imgA = cvGetMat( imgA, &stubA );
+    imgB = cvGetMat( imgB, &stubB );
+
+    if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
+        CV_Error( CV_StsUnsupportedFormat, "" );
+
+    if( !CV_ARE_TYPES_EQ( imgA, imgB ))
+        CV_Error( CV_StsUnmatchedFormats, "" );
+
+    if( !CV_ARE_SIZES_EQ( imgA, imgB ))
+        CV_Error( CV_StsUnmatchedSizes, "" );
+
+    if( imgA->step != imgB->step )
+        CV_Error( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
+
+    imgSize = cvGetMatSize( imgA );
+
+    if( pyrA )
+    {
+        pyrA = cvGetMat( pyrA, &pstubA );
+
+        if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
+            CV_Error( CV_StsBadArg, "pyramid A has insufficient size" );
+    }
+    else
+    {
+        pyrA = &pstubA;
+        pyrA->data.ptr = 0;
+    }
+
+    if( pyrB )
+    {
+        pyrB = cvGetMat( pyrB, &pstubB );
+
+        if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
+            CV_Error( CV_StsBadArg, "pyramid B has insufficient size" );
+    }
+    else
+    {
+        pyrB = &pstubB;
+        pyrB->data.ptr = 0;
+    }
+
+    if( count == 0 )
+        return;
+
+    if( !featuresA || !featuresB )
+        CV_Error( CV_StsNullPtr, "Some of arrays of point coordinates are missing" );
+
+    if( count < 0 )
+        CV_Error( CV_StsOutOfRange, "The number of tracked points is negative or zero" );
+
+    if( winSize.width <= 1 || winSize.height <= 1 )
+        CV_Error( CV_StsBadSize, "Invalid search window size" );
+
+    icvInitPyramidalAlgorithm( imgA, imgB, pyrA, pyrB,
+        level, &criteria, MAX_ITERS, flags,
+        &imgI, &imgJ, &step, &size, &scale, &pyrBuffer );
+
+    if( !status )
+    {
+        _status.allocate(count);
+        status = _status;
+    }
+
+    memset( status, 1, count );
+    if( error )
+        memset( error, 0, count*sizeof(error[0]) );
+
+    if( !(flags & CV_LKFLOW_INITIAL_GUESSES) )
+        memcpy( featuresB, featuresA, count*sizeof(featuresA[0]));
+    
+    for( i = 0; i < count; i++ )
+    {
+        featuresB[i].x = (float)(featuresB[i].x * scale[level] * 0.5);
+        featuresB[i].y = (float)(featuresB[i].y * scale[level] * 0.5);
+    }
+
+    /* do processing from top pyramid level (smallest image)
+       to the bottom (original image) */
+    for( l = level; l >= 0; l-- )
+    {
+        CvMat imgI_l, imgJ_l;        
+        cvInitMatHeader(&imgI_l, size[l].height, size[l].width, imgA->type, imgI[l], step[l]);
+        cvInitMatHeader(&imgJ_l, size[l].height, size[l].width, imgB->type, imgJ[l], step[l]);
+        
+        cv::parallel_for(cv::BlockedRange(0, count),
+                         cv::LKTrackerInvoker(&imgI_l, &imgJ_l, featuresA,
+                                              featuresB, status, error,
+                                              criteria, winSize, l, flags));
+    } // end of pyramid levels loop (l)
 }
 
 
@@ -653,13 +915,9 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
 {
     const int MAX_ITERS = 100;
 
-    char* _status = 0;
-    uchar *buffer = 0;
-    uchar *pyr_buffer = 0;
-
-    CV_FUNCNAME( "cvCalcAffineFlowPyrLK" );
-
-    __BEGIN__;
+    cv::AutoBuffer<char> _status;
+    cv::AutoBuffer<uchar> buffer;
+    cv::AutoBuffer<uchar> pyr_buffer;
 
     CvMat stubA, *imgA = (CvMat*)arrA;
     CvMat stubB, *imgB = (CvMat*)arrB;
@@ -693,32 +951,32 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
     CvSize imgSize;
     float eps = (float)MIN(winSize.width, winSize.height);
 
-    CV_CALL( imgA = cvGetMat( imgA, &stubA ));
-    CV_CALL( imgB = cvGetMat( imgB, &stubB ));
+    imgA = cvGetMat( imgA, &stubA );
+    imgB = cvGetMat( imgB, &stubB );
 
     if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
-        CV_ERROR( CV_StsUnsupportedFormat, "" );
+        CV_Error( CV_StsUnsupportedFormat, "" );
 
     if( !CV_ARE_TYPES_EQ( imgA, imgB ))
-        CV_ERROR( CV_StsUnmatchedFormats, "" );
+        CV_Error( CV_StsUnmatchedFormats, "" );
 
     if( !CV_ARE_SIZES_EQ( imgA, imgB ))
-        CV_ERROR( CV_StsUnmatchedSizes, "" );
+        CV_Error( CV_StsUnmatchedSizes, "" );
 
     if( imgA->step != imgB->step )
-        CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
+        CV_Error( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
 
     if( !matrices )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     imgSize = cvGetMatSize( imgA );
 
     if( pyrA )
     {
-        CV_CALL( pyrA = cvGetMat( pyrA, &pstubA ));
+        pyrA = cvGetMat( pyrA, &pstubA );
 
         if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
-            CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" );
+            CV_Error( CV_StsBadArg, "pyramid A has insufficient size" );
     }
     else
     {
@@ -728,10 +986,10 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
 
     if( pyrB )
     {
-        CV_CALL( pyrB = cvGetMat( pyrB, &pstubB ));
+        pyrB = cvGetMat( pyrB, &pstubB );
 
         if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
-            CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" );
+            CV_Error( CV_StsBadArg, "pyramid B has insufficient size" );
     }
     else
     {
@@ -740,31 +998,34 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
     }
 
     if( count == 0 )
-        EXIT;
+        return;
 
     /* check input arguments */
     if( !featuresA || !featuresB || !matrices )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( winSize.width <= 1 || winSize.height <= 1 )
-        CV_ERROR( CV_StsOutOfRange, "the search window is too small" );
+        CV_Error( CV_StsOutOfRange, "the search window is too small" );
 
     if( count < 0 )
-        CV_ERROR( CV_StsOutOfRange, "" );
+        CV_Error( CV_StsOutOfRange, "" );
 
-    CV_CALL( icvInitPyramidalAlgorithm( imgA, imgB,
+    icvInitPyramidalAlgorithm( imgA, imgB,
         pyrA, pyrB, level, &criteria, MAX_ITERS, flags,
-        &imgI, &imgJ, &step, &size, &scale, &pyr_buffer ));
+        &imgI, &imgJ, &step, &size, &scale, &pyr_buffer );
 
     /* buffer_size = <size for patches> + <size for pyramids> */
     bufferBytes = (srcPatchLen + patchLen*3)*sizeof(patchI[0]) + (36*2 + 6)*sizeof(double);
 
-    CV_CALL( buffer = (uchar*)cvAlloc(bufferBytes));
+    buffer.allocate(bufferBytes);
 
     if( !status )
-        CV_CALL( status = _status = (char*)cvAlloc(count) );
+    {
+        _status.allocate(count);
+        status = _status;
+    }
 
-    patchI = (float *) buffer;
+    patchI = (float *)(uchar*)buffer;
     patchJ = patchI + srcPatchLen;
     Ix = patchJ + patchLen;
     Iy = Ix + patchLen;
@@ -963,7 +1224,9 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
                     }
                 }
 
-                icvTransformVector_64d( G, b, eta, 6, 6 );
+                for( k = 0; k < 6; k++ )
+                    eta[k] = G[k*6]*b[0] + G[k*6+1]*b[1] + G[k*6+2]*b[2] +
+                        G[k*6+3]*b[3] + G[k*6+4]*b[4] + G[k*6+5]*b[5];
 
                 Av[2] = (float)(Av[2] + Av[0] * eta[0] + Av[1] * eta[1]);
                 Av[5] = (float)(Av[5] + Av[3] * eta[0] + Av[4] * eta[1]);
@@ -1011,12 +1274,6 @@ cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
             }
         }
     }
-
-    __END__;
-
-    cvFree( &pyr_buffer );
-    cvFree( &buffer );
-    cvFree( &_status );
 }
 
 
@@ -1121,51 +1378,41 @@ icvGetRTMatrix( const CvPoint2D32f* a, const CvPoint2D32f* b,
 
 
 CV_IMPL int
-cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_affine )
+cvEstimateRigidTransform( const CvArr* matA, const CvArr* matB, CvMat* matM, int full_affine )
 {
-    int result = 0;
-    
-    const int COUNT = 20;
+    const int COUNT = 15;
     const int WIDTH = 160, HEIGHT = 120;
-    const int RANSAC_MAX_ITERS = 100;
+    const int RANSAC_MAX_ITERS = 500;
     const int RANSAC_SIZE0 = 3;
-    const double MIN_TRIANGLE_SIDE = 20;
     const double RANSAC_GOOD_RATIO = 0.5;
 
-    int allocated = 1;
-    CvMat *sA = 0, *sB = 0;
-    CvPoint2D32f *pA = 0, *pB = 0;
-    int* good_idx = 0;
-    char *status = 0;
-    CvMat* gray = 0;
-
-    CV_FUNCNAME( "cvEstimateRigidTransform" );
-
-    __BEGIN__;
+    cv::Ptr<CvMat> sA, sB;
+    cv::AutoBuffer<CvPoint2D32f> pA, pB;
+    cv::AutoBuffer<int> good_idx;
+    cv::AutoBuffer<char> status;
+    cv::Ptr<CvMat> gray;
 
-    CvMat stubA, *A;
-    CvMat stubB, *B;
+    CvMat stubA, *A = cvGetMat( matA, &stubA );
+    CvMat stubB, *B = cvGetMat( matB, &stubB );
     CvSize sz0, sz1;
     int cn, equal_sizes;
     int i, j, k, k1;
-    int count_x, count_y, count;
+    int count_x, count_y, count = 0;
     double scale = 1;
     CvRNG rng = cvRNG(-1);
     double m[6]={0};
     CvMat M = cvMat( 2, 3, CV_64F, m );
     int good_count = 0;
+    CvRect brect;
 
-    CV_CALL( A = cvGetMat( _A, &stubA ));
-    CV_CALL( B = cvGetMat( _B, &stubB ));
-
-    if( !CV_IS_MAT(_M) )
-        CV_ERROR( _M ? CV_StsBadArg : CV_StsNullPtr, "Output parameter M is not a valid matrix" );
+    if( !CV_IS_MAT(matM) )
+        CV_Error( matM ? CV_StsBadArg : CV_StsNullPtr, "Output parameter M is not a valid matrix" );
 
     if( !CV_ARE_SIZES_EQ( A, B ) )
-        CV_ERROR( CV_StsUnmatchedSizes, "Both input images must have the same size" );
+        CV_Error( CV_StsUnmatchedSizes, "Both input images must have the same size" );
 
     if( !CV_ARE_TYPES_EQ( A, B ) )
-        CV_ERROR( CV_StsUnmatchedFormats, "Both input images must have the same data type" );
+        CV_Error( CV_StsUnmatchedFormats, "Both input images must have the same data type" );
 
     if( CV_MAT_TYPE(A->type) == CV_8UC1 || CV_MAT_TYPE(A->type) == CV_8UC3 )
     {
@@ -1182,32 +1429,24 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
 
         if( !equal_sizes || cn != 1 )
         {
-            CV_CALL( sA = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
-            CV_CALL( sB = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
-
-            if( !equal_sizes && cn != 1 )
-                CV_CALL( gray = cvCreateMat( sz0.height, sz0.width, CV_8UC1 ));
+            sA = cvCreateMat( sz1.height, sz1.width, CV_8UC1 );
+            sB = cvCreateMat( sz1.height, sz1.width, CV_8UC1 );
 
-            if( gray )
+            if( cn != 1 )
             {
+                gray = cvCreateMat( sz0.height, sz0.width, CV_8UC1 );
                 cvCvtColor( A, gray, CV_BGR2GRAY );
                 cvResize( gray, sA, CV_INTER_AREA );
                 cvCvtColor( B, gray, CV_BGR2GRAY );
                 cvResize( gray, sB, CV_INTER_AREA );
-            }
-            else if( cn == 1 )
-            {
-                cvResize( gray, sA, CV_INTER_AREA );
-                cvResize( gray, sB, CV_INTER_AREA );
+                gray.release();
             }
             else
             {
-                cvCvtColor( A, gray, CV_BGR2GRAY );
-                cvResize( gray, sA, CV_INTER_AREA );
-                cvCvtColor( B, gray, CV_BGR2GRAY );
+                cvResize( A, sA, CV_INTER_AREA );
+                cvResize( B, sB, CV_INTER_AREA );
             }
-
-            cvReleaseMat( &gray );
+           
             A = sA;
             B = sB;
         }
@@ -1216,9 +1455,9 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
         count_x = cvRound((double)COUNT*sz1.width/sz1.height);
         count = count_x * count_y;
 
-        CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
-        CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
-        CV_CALL( status = (char*)cvAlloc( count*sizeof(status[0]) ));
+        pA.allocate(count);
+        pB.allocate(count);
+        status.allocate(count);
 
         for( i = 0, k = 0; i < count_y; i++ )
             for( j = 0; j < count_x; j++, k++ )
@@ -1248,32 +1487,24 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
     else if( CV_MAT_TYPE(A->type) == CV_32FC2 || CV_MAT_TYPE(A->type) == CV_32SC2 )
     {
         count = A->cols*A->rows;
-
-        if( CV_IS_MAT_CONT(A->type & B->type) && CV_MAT_TYPE(A->type) == CV_32FC2 )
-        {
-            pA = (CvPoint2D32f*)A->data.ptr;
-            pB = (CvPoint2D32f*)B->data.ptr;
-            allocated = 0;
-        }
-        else
-        {
-            CvMat _pA, _pB;
-
-            CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
-            CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
-            _pA = cvMat( A->rows, A->cols, CV_32FC2, pA );
-            _pB = cvMat( B->rows, B->cols, CV_32FC2, pB );
-            cvConvert( A, &_pA );
-            cvConvert( B, &_pB );
-        }
+        CvMat _pA, _pB;
+        pA.allocate(count);
+        pB.allocate(count);
+        _pA = cvMat( A->rows, A->cols, CV_32FC2, pA );
+        _pB = cvMat( B->rows, B->cols, CV_32FC2, pB );
+        cvConvert( A, &_pA );
+        cvConvert( B, &_pB );
     }
     else
-        CV_ERROR( CV_StsUnsupportedFormat, "Both input images must have either 8uC1 or 8uC3 type" );
+        CV_Error( CV_StsUnsupportedFormat, "Both input images must have either 8uC1 or 8uC3 type" );
 
-    CV_CALL( good_idx = (int*)cvAlloc( count*sizeof(good_idx[0]) ));
+    good_idx.allocate(count);
 
     if( count < RANSAC_SIZE0 )
-        EXIT;
+        return 0;
+    
+    CvMat _pB = cvMat(1, count, CV_32FC2, pB);    
+    brect = cvBoundingRect(&_pB, 1);
 
     // RANSAC stuff:
     // 1. find the consensus
@@ -1299,10 +1530,10 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
                         break;
                     // check that the points are not very close one each other
                     if( fabs(pA[idx[i]].x - pA[idx[j]].x) +
-                        fabs(pA[idx[i]].y - pA[idx[j]].y) < MIN_TRIANGLE_SIDE )
+                        fabs(pA[idx[i]].y - pA[idx[j]].y) < FLT_EPSILON )
                         break;
                     if( fabs(pB[idx[i]].x - pB[idx[j]].x) +
-                        fabs(pB[idx[i]].y - pB[idx[j]].y) < MIN_TRIANGLE_SIDE )
+                        fabs(pB[idx[i]].y - pB[idx[j]].y) < FLT_EPSILON )
                         break;
                 }
 
@@ -1319,9 +1550,15 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
                     b[0] = pB[idx[0]];
                     b[1] = pB[idx[1]];
                     b[2] = pB[idx[2]];
-
-                    if( fabs((a[1].x - a[0].x)*(a[2].y - a[0].y) - (a[1].y - a[0].y)*(a[2].x - a[0].x)) < 1 ||
-                        fabs((b[1].x - b[0].x)*(b[2].y - b[0].y) - (b[1].y - b[0].y)*(b[2].x - b[0].x)) < 1 )
+                    
+                    double dax1 = a[1].x - a[0].x, day1 = a[1].y - a[0].y;
+                    double dax2 = a[2].x - a[0].x, day2 = a[2].y - a[0].y;
+                    double dbx1 = b[1].x - b[0].y, dby1 = b[1].y - b[0].y;
+                    double dbx2 = b[2].x - b[0].x, dby2 = b[2].y - b[0].y;
+                    const double eps = 0.01;
+
+                    if( fabs(dax1*day2 - day1*dax2) < eps*sqrt(dax1*dax1+day1*day1)*sqrt(dax2*dax2+day2*day2) ||
+                        fabs(dbx1*dby2 - dby1*dbx2) < eps*sqrt(dbx1*dbx1+dby1*dby1)*sqrt(dbx2*dbx2+dby2*dby2) )
                         continue;
                 }
                 break;
@@ -1337,10 +1574,10 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
         // estimate the transformation using 3 points
         icvGetRTMatrix( a, b, 3, &M, full_affine );
 
-        for( i = 0; i < count; i++ )
+        for( i = 0, good_count = 0; i < count; i++ )
         {
             if( fabs( m[0]*pA[i].x + m[1]*pA[i].y + m[2] - pB[i].x ) +
-                fabs( m[3]*pA[i].x + m[4]*pA[i].y + m[5] - pB[i].y ) < 8 )
+                fabs( m[3]*pA[i].x + m[4]*pA[i].y + m[5] - pB[i].y ) < MAX(brect.width,brect.height)*0.05 )
                 good_idx[good_count++] = i;
         }
 
@@ -1349,7 +1586,7 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
     }
 
     if( k >= RANSAC_MAX_ITERS )
-        EXIT;
+        return 0;
 
     if( good_count < count )
     {
@@ -1364,21 +1601,23 @@ cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_
     icvGetRTMatrix( pA, pB, good_count, &M, full_affine );
     m[2] /= scale;
     m[5] /= scale;
-    CV_CALL( cvConvert( &M, _M ));
-    result = 1;
-
-    __END__;
+    cvConvert( &M, matM );
+    
+    return 1;
+}
 
-    cvReleaseMat( &sA );
-    cvReleaseMat( &sB );
-    cvFree( &pA );
-    cvFree( &pB );
-    cvFree( &status );
-    cvFree( &good_idx );
-    cvReleaseMat( &gray );
+namespace cv
+{
 
-    return result;
+Mat estimateRigidTransform( const Mat& A,
+                            const Mat& B,
+                            bool fullAffine )
+{
+    Mat M(2, 3, CV_64F);
+    CvMat matA = A, matB = B, matM = M;
+    cvEstimateRigidTransform(&matA, &matB, &matM, fullAffine);
+    return M;
+}
 }
-
 
 /* End of file. */