1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
46 intersect( CvPoint2D32f pt, CvSize win_size, CvSize imgSize,
47 CvPoint* min_pt, CvPoint* max_pt )
51 ipt.x = cvFloor( pt.x );
52 ipt.y = cvFloor( pt.y );
54 ipt.x -= win_size.width;
55 ipt.y -= win_size.height;
57 win_size.width = win_size.width * 2 + 1;
58 win_size.height = win_size.height * 2 + 1;
60 min_pt->x = MAX( 0, -ipt.x );
61 min_pt->y = MAX( 0, -ipt.y );
62 max_pt->x = MIN( win_size.width, imgSize.width - ipt.x );
63 max_pt->y = MIN( win_size.height, imgSize.height - ipt.y );
67 static int icvMinimalPyramidSize( CvSize imgSize )
69 return cvAlign(imgSize.width,8) * imgSize.height / 3;
74 icvInitPyramidalAlgorithm( const CvMat* imgA, const CvMat* imgB,
75 CvMat* pyrA, CvMat* pyrB,
76 int level, CvTermCriteria * criteria,
77 int max_iters, int flags,
78 uchar *** imgI, uchar *** imgJ,
79 int **step, CvSize** size,
80 double **scale, uchar ** buffer )
82 CV_FUNCNAME( "icvInitPyramidalAlgorithm" );
87 int pyrBytes, bufferBytes = 0, elem_size;
88 int level1 = level + 1;
91 CvSize imgSize, levelSize;
99 /* check input arguments */
100 if( (flags & CV_LKFLOW_PYR_A_READY) != 0 && !pyrA ||
101 (flags & CV_LKFLOW_PYR_B_READY) != 0 && !pyrB )
102 CV_ERROR( CV_StsNullPtr, "Some of the precomputed pyramids are missing" );
105 CV_ERROR( CV_StsOutOfRange, "The number of pyramid layers is negative" );
107 switch( criteria->type )
109 case CV_TERMCRIT_ITER:
110 criteria->epsilon = 0.f;
112 case CV_TERMCRIT_EPS:
113 criteria->max_iter = max_iters;
115 case CV_TERMCRIT_ITER | CV_TERMCRIT_EPS:
119 CV_ERROR( CV_StsBadArg, "Invalid termination criteria" );
122 /* compare squared values */
123 criteria->epsilon *= criteria->epsilon;
125 /* set pointers and step for every level */
128 imgSize = cvGetSize(imgA);
129 elem_size = CV_ELEM_SIZE(imgA->type);
132 for( i = 1; i < level1; i++ )
134 levelSize.width = (levelSize.width + 1) >> 1;
135 levelSize.height = (levelSize.height + 1) >> 1;
137 int tstep = cvAlign(levelSize.width,ALIGN) * elem_size;
138 pyrBytes += tstep * levelSize.height;
141 assert( pyrBytes <= imgSize.width * imgSize.height * elem_size * 4 / 3 );
143 /* buffer_size = <size for patches> + <size for pyramids> */
144 bufferBytes = (int)((level1 >= 0) * ((pyrA->data.ptr == 0) +
145 (pyrB->data.ptr == 0)) * pyrBytes +
146 (sizeof(imgI[0][0]) * 2 + sizeof(step[0][0]) +
147 sizeof(size[0][0]) + sizeof(scale[0][0])) * level1);
149 CV_CALL( *buffer = (uchar *)cvAlloc( bufferBytes ));
151 *imgI = (uchar **) buffer[0];
152 *imgJ = *imgI + level1;
153 *step = (int *) (*imgJ + level1);
154 *scale = (double *) (*step + level1);
155 *size = (CvSize *)(*scale + level1);
157 imgI[0][0] = imgA->data.ptr;
158 imgJ[0][0] = imgB->data.ptr;
159 step[0][0] = imgA->step;
161 size[0][0] = imgSize;
165 uchar *bufPtr = (uchar *) (*size + level1);
166 uchar *ptrA = pyrA->data.ptr;
167 uchar *ptrB = pyrB->data.ptr;
180 /* build pyramids for both frames */
181 for( i = 1; i <= level; i++ )
184 CvMat prev_level, next_level;
186 levelSize.width = (levelSize.width + 1) >> 1;
187 levelSize.height = (levelSize.height + 1) >> 1;
189 size[0][i] = levelSize;
190 step[0][i] = cvAlign( levelSize.width, ALIGN ) * elem_size;
191 scale[0][i] = scale[0][i - 1] * 0.5;
193 levelBytes = step[0][i] * levelSize.height;
194 imgI[0][i] = (uchar *) ptrA;
197 if( !(flags & CV_LKFLOW_PYR_A_READY) )
199 prev_level = cvMat( size[0][i-1].height, size[0][i-1].width, CV_8UC1 );
200 next_level = cvMat( size[0][i].height, size[0][i].width, CV_8UC1 );
201 cvSetData( &prev_level, imgI[0][i-1], step[0][i-1] );
202 cvSetData( &next_level, imgI[0][i], step[0][i] );
203 cvPyrDown( &prev_level, &next_level );
206 imgJ[0][i] = (uchar *) ptrB;
209 if( !(flags & CV_LKFLOW_PYR_B_READY) )
211 prev_level = cvMat( size[0][i-1].height, size[0][i-1].width, CV_8UC1 );
212 next_level = cvMat( size[0][i].height, size[0][i].width, CV_8UC1 );
213 cvSetData( &prev_level, imgJ[0][i-1], step[0][i-1] );
214 cvSetData( &next_level, imgJ[0][i], step[0][i] );
215 cvPyrDown( &prev_level, &next_level );
224 /* compute dI/dx and dI/dy */
226 icvCalcIxIy_32f( const float* src, int src_step, float* dstX, float* dstY, int dst_step,
227 CvSize src_size, const float* smooth_k, float* buffer0 )
229 int src_width = src_size.width, dst_width = src_size.width-2;
230 int x, height = src_size.height - 2;
231 float* buffer1 = buffer0 + src_width;
233 src_step /= sizeof(src[0]);
234 dst_step /= sizeof(dstX[0]);
236 for( ; height--; src += src_step, dstX += dst_step, dstY += dst_step )
238 const float* src2 = src + src_step;
239 const float* src3 = src + src_step*2;
241 for( x = 0; x < src_width; x++ )
243 float t0 = (src3[x] + src[x])*smooth_k[0] + src2[x]*smooth_k[1];
244 float t1 = src3[x] - src[x];
245 buffer0[x] = t0; buffer1[x] = t1;
248 for( x = 0; x < dst_width; x++ )
250 float t0 = buffer0[x+2] - buffer0[x];
251 float t1 = (buffer1[x] + buffer1[x+2])*smooth_k[0] + buffer1[x+1]*smooth_k[1];
252 dstX[x] = t0; dstY[x] = t1;
258 icvOpticalFlowPyrLKInitAlloc_8u_C1R_t icvOpticalFlowPyrLKInitAlloc_8u_C1R_p = 0;
259 icvOpticalFlowPyrLKFree_8u_C1R_t icvOpticalFlowPyrLKFree_8u_C1R_p = 0;
260 icvOpticalFlowPyrLK_8u_C1R_t icvOpticalFlowPyrLK_8u_C1R_p = 0;
264 cvCalcOpticalFlowPyrLK( const void* arrA, const void* arrB,
265 void* pyrarrA, void* pyrarrB,
266 const CvPoint2D32f * featuresA,
267 CvPoint2D32f * featuresB,
268 int count, CvSize winSize, int level,
269 char *status, float *error,
270 CvTermCriteria criteria, int flags )
272 uchar *pyrBuffer = 0;
277 void* ipp_optflow_state = 0;
279 CV_FUNCNAME( "cvCalcOpticalFlowPyrLK" );
283 const int MAX_ITERS = 100;
285 CvMat stubA, *imgA = (CvMat*)arrA;
286 CvMat stubB, *imgB = (CvMat*)arrB;
287 CvMat pstubA, *pyrA = (CvMat*)pyrarrA;
288 CvMat pstubB, *pyrB = (CvMat*)pyrarrB;
290 static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 }; /* 3/32, 10/32, 3/32 */
299 int threadCount = cvGetNumThreads();
300 float* _patchI[CV_MAX_THREADS];
301 float* _patchJ[CV_MAX_THREADS];
302 float* _Ix[CV_MAX_THREADS];
303 float* _Iy[CV_MAX_THREADS];
307 CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 );
308 int patchLen = patchSize.width * patchSize.height;
309 int srcPatchLen = (patchSize.width + 2)*(patchSize.height + 2);
311 CV_CALL( imgA = cvGetMat( imgA, &stubA ));
312 CV_CALL( imgB = cvGetMat( imgB, &stubB ));
314 if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
315 CV_ERROR( CV_StsUnsupportedFormat, "" );
317 if( !CV_ARE_TYPES_EQ( imgA, imgB ))
318 CV_ERROR( CV_StsUnmatchedFormats, "" );
320 if( !CV_ARE_SIZES_EQ( imgA, imgB ))
321 CV_ERROR( CV_StsUnmatchedSizes, "" );
323 if( imgA->step != imgB->step )
324 CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
326 imgSize = cvGetMatSize( imgA );
330 CV_CALL( pyrA = cvGetMat( pyrA, &pstubA ));
332 if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
333 CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" );
343 CV_CALL( pyrB = cvGetMat( pyrB, &pstubB ));
345 if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
346 CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" );
357 if( !featuresA || !featuresB )
358 CV_ERROR( CV_StsNullPtr, "Some of arrays of point coordinates are missing" );
361 CV_ERROR( CV_StsOutOfRange, "The number of tracked points is negative or zero" );
363 if( winSize.width <= 1 || winSize.height <= 1 )
364 CV_ERROR( CV_StsBadSize, "Invalid search window size" );
366 for( i = 0; i < threadCount; i++ )
367 _patchI[i] = _patchJ[i] = _Ix[i] = _Iy[i] = 0;
369 CV_CALL( icvInitPyramidalAlgorithm( imgA, imgB, pyrA, pyrB,
370 level, &criteria, MAX_ITERS, flags,
371 &imgI, &imgJ, &step, &size, &scale, &pyrBuffer ));
374 CV_CALL( status = _status = (char*)cvAlloc( count*sizeof(_status[0]) ));
377 if( icvOpticalFlowPyrLKInitAlloc_8u_C1R_p &&
378 icvOpticalFlowPyrLKFree_8u_C1R_p &&
379 icvOpticalFlowPyrLK_8u_C1R_p &&
380 winSize.width == winSize.height &&
381 icvOpticalFlowPyrLKInitAlloc_8u_C1R_p( &ipp_optflow_state, imgSize,
382 winSize.width*2+1, cvAlgHintAccurate ) >= 0 )
384 CvPyramid ipp_pyrA, ipp_pyrB;
385 static const double rate[] = { 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125,
386 0.00390625, 0.001953125, 0.0009765625, 0.00048828125, 0.000244140625,
388 // initialize pyramid structures
389 assert( level < 14 );
392 ipp_pyrA.sz = ipp_pyrB.sz = size;
393 ipp_pyrA.rate = ipp_pyrB.rate = (double*)rate;
394 ipp_pyrA.step = ipp_pyrB.step = step;
395 ipp_pyrA.state = ipp_pyrB.state = 0;
396 ipp_pyrA.level = ipp_pyrB.level = level;
399 CV_CALL( error = _error = (float*)cvAlloc( count*sizeof(_error[0]) ));
401 for( i = 0; i < count; i++ )
402 featuresB[i] = featuresA[i];
404 if( icvOpticalFlowPyrLK_8u_C1R_p( &ipp_pyrA, &ipp_pyrB,
405 (const float*)featuresA, (float*)featuresB, status, error, count,
406 winSize.width*2 + 1, level, criteria.max_iter,
407 (float)criteria.epsilon, ipp_optflow_state ) >= 0 )
409 for( i = 0; i < count; i++ )
410 status[i] = status[i] == 0;
416 /* buffer_size = <size for patches> + <size for pyramids> */
417 bufferBytes = (srcPatchLen + patchLen * 3) * sizeof( _patchI[0][0] ) * threadCount;
418 CV_CALL( buffer = (uchar*)cvAlloc( bufferBytes ));
420 for( i = 0; i < threadCount; i++ )
422 _patchI[i] = i == 0 ? (float*)buffer : _Iy[i-1] + patchLen;
423 _patchJ[i] = _patchI[i] + srcPatchLen;
424 _Ix[i] = _patchJ[i] + patchLen;
425 _Iy[i] = _Ix[i] + patchLen;
428 memset( status, 1, count );
430 memset( error, 0, count*sizeof(error[0]) );
432 if( !(flags & CV_LKFLOW_INITIAL_GUESSES) )
433 memcpy( featuresB, featuresA, count*sizeof(featuresA[0]));
435 /* do processing from top pyramid level (smallest image)
436 to the bottom (original image) */
437 for( l = level; l >= 0; l-- )
439 CvSize levelSize = size[l];
440 int levelStep = step[l];
444 #pragma omp parallel for num_threads(threadCount), schedule(dynamic)
446 /* find flow for each given point */
447 for( i = 0; i < count; i++ )
450 CvPoint minI, maxI, minJ, maxJ;
454 CvPoint prev_minJ = { -1, -1 }, prev_maxJ = { -1, -1 };
455 double Gxx = 0, Gxy = 0, Gyy = 0, D = 0, minEig = 0;
456 float prev_mx = 0, prev_my = 0;
458 int threadIdx = cvGetThreadNum();
459 float* patchI = _patchI[threadIdx];
460 float* patchJ = _patchJ[threadIdx];
461 float* Ix = _Ix[threadIdx];
462 float* Iy = _Iy[threadIdx];
464 v.x = featuresB[i].x;
465 v.y = featuresB[i].y;
473 v.x = (float)(v.x * scale[l]);
474 v.y = (float)(v.y * scale[l]);
477 pt_status = status[i];
481 minI = maxI = minJ = maxJ = cvPoint( 0, 0 );
483 u.x = (float) (featuresA[i].x * scale[l]);
484 u.y = (float) (featuresA[i].y * scale[l]);
486 intersect( u, winSize, levelSize, &minI, &maxI );
487 isz = jsz = cvSize(maxI.x - minI.x + 2, maxI.y - minI.y + 2);
488 u.x += (minI.x - (patchSize.width - maxI.x + 1))*0.5f;
489 u.y += (minI.y - (patchSize.height - maxI.y + 1))*0.5f;
491 if( isz.width < 3 || isz.height < 3 ||
492 icvGetRectSubPix_8u32f_C1R( imgI[l], levelStep, levelSize,
493 patchI, isz.width*sizeof(patchI[0]), isz, u ) < 0 )
495 /* point is outside the image. take the next */
500 icvCalcIxIy_32f( patchI, isz.width*sizeof(patchI[0]), Ix, Iy,
501 (isz.width-2)*sizeof(patchI[0]), isz, smoothKernel, patchJ );
503 for( j = 0; j < criteria.max_iter; j++ )
505 double bx = 0, by = 0;
509 intersect( v, winSize, levelSize, &minJ, &maxJ );
511 minJ.x = MAX( minJ.x, minI.x );
512 minJ.y = MAX( minJ.y, minI.y );
514 maxJ.x = MIN( maxJ.x, maxI.x );
515 maxJ.y = MIN( maxJ.y, maxI.y );
517 jsz = cvSize(maxJ.x - minJ.x, maxJ.y - minJ.y);
519 _v.x = v.x + (minJ.x - (patchSize.width - maxJ.x + 1))*0.5f;
520 _v.y = v.y + (minJ.y - (patchSize.height - maxJ.y + 1))*0.5f;
522 if( jsz.width < 1 || jsz.height < 1 ||
523 icvGetRectSubPix_8u32f_C1R( imgJ[l], levelStep, levelSize, patchJ,
524 jsz.width*sizeof(patchJ[0]), jsz, _v ) < 0 )
526 /* point is outside image. take the next */
531 if( maxJ.x == prev_maxJ.x && maxJ.y == prev_maxJ.y &&
532 minJ.x == prev_minJ.x && minJ.y == prev_minJ.y )
534 for( y = 0; y < jsz.height; y++ )
536 const float* pi = patchI +
537 (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
538 const float* pj = patchJ + y*jsz.width;
539 const float* ix = Ix +
540 (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
541 const float* iy = Iy + (ix - Ix);
543 for( x = 0; x < jsz.width; x++ )
545 double t0 = pi[x] - pj[x];
554 for( y = 0; y < jsz.height; y++ )
556 const float* pi = patchI +
557 (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
558 const float* pj = patchJ + y*jsz.width;
559 const float* ix = Ix +
560 (y + minJ.y - minI.y)*(isz.width-2) + minJ.x - minI.x;
561 const float* iy = Iy + (ix - Ix);
563 for( x = 0; x < jsz.width; x++ )
565 double t = pi[x] - pj[x];
566 bx += (double) (t * ix[x]);
567 by += (double) (t * iy[x]);
568 Gxx += ix[x] * ix[x];
569 Gxy += ix[x] * iy[x];
570 Gyy += iy[x] * iy[x];
574 D = Gxx * Gyy - Gxy * Gxy;
575 if( D < DBL_EPSILON )
581 // Adi Shavit - 2008.05
582 if( flags & CV_LKFLOW_GET_MIN_EIGENVALS )
583 minEig = (Gyy + Gxx - sqrt((Gxx-Gyy)*(Gxx-Gyy) + 4.*Gxy*Gxy))/(2*jsz.height*jsz.width);
591 mx = (float) ((Gyy * bx - Gxy * by) * D);
592 my = (float) ((Gxx * by - Gxy * bx) * D);
597 if( mx * mx + my * my < criteria.epsilon )
600 if( j > 0 && fabs(mx + prev_mx) < 0.01 && fabs(my + prev_my) < 0.01 )
611 status[i] = (char)pt_status;
612 if( l == 0 && error && pt_status )
616 if( flags & CV_LKFLOW_GET_MIN_EIGENVALS )
620 for( y = 0; y < jsz.height; y++ )
622 const float* pi = patchI +
623 (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
624 const float* pj = patchJ + y*jsz.width;
626 for( x = 0; x < jsz.width; x++ )
628 double t = pi[x] - pj[x];
634 error[i] = (float)err;
636 } // end of point processing loop (i)
638 } // end of pyramid levels loop (l)
642 if( ipp_optflow_state )
643 icvOpticalFlowPyrLKFree_8u_C1R_p( ipp_optflow_state );
645 cvFree( &pyrBuffer );
652 /* Affine tracking algorithm */
655 cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
656 void* pyrarrA, void* pyrarrB,
657 const CvPoint2D32f * featuresA,
658 CvPoint2D32f * featuresB,
659 float *matrices, int count,
660 CvSize winSize, int level,
661 char *status, float *error,
662 CvTermCriteria criteria, int flags )
664 const int MAX_ITERS = 100;
668 uchar *pyr_buffer = 0;
670 CV_FUNCNAME( "cvCalcAffineFlowPyrLK" );
674 CvMat stubA, *imgA = (CvMat*)arrA;
675 CvMat stubB, *imgB = (CvMat*)arrB;
676 CvMat pstubA, *pyrA = (CvMat*)pyrarrA;
677 CvMat pstubB, *pyrB = (CvMat*)pyrarrB;
679 static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 }; /* 3/32, 10/32, 3/32 */
696 CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 );
697 int patchLen = patchSize.width * patchSize.height;
698 int patchStep = patchSize.width * sizeof( patchI[0] );
700 CvSize srcPatchSize = cvSize( patchSize.width + 2, patchSize.height + 2 );
701 int srcPatchLen = srcPatchSize.width * srcPatchSize.height;
702 int srcPatchStep = srcPatchSize.width * sizeof( patchI[0] );
704 float eps = (float)MIN(winSize.width, winSize.height);
706 CV_CALL( imgA = cvGetMat( imgA, &stubA ));
707 CV_CALL( imgB = cvGetMat( imgB, &stubB ));
709 if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
710 CV_ERROR( CV_StsUnsupportedFormat, "" );
712 if( !CV_ARE_TYPES_EQ( imgA, imgB ))
713 CV_ERROR( CV_StsUnmatchedFormats, "" );
715 if( !CV_ARE_SIZES_EQ( imgA, imgB ))
716 CV_ERROR( CV_StsUnmatchedSizes, "" );
718 if( imgA->step != imgB->step )
719 CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
722 CV_ERROR( CV_StsNullPtr, "" );
724 imgSize = cvGetMatSize( imgA );
728 CV_CALL( pyrA = cvGetMat( pyrA, &pstubA ));
730 if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
731 CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" );
741 CV_CALL( pyrB = cvGetMat( pyrB, &pstubB ));
743 if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
744 CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" );
755 /* check input arguments */
756 if( !featuresA || !featuresB || !matrices )
757 CV_ERROR( CV_StsNullPtr, "" );
759 if( winSize.width <= 1 || winSize.height <= 1 )
760 CV_ERROR( CV_StsOutOfRange, "the search window is too small" );
763 CV_ERROR( CV_StsOutOfRange, "" );
765 CV_CALL( icvInitPyramidalAlgorithm( imgA, imgB,
766 pyrA, pyrB, level, &criteria, MAX_ITERS, flags,
767 &imgI, &imgJ, &step, &size, &scale, &pyr_buffer ));
769 /* buffer_size = <size for patches> + <size for pyramids> */
770 bufferBytes = (srcPatchLen + patchLen*3)*sizeof(patchI[0]) + (36*2 + 6)*sizeof(double);
772 CV_CALL( buffer = (uchar*)cvAlloc(bufferBytes));
775 CV_CALL( status = _status = (char*)cvAlloc(count) );
777 patchI = (float *) buffer;
778 patchJ = patchI + srcPatchLen;
779 Ix = patchJ + patchLen;
783 memset( status, 1, count );
785 if( !(flags & CV_LKFLOW_INITIAL_GUESSES) )
787 memcpy( featuresB, featuresA, count * sizeof( featuresA[0] ));
788 for( i = 0; i < count * 4; i += 4 )
790 matrices[i] = matrices[i + 3] = 1.f;
791 matrices[i + 1] = matrices[i + 2] = 0.f;
795 for( i = 0; i < count; i++ )
797 featuresB[i].x = (float)(featuresB[i].x * scale[level] * 0.5);
798 featuresB[i].y = (float)(featuresB[i].y * scale[level] * 0.5);
801 /* do processing from top pyramid level (smallest image)
802 to the bottom (original image) */
803 for( l = level; l >= 0; l-- )
805 CvSize levelSize = size[l];
806 int levelStep = step[l];
808 /* find flow for each given point at the particular level */
809 for( i = 0; i < count; i++ )
814 double meanI = 0, meanJ = 0;
816 int pt_status = status[i];
822 Av[0] = matrices[i*4];
823 Av[1] = matrices[i*4+1];
824 Av[3] = matrices[i*4+2];
825 Av[4] = matrices[i*4+3];
827 Av[2] = featuresB[i].x += featuresB[i].x;
828 Av[5] = featuresB[i].y += featuresB[i].y;
830 u.x = (float) (featuresA[i].x * scale[l]);
831 u.y = (float) (featuresA[i].y * scale[l]);
833 if( u.x < -eps || u.x >= levelSize.width+eps ||
834 u.y < -eps || u.y >= levelSize.height+eps ||
835 icvGetRectSubPix_8u32f_C1R( imgI[l], levelStep,
836 levelSize, patchI, srcPatchStep, srcPatchSize, u ) < 0 )
838 /* point is outside the image. take the next */
844 icvCalcIxIy_32f( patchI, srcPatchStep, Ix, Iy,
845 (srcPatchSize.width-2)*sizeof(patchI[0]), srcPatchSize,
846 smoothKernel, patchJ );
848 /* repack patchI (remove borders) */
849 for( k = 0; k < patchSize.height; k++ )
850 memcpy( patchI + k * patchSize.width,
851 patchI + (k + 1) * srcPatchSize.width + 1, patchStep );
853 memset( G, 0, sizeof( G ));
855 /* calculate G matrix */
856 for( y = -winSize.height, k = 0; y <= winSize.height; y++ )
858 for( x = -winSize.width; x <= winSize.width; x++, k++ )
860 double ixix = ((double) Ix[k]) * Ix[k];
861 double ixiy = ((double) Ix[k]) * Iy[k];
862 double iyiy = ((double) Iy[k]) * Iy[k];
885 // G[13] == G[8] == G[4]
916 meanI /= patchSize.width*patchSize.height;
922 // fill part of G below its diagonal
923 for( y = 1; y < 6; y++ )
924 for( x = 0; x < y; x++ )
925 G[y * 6 + x] = G[x * 6 + y];
927 cvInitMatHeader( &mat, 6, 6, CV_64FC1, G );
929 if( cvInvert( &mat, &mat, CV_SVD ) < 1e-4 )
931 /* bad matrix. take the next point */
937 for( j = 0; j < criteria.max_iter; j++ )
939 double b[6] = {0,0,0,0,0,0}, eta[6];
940 double t0, t1, s = 0;
942 if( Av[2] < -eps || Av[2] >= levelSize.width+eps ||
943 Av[5] < -eps || Av[5] >= levelSize.height+eps ||
944 icvGetQuadrangleSubPix_8u32f_C1R( imgJ[l], levelStep,
945 levelSize, patchJ, patchStep, patchSize, Av ) < 0 )
951 for( y = -winSize.height, k = 0, meanJ = 0; y <= winSize.height; y++ )
952 for( x = -winSize.width; x <= winSize.width; x++, k++ )
955 meanJ = meanJ / (patchSize.width * patchSize.height) - meanI;
957 for( y = -winSize.height, k = 0; y <= winSize.height; y++ )
959 for( x = -winSize.width; x <= winSize.width; x++, k++ )
961 double t = patchI[k] - patchJ[k] + meanJ;
962 double ixt = Ix[k] * t;
963 double iyt = Iy[k] * t;
976 icvTransformVector_64d( G, b, eta, 6, 6 );
978 Av[2] = (float)(Av[2] + Av[0] * eta[0] + Av[1] * eta[1]);
979 Av[5] = (float)(Av[5] + Av[3] * eta[0] + Av[4] * eta[1]);
981 t0 = Av[0] * (1 + eta[2]) + Av[1] * eta[4];
982 t1 = Av[0] * eta[3] + Av[1] * (1 + eta[5]);
986 t0 = Av[3] * (1 + eta[2]) + Av[4] * eta[4];
987 t1 = Av[3] * eta[3] + Av[4] * (1 + eta[5]);
991 if( eta[0] * eta[0] + eta[1] * eta[1] < criteria.epsilon )
995 if( pt_status != 0 || l == 0 )
997 status[i] = (char)pt_status;
998 featuresB[i].x = Av[2];
999 featuresB[i].y = Av[5];
1001 matrices[i*4] = Av[0];
1002 matrices[i*4+1] = Av[1];
1003 matrices[i*4+2] = Av[3];
1004 matrices[i*4+3] = Av[4];
1007 if( pt_status && l == 0 && error )
1012 for( y = 0, k = 0; y < patchSize.height; y++ )
1014 for( x = 0; x < patchSize.width; x++, k++ )
1016 double t = patchI[k] - patchJ[k] + meanJ;
1020 error[i] = (float)sqrt(err);
1027 cvFree( &pyr_buffer );
1035 icvGetRTMatrix( const CvPoint2D32f* a, const CvPoint2D32f* b,
1036 int count, CvMat* M, int full_affine )
1040 double sa[36], sb[6];
1041 CvMat A = cvMat( 6, 6, CV_64F, sa ), B = cvMat( 6, 1, CV_64F, sb );
1042 CvMat MM = cvMat( 6, 1, CV_64F, M->data.db );
1046 memset( sa, 0, sizeof(sa) );
1047 memset( sb, 0, sizeof(sb) );
1049 for( i = 0; i < count; i++ )
1051 sa[0] += a[i].x*a[i].x;
1052 sa[1] += a[i].y*a[i].x;
1055 sa[6] += a[i].x*a[i].y;
1056 sa[7] += a[i].y*a[i].y;
1063 sb[0] += a[i].x*b[i].x;
1064 sb[1] += a[i].y*b[i].x;
1066 sb[3] += a[i].x*b[i].y;
1067 sb[4] += a[i].y*b[i].y;
1081 cvSolve( &A, &B, &MM, CV_SVD );
1085 double sa[16], sb[4], m[4], *om = M->data.db;
1086 CvMat A = cvMat( 4, 4, CV_64F, sa ), B = cvMat( 4, 1, CV_64F, sb );
1087 CvMat MM = cvMat( 4, 1, CV_64F, m );
1091 memset( sa, 0, sizeof(sa) );
1092 memset( sb, 0, sizeof(sb) );
1094 for( i = 0; i < count; i++ )
1096 sa[0] += a[i].x*a[i].x + a[i].y*a[i].y;
1102 sa[5] += a[i].x*a[i].x + a[i].y*a[i].y;
1116 sb[0] += a[i].x*b[i].x + a[i].y*b[i].y;
1117 sb[1] += a[i].x*b[i].y - a[i].y*b[i].x;
1122 cvSolve( &A, &B, &MM, CV_SVD );
1124 om[0] = om[4] = m[0];
1134 cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_affine )
1138 const int COUNT = 15;
1139 const int WIDTH = 160, HEIGHT = 120;
1140 const int RANSAC_MAX_ITERS = 100;
1141 const int RANSAC_SIZE0 = 3;
1142 const double MIN_TRIANGLE_SIDE = 20;
1143 const double RANSAC_GOOD_RATIO = 0.5;
1146 CvMat *sA = 0, *sB = 0;
1147 CvPoint2D32f *pA = 0, *pB = 0;
1152 CV_FUNCNAME( "cvEstimateRigidTransform" );
1159 int cn, equal_sizes;
1161 int count_x, count_y, count;
1163 CvRNG rng = cvRNG(-1);
1165 CvMat M = cvMat( 2, 3, CV_64F, m );
1168 CV_CALL( A = cvGetMat( _A, &stubA ));
1169 CV_CALL( B = cvGetMat( _B, &stubB ));
1171 if( !CV_IS_MAT(_M) )
1172 CV_ERROR( _M ? CV_StsBadArg : CV_StsNullPtr, "Output parameter M is not a valid matrix" );
1174 if( !CV_ARE_SIZES_EQ( A, B ) )
1175 CV_ERROR( CV_StsUnmatchedSizes, "Both input images must have the same size" );
1177 if( !CV_ARE_TYPES_EQ( A, B ) )
1178 CV_ERROR( CV_StsUnmatchedFormats, "Both input images must have the same data type" );
1180 if( CV_MAT_TYPE(A->type) == CV_8UC1 || CV_MAT_TYPE(A->type) == CV_8UC3 )
1182 cn = CV_MAT_CN(A->type);
1184 sz1 = cvSize(WIDTH, HEIGHT);
1186 scale = MAX( (double)sz1.width/sz0.width, (double)sz1.height/sz0.height );
1187 scale = MIN( scale, 1. );
1188 sz1.width = cvRound( sz0.width * scale );
1189 sz1.height = cvRound( sz0.height * scale );
1191 equal_sizes = sz1.width == sz0.width && sz1.height == sz0.height;
1193 if( !equal_sizes || cn != 1 )
1195 CV_CALL( sA = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
1196 CV_CALL( sB = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
1198 if( !equal_sizes && cn != 1 )
1199 CV_CALL( gray = cvCreateMat( sz0.height, sz0.width, CV_8UC1 ));
1203 cvCvtColor( A, gray, CV_BGR2GRAY );
1204 cvResize( gray, sA, CV_INTER_AREA );
1205 cvCvtColor( B, gray, CV_BGR2GRAY );
1206 cvResize( gray, sB, CV_INTER_AREA );
1210 cvResize( gray, sA, CV_INTER_AREA );
1211 cvResize( gray, sB, CV_INTER_AREA );
1215 cvCvtColor( A, gray, CV_BGR2GRAY );
1216 cvResize( gray, sA, CV_INTER_AREA );
1217 cvCvtColor( B, gray, CV_BGR2GRAY );
1220 cvReleaseMat( &gray );
1226 count_x = cvRound((double)COUNT*sz1.width/sz1.height);
1227 count = count_x * count_y;
1229 CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
1230 CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
1231 CV_CALL( status = (char*)cvAlloc( count*sizeof(status[0]) ));
1233 for( i = 0, k = 0; i < count_y; i++ )
1234 for( j = 0; j < count_x; j++, k++ )
1236 pA[k].x = (j+0.5f)*sz1.width/count_x;
1237 pA[k].y = (i+0.5f)*sz1.height/count_y;
1240 // find the corresponding points in B
1241 cvCalcOpticalFlowPyrLK( A, B, 0, 0, pA, pB, count, cvSize(10,10), 3,
1242 status, 0, cvTermCriteria(CV_TERMCRIT_ITER,40,0.1), 0 );
1244 // repack the remained points
1245 for( i = 0, k = 0; i < count; i++ )
1258 else if( CV_MAT_TYPE(A->type) == CV_32FC2 || CV_MAT_TYPE(A->type) == CV_32SC2 )
1260 count = A->cols*A->rows;
1262 if( CV_IS_MAT_CONT(A->type & B->type) && CV_MAT_TYPE(A->type) == CV_32FC2 )
1264 pA = (CvPoint2D32f*)A->data.ptr;
1265 pB = (CvPoint2D32f*)B->data.ptr;
1272 CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
1273 CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
1274 _pA = cvMat( A->rows, A->cols, CV_32FC2, pA );
1275 _pB = cvMat( B->rows, B->cols, CV_32FC2, pB );
1276 cvConvert( A, &_pA );
1277 cvConvert( B, &_pB );
1281 CV_ERROR( CV_StsUnsupportedFormat, "Both input images must have either 8uC1 or 8uC3 type" );
1283 CV_CALL( good_idx = (int*)cvAlloc( count*sizeof(good_idx[0]) ));
1285 if( count < RANSAC_SIZE0 )
1289 // 1. find the consensus
1290 for( k = 0; k < RANSAC_MAX_ITERS; k++ )
1292 int idx[RANSAC_SIZE0];
1296 memset( a, 0, sizeof(a) );
1297 memset( b, 0, sizeof(b) );
1299 // choose random 3 non-complanar points from A & B
1300 for( i = 0; i < RANSAC_SIZE0; i++ )
1302 for( k1 = 0; k1 < RANSAC_MAX_ITERS; k1++ )
1304 idx[i] = cvRandInt(&rng) % count;
1306 for( j = 0; j < i; j++ )
1308 if( idx[j] == idx[i] )
1310 // check that the points are not very close one each other
1311 if( fabs(pA[idx[i]].x - pA[idx[j]].x) +
1312 fabs(pA[idx[i]].y - pA[idx[j]].y) < MIN_TRIANGLE_SIDE )
1314 if( fabs(pB[idx[i]].x - pB[idx[j]].x) +
1315 fabs(pB[idx[i]].y - pB[idx[j]].y) < MIN_TRIANGLE_SIDE )
1322 if( i+1 == RANSAC_SIZE0 )
1324 // additional check for non-complanar vectors
1333 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 ||
1334 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 )
1340 if( k1 >= RANSAC_MAX_ITERS )
1344 if( i < RANSAC_SIZE0 )
1347 // estimate the transformation using 3 points
1348 icvGetRTMatrix( a, b, 3, &M, full_affine );
1350 for( i = 0, good_count = 0; i < count; i++ )
1352 if( fabs( m[0]*pA[i].x + m[1]*pA[i].y + m[2] - pB[i].x ) +
1353 fabs( m[3]*pA[i].x + m[4]*pA[i].y + m[5] - pB[i].y ) < 8 )
1354 good_idx[good_count++] = i;
1357 if( good_count >= count*RANSAC_GOOD_RATIO )
1361 if( k >= RANSAC_MAX_ITERS )
1364 if( good_count < count )
1366 for( i = 0; i < good_count; i++ )
1374 icvGetRTMatrix( pA, pB, good_count, &M, full_affine );
1377 CV_CALL( cvConvert( &M, _M ));
1382 cvReleaseMat( &sA );
1383 cvReleaseMat( &sB );
1387 cvFree( &good_idx );
1388 cvReleaseMat( &gray );