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;
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 )
586 mx = (float) ((Gyy * bx - Gxy * by) * D);
587 my = (float) ((Gxx * by - Gxy * bx) * D);
592 if( mx * mx + my * my < criteria.epsilon )
595 if( j > 0 && fabs(mx + prev_mx) < 0.01 && fabs(my + prev_my) < 0.01 )
606 status[i] = (char)pt_status;
607 if( l == 0 && error && pt_status )
612 for( y = 0; y < jsz.height; y++ )
614 const float* pi = patchI +
615 (y + minJ.y - minI.y + 1)*isz.width + minJ.x - minI.x + 1;
616 const float* pj = patchJ + y*jsz.width;
618 for( x = 0; x < jsz.width; x++ )
620 double t = pi[x] - pj[x];
624 error[i] = (float)sqrt(err);
626 } // end of point processing loop (i)
628 } // end of pyramid levels loop (l)
632 if( ipp_optflow_state )
633 icvOpticalFlowPyrLKFree_8u_C1R_p( ipp_optflow_state );
635 cvFree( &pyrBuffer );
642 /* Affine tracking algorithm */
645 cvCalcAffineFlowPyrLK( const void* arrA, const void* arrB,
646 void* pyrarrA, void* pyrarrB,
647 const CvPoint2D32f * featuresA,
648 CvPoint2D32f * featuresB,
649 float *matrices, int count,
650 CvSize winSize, int level,
651 char *status, float *error,
652 CvTermCriteria criteria, int flags )
654 const int MAX_ITERS = 100;
658 uchar *pyr_buffer = 0;
660 CV_FUNCNAME( "cvCalcAffineFlowPyrLK" );
664 CvMat stubA, *imgA = (CvMat*)arrA;
665 CvMat stubB, *imgB = (CvMat*)arrB;
666 CvMat pstubA, *pyrA = (CvMat*)pyrarrA;
667 CvMat pstubB, *pyrB = (CvMat*)pyrarrB;
669 static const float smoothKernel[] = { 0.09375, 0.3125, 0.09375 }; /* 3/32, 10/32, 3/32 */
686 CvSize patchSize = cvSize( winSize.width * 2 + 1, winSize.height * 2 + 1 );
687 int patchLen = patchSize.width * patchSize.height;
688 int patchStep = patchSize.width * sizeof( patchI[0] );
690 CvSize srcPatchSize = cvSize( patchSize.width + 2, patchSize.height + 2 );
691 int srcPatchLen = srcPatchSize.width * srcPatchSize.height;
692 int srcPatchStep = srcPatchSize.width * sizeof( patchI[0] );
694 float eps = (float)MIN(winSize.width, winSize.height);
696 CV_CALL( imgA = cvGetMat( imgA, &stubA ));
697 CV_CALL( imgB = cvGetMat( imgB, &stubB ));
699 if( CV_MAT_TYPE( imgA->type ) != CV_8UC1 )
700 CV_ERROR( CV_StsUnsupportedFormat, "" );
702 if( !CV_ARE_TYPES_EQ( imgA, imgB ))
703 CV_ERROR( CV_StsUnmatchedFormats, "" );
705 if( !CV_ARE_SIZES_EQ( imgA, imgB ))
706 CV_ERROR( CV_StsUnmatchedSizes, "" );
708 if( imgA->step != imgB->step )
709 CV_ERROR( CV_StsUnmatchedSizes, "imgA and imgB must have equal steps" );
712 CV_ERROR( CV_StsNullPtr, "" );
714 imgSize = cvGetMatSize( imgA );
718 CV_CALL( pyrA = cvGetMat( pyrA, &pstubA ));
720 if( pyrA->step*pyrA->height < icvMinimalPyramidSize( imgSize ) )
721 CV_ERROR( CV_StsBadArg, "pyramid A has insufficient size" );
731 CV_CALL( pyrB = cvGetMat( pyrB, &pstubB ));
733 if( pyrB->step*pyrB->height < icvMinimalPyramidSize( imgSize ) )
734 CV_ERROR( CV_StsBadArg, "pyramid B has insufficient size" );
745 /* check input arguments */
746 if( !featuresA || !featuresB || !matrices )
747 CV_ERROR( CV_StsNullPtr, "" );
749 if( winSize.width <= 1 || winSize.height <= 1 )
750 CV_ERROR( CV_StsOutOfRange, "the search window is too small" );
753 CV_ERROR( CV_StsOutOfRange, "" );
755 CV_CALL( icvInitPyramidalAlgorithm( imgA, imgB,
756 pyrA, pyrB, level, &criteria, MAX_ITERS, flags,
757 &imgI, &imgJ, &step, &size, &scale, &pyr_buffer ));
759 /* buffer_size = <size for patches> + <size for pyramids> */
760 bufferBytes = (srcPatchLen + patchLen*3)*sizeof(patchI[0]) + (36*2 + 6)*sizeof(double);
762 CV_CALL( buffer = (uchar*)cvAlloc(bufferBytes));
765 CV_CALL( status = _status = (char*)cvAlloc(count) );
767 patchI = (float *) buffer;
768 patchJ = patchI + srcPatchLen;
769 Ix = patchJ + patchLen;
773 memset( status, 1, count );
775 if( !(flags & CV_LKFLOW_INITIAL_GUESSES) )
777 memcpy( featuresB, featuresA, count * sizeof( featuresA[0] ));
778 for( i = 0; i < count * 4; i += 4 )
780 matrices[i] = matrices[i + 3] = 1.f;
781 matrices[i + 1] = matrices[i + 2] = 0.f;
785 for( i = 0; i < count; i++ )
787 featuresB[i].x = (float)(featuresB[i].x * scale[level] * 0.5);
788 featuresB[i].y = (float)(featuresB[i].y * scale[level] * 0.5);
791 /* do processing from top pyramid level (smallest image)
792 to the bottom (original image) */
793 for( l = level; l >= 0; l-- )
795 CvSize levelSize = size[l];
796 int levelStep = step[l];
798 /* find flow for each given point at the particular level */
799 for( i = 0; i < count; i++ )
804 double meanI = 0, meanJ = 0;
806 int pt_status = status[i];
812 Av[0] = matrices[i*4];
813 Av[1] = matrices[i*4+1];
814 Av[3] = matrices[i*4+2];
815 Av[4] = matrices[i*4+3];
817 Av[2] = featuresB[i].x += featuresB[i].x;
818 Av[5] = featuresB[i].y += featuresB[i].y;
820 u.x = (float) (featuresA[i].x * scale[l]);
821 u.y = (float) (featuresA[i].y * scale[l]);
823 if( u.x < -eps || u.x >= levelSize.width+eps ||
824 u.y < -eps || u.y >= levelSize.height+eps ||
825 icvGetRectSubPix_8u32f_C1R( imgI[l], levelStep,
826 levelSize, patchI, srcPatchStep, srcPatchSize, u ) < 0 )
828 /* point is outside the image. take the next */
834 icvCalcIxIy_32f( patchI, srcPatchStep, Ix, Iy,
835 (srcPatchSize.width-2)*sizeof(patchI[0]), srcPatchSize,
836 smoothKernel, patchJ );
838 /* repack patchI (remove borders) */
839 for( k = 0; k < patchSize.height; k++ )
840 memcpy( patchI + k * patchSize.width,
841 patchI + (k + 1) * srcPatchSize.width + 1, patchStep );
843 memset( G, 0, sizeof( G ));
845 /* calculate G matrix */
846 for( y = -winSize.height, k = 0; y <= winSize.height; y++ )
848 for( x = -winSize.width; x <= winSize.width; x++, k++ )
850 double ixix = ((double) Ix[k]) * Ix[k];
851 double ixiy = ((double) Ix[k]) * Iy[k];
852 double iyiy = ((double) Iy[k]) * Iy[k];
875 // G[13] == G[8] == G[4]
906 meanI /= patchSize.width*patchSize.height;
912 // fill part of G below its diagonal
913 for( y = 1; y < 6; y++ )
914 for( x = 0; x < y; x++ )
915 G[y * 6 + x] = G[x * 6 + y];
917 cvInitMatHeader( &mat, 6, 6, CV_64FC1, G );
919 if( cvInvert( &mat, &mat, CV_SVD ) < 1e-4 )
921 /* bad matrix. take the next point */
927 for( j = 0; j < criteria.max_iter; j++ )
929 double b[6] = {0,0,0,0,0,0}, eta[6];
930 double t0, t1, s = 0;
932 if( Av[2] < -eps || Av[2] >= levelSize.width+eps ||
933 Av[5] < -eps || Av[5] >= levelSize.height+eps ||
934 icvGetQuadrangleSubPix_8u32f_C1R( imgJ[l], levelStep,
935 levelSize, patchJ, patchStep, patchSize, Av ) < 0 )
941 for( y = -winSize.height, k = 0, meanJ = 0; y <= winSize.height; y++ )
942 for( x = -winSize.width; x <= winSize.width; x++, k++ )
945 meanJ = meanJ / (patchSize.width * patchSize.height) - meanI;
947 for( y = -winSize.height, k = 0; y <= winSize.height; y++ )
949 for( x = -winSize.width; x <= winSize.width; x++, k++ )
951 double t = patchI[k] - patchJ[k] + meanJ;
952 double ixt = Ix[k] * t;
953 double iyt = Iy[k] * t;
966 icvTransformVector_64d( G, b, eta, 6, 6 );
968 Av[2] = (float)(Av[2] + Av[0] * eta[0] + Av[1] * eta[1]);
969 Av[5] = (float)(Av[5] + Av[3] * eta[0] + Av[4] * eta[1]);
971 t0 = Av[0] * (1 + eta[2]) + Av[1] * eta[4];
972 t1 = Av[0] * eta[3] + Av[1] * (1 + eta[5]);
976 t0 = Av[3] * (1 + eta[2]) + Av[4] * eta[4];
977 t1 = Av[3] * eta[3] + Av[4] * (1 + eta[5]);
981 if( eta[0] * eta[0] + eta[1] * eta[1] < criteria.epsilon )
985 if( pt_status != 0 || l == 0 )
987 status[i] = (char)pt_status;
988 featuresB[i].x = Av[2];
989 featuresB[i].y = Av[5];
991 matrices[i*4] = Av[0];
992 matrices[i*4+1] = Av[1];
993 matrices[i*4+2] = Av[3];
994 matrices[i*4+3] = Av[4];
997 if( pt_status && l == 0 && error )
1002 for( y = 0, k = 0; y < patchSize.height; y++ )
1004 for( x = 0; x < patchSize.width; x++, k++ )
1006 double t = patchI[k] - patchJ[k] + meanJ;
1010 error[i] = (float)sqrt(err);
1017 cvFree( &pyr_buffer );
1025 icvGetRTMatrix( const CvPoint2D32f* a, const CvPoint2D32f* b,
1026 int count, CvMat* M, int full_affine )
1030 double sa[36], sb[6];
1031 CvMat A = cvMat( 6, 6, CV_64F, sa ), B = cvMat( 6, 1, CV_64F, sb );
1032 CvMat MM = cvMat( 6, 1, CV_64F, M->data.db );
1036 memset( sa, 0, sizeof(sa) );
1037 memset( sb, 0, sizeof(sb) );
1039 for( i = 0; i < count; i++ )
1041 sa[0] += a[i].x*a[i].x;
1042 sa[1] += a[i].y*a[i].x;
1045 sa[6] += a[i].x*a[i].y;
1046 sa[7] += a[i].y*a[i].y;
1053 sb[0] += a[i].x*b[i].x;
1054 sb[1] += a[i].y*b[i].x;
1056 sb[3] += a[i].x*b[i].y;
1057 sb[4] += a[i].y*b[i].y;
1071 cvSolve( &A, &B, &MM, CV_SVD );
1075 double sa[16], sb[4], m[4], *om = M->data.db;
1076 CvMat A = cvMat( 4, 4, CV_64F, sa ), B = cvMat( 4, 1, CV_64F, sb );
1077 CvMat MM = cvMat( 4, 1, CV_64F, m );
1081 memset( sa, 0, sizeof(sa) );
1082 memset( sb, 0, sizeof(sb) );
1084 for( i = 0; i < count; i++ )
1086 sa[0] += a[i].x*a[i].x + a[i].y*a[i].y;
1092 sa[5] += a[i].x*a[i].x + a[i].y*a[i].y;
1106 sb[0] += a[i].x*b[i].x + a[i].y*b[i].y;
1107 sb[1] += a[i].x*b[i].y - a[i].y*b[i].x;
1112 cvSolve( &A, &B, &MM, CV_SVD );
1114 om[0] = om[4] = m[0];
1124 cvEstimateRigidTransform( const CvArr* _A, const CvArr* _B, CvMat* _M, int full_affine )
1128 const int COUNT = 15;
1129 const int WIDTH = 160, HEIGHT = 120;
1130 const int RANSAC_MAX_ITERS = 100;
1131 const int RANSAC_SIZE0 = 3;
1132 const double MIN_TRIANGLE_SIDE = 20;
1133 const double RANSAC_GOOD_RATIO = 0.5;
1136 CvMat *sA = 0, *sB = 0;
1137 CvPoint2D32f *pA = 0, *pB = 0;
1142 CV_FUNCNAME( "cvEstimateRigidTransform" );
1149 int cn, equal_sizes;
1151 int count_x, count_y, count;
1153 CvRNG rng = cvRNG(-1);
1155 CvMat M = cvMat( 2, 3, CV_64F, m );
1158 CV_CALL( A = cvGetMat( _A, &stubA ));
1159 CV_CALL( B = cvGetMat( _B, &stubB ));
1161 if( !CV_IS_MAT(_M) )
1162 CV_ERROR( _M ? CV_StsBadArg : CV_StsNullPtr, "Output parameter M is not a valid matrix" );
1164 if( !CV_ARE_SIZES_EQ( A, B ) )
1165 CV_ERROR( CV_StsUnmatchedSizes, "Both input images must have the same size" );
1167 if( !CV_ARE_TYPES_EQ( A, B ) )
1168 CV_ERROR( CV_StsUnmatchedFormats, "Both input images must have the same data type" );
1170 if( CV_MAT_TYPE(A->type) == CV_8UC1 || CV_MAT_TYPE(A->type) == CV_8UC3 )
1172 cn = CV_MAT_CN(A->type);
1174 sz1 = cvSize(WIDTH, HEIGHT);
1176 scale = MAX( (double)sz1.width/sz0.width, (double)sz1.height/sz0.height );
1177 scale = MIN( scale, 1. );
1178 sz1.width = cvRound( sz0.width * scale );
1179 sz1.height = cvRound( sz0.height * scale );
1181 equal_sizes = sz1.width == sz0.width && sz1.height == sz0.height;
1183 if( !equal_sizes || cn != 1 )
1185 CV_CALL( sA = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
1186 CV_CALL( sB = cvCreateMat( sz1.height, sz1.width, CV_8UC1 ));
1188 if( !equal_sizes && cn != 1 )
1189 CV_CALL( gray = cvCreateMat( sz0.height, sz0.width, CV_8UC1 ));
1193 cvCvtColor( A, gray, CV_BGR2GRAY );
1194 cvResize( gray, sA, CV_INTER_AREA );
1195 cvCvtColor( B, gray, CV_BGR2GRAY );
1196 cvResize( gray, sB, CV_INTER_AREA );
1200 cvResize( gray, sA, CV_INTER_AREA );
1201 cvResize( gray, sB, CV_INTER_AREA );
1205 cvCvtColor( A, gray, CV_BGR2GRAY );
1206 cvResize( gray, sA, CV_INTER_AREA );
1207 cvCvtColor( B, gray, CV_BGR2GRAY );
1210 cvReleaseMat( &gray );
1216 count_x = cvRound((double)COUNT*sz1.width/sz1.height);
1217 count = count_x * count_y;
1219 CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
1220 CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
1221 CV_CALL( status = (char*)cvAlloc( count*sizeof(status[0]) ));
1223 for( i = 0, k = 0; i < count_y; i++ )
1224 for( j = 0; j < count_x; j++, k++ )
1226 pA[k].x = (j+0.5f)*sz1.width/count_x;
1227 pA[k].y = (i+0.5f)*sz1.height/count_y;
1230 // find the corresponding points in B
1231 cvCalcOpticalFlowPyrLK( A, B, 0, 0, pA, pB, count, cvSize(10,10), 3,
1232 status, 0, cvTermCriteria(CV_TERMCRIT_ITER,40,0.1), 0 );
1234 // repack the remained points
1235 for( i = 0, k = 0; i < count; i++ )
1248 else if( CV_MAT_TYPE(A->type) == CV_32FC2 || CV_MAT_TYPE(A->type) == CV_32SC2 )
1250 count = A->cols*A->rows;
1252 if( CV_IS_MAT_CONT(A->type & B->type) && CV_MAT_TYPE(A->type) == CV_32FC2 )
1254 pA = (CvPoint2D32f*)A->data.ptr;
1255 pB = (CvPoint2D32f*)B->data.ptr;
1262 CV_CALL( pA = (CvPoint2D32f*)cvAlloc( count*sizeof(pA[0]) ));
1263 CV_CALL( pB = (CvPoint2D32f*)cvAlloc( count*sizeof(pB[0]) ));
1264 _pA = cvMat( A->rows, A->cols, CV_32FC2, pA );
1265 _pB = cvMat( B->rows, B->cols, CV_32FC2, pB );
1266 cvConvert( A, &_pA );
1267 cvConvert( B, &_pB );
1271 CV_ERROR( CV_StsUnsupportedFormat, "Both input images must have either 8uC1 or 8uC3 type" );
1273 CV_CALL( good_idx = (int*)cvAlloc( count*sizeof(good_idx[0]) ));
1275 if( count < RANSAC_SIZE0 )
1279 // 1. find the consensus
1280 for( k = 0; k < RANSAC_MAX_ITERS; k++ )
1282 int idx[RANSAC_SIZE0];
1286 memset( a, 0, sizeof(a) );
1287 memset( b, 0, sizeof(b) );
1289 // choose random 3 non-complanar points from A & B
1290 for( i = 0; i < RANSAC_SIZE0; i++ )
1292 for( k1 = 0; k1 < RANSAC_MAX_ITERS; k1++ )
1294 idx[i] = cvRandInt(&rng) % count;
1296 for( j = 0; j < i; j++ )
1298 if( idx[j] == idx[i] )
1300 // check that the points are not very close one each other
1301 if( fabs(pA[idx[i]].x - pA[idx[j]].x) +
1302 fabs(pA[idx[i]].y - pA[idx[j]].y) < MIN_TRIANGLE_SIDE )
1304 if( fabs(pB[idx[i]].x - pB[idx[j]].x) +
1305 fabs(pB[idx[i]].y - pB[idx[j]].y) < MIN_TRIANGLE_SIDE )
1312 if( i+1 == RANSAC_SIZE0 )
1314 // additional check for non-complanar vectors
1323 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 ||
1324 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 )
1330 if( k1 >= RANSAC_MAX_ITERS )
1334 if( i < RANSAC_SIZE0 )
1337 // estimate the transformation using 3 points
1338 icvGetRTMatrix( a, b, 3, &M, full_affine );
1340 for( i = 0, good_count = 0; i < count; i++ )
1342 if( fabs( m[0]*pA[i].x + m[1]*pA[i].y + m[2] - pB[i].x ) +
1343 fabs( m[3]*pA[i].x + m[4]*pA[i].y + m[5] - pB[i].y ) < 8 )
1344 good_idx[good_count++] = i;
1347 if( good_count >= count*RANSAC_GOOD_RATIO )
1351 if( k >= RANSAC_MAX_ITERS )
1354 if( good_count < count )
1356 for( i = 0; i < good_count; i++ )
1364 icvGetRTMatrix( pA, pB, good_count, &M, full_affine );
1367 CV_CALL( cvConvert( &M, _M ));
1372 cvReleaseMat( &sA );
1373 cvReleaseMat( &sB );
1377 cvFree( &good_idx );
1378 cvReleaseMat( &gray );