Update the changelog
[opencv] / cv / include / cvcompat.h
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright( C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 //(including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort(including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 /*
43    A few macros and definitions for backward compatibility
44    with the previous versions of OpenCV. They are obsolete and
45    are likely to be removed in future. To check whether your code
46    uses any of these, define CV_NO_BACKWARD_COMPATIBILITY before
47    including cv.h.
48 */
49
50 #ifndef _CVCOMPAT_H_
51 #define _CVCOMPAT_H_
52
53 #include <string.h>
54
55 #ifdef __cplusplus
56     #define CV_UNREFERENCED(arg)
57 #else
58     #define CV_UNREFERENCED(arg) arg
59 #endif
60
61 #define CvMatType int
62 #define CvDisMaskType int
63 #define CvMatArray CvMat
64
65 #define CvThreshType int
66 #define CvAdaptiveThreshMethod int
67 #define CvCompareMethod int
68 #define CvFontFace int
69 #define CvPolyApproxMethod int
70 #define CvContoursMatchMethod int
71 #define CvContourTreesMatchMethod int
72 #define CvCoeffType int
73 #define CvRodriguesType int
74 #define CvElementShape int
75 #define CvMorphOp int
76 #define CvTemplMatchMethod int
77
78 #define CvPoint2D64d CvPoint2D64f
79 #define CvPoint3D64d CvPoint3D64f
80
81 #define  CV_MAT32F      CV_32FC1
82 #define  CV_MAT3x1_32F  CV_32FC1
83 #define  CV_MAT4x1_32F  CV_32FC1
84 #define  CV_MAT3x3_32F  CV_32FC1
85 #define  CV_MAT4x4_32F  CV_32FC1
86
87 #define  CV_MAT64D      CV_64FC1
88 #define  CV_MAT3x1_64D  CV_64FC1
89 #define  CV_MAT4x1_64D  CV_64FC1
90 #define  CV_MAT3x3_64D  CV_64FC1
91 #define  CV_MAT4x4_64D  CV_64FC1
92
93 #define  IPL_GAUSSIAN_5x5   7
94 #define  CvBox2D32f     CvBox2D
95
96 /* allocation/deallocation macros */
97 #define cvCreateImageData   cvCreateData
98 #define cvReleaseImageData  cvReleaseData
99 #define cvSetImageData      cvSetData
100 #define cvGetImageRawData   cvGetRawData
101
102 #define cvmAlloc            cvCreateData
103 #define cvmFree             cvReleaseData
104 #define cvmAllocArray       cvCreateData
105 #define cvmFreeArray        cvReleaseData
106
107 #define cvIntegralImage     cvIntegral
108 #define cvMatchContours     cvMatchShapes
109
110 CV_INLINE CvMat cvMatArray( int rows, int cols, int type,
111                             int count, void* data CV_DEFAULT(0))
112 {
113     return cvMat( rows*count, cols, type, data );
114 }
115
116 #define cvUpdateMHIByTime  cvUpdateMotionHistory
117
118 #define cvAccMask cvAcc
119 #define cvSquareAccMask cvSquareAcc
120 #define cvMultiplyAccMask cvMultiplyAcc
121 #define cvRunningAvgMask(imgY, imgU, mask, alpha) cvRunningAvg(imgY, imgU, alpha, mask)
122
123 #define cvSetHistThresh  cvSetHistBinRanges
124 #define cvCalcHistMask(img, mask, hist, doNotClear) cvCalcHist(img, hist, doNotClear, mask)
125
126 CV_INLINE double cvMean( const CvArr* image, const CvArr* mask CV_DEFAULT(0))
127 {
128     CvScalar mean = cvAvg( image, mask );
129     return mean.val[0];
130 }
131
132
133 CV_INLINE double  cvSumPixels( const CvArr* image )
134 {
135     CvScalar scalar = cvSum( image );
136     return scalar.val[0];
137 }
138
139 CV_INLINE void  cvMean_StdDev( const CvArr* image, double* mean, double* sdv,
140                                const CvArr* mask CV_DEFAULT(0))
141 {
142     CvScalar _mean, _sdv;
143     cvAvgSdv( image, &_mean, &_sdv, mask );
144
145     if( mean )
146         *mean = _mean.val[0];
147
148     if( sdv )
149         *sdv = _sdv.val[0];
150 }
151
152
153 CV_INLINE void cvmPerspectiveProject( const CvMat* mat, const CvArr* src, CvArr* dst )
154 {
155     CvMat tsrc, tdst;
156
157     cvReshape( src, &tsrc, 3, 0 );
158     cvReshape( dst, &tdst, 3, 0 );
159
160     cvPerspectiveTransform( &tsrc, &tdst, mat );
161 }
162
163
164 CV_INLINE void cvFillImage( CvArr* mat, double color )
165 {
166     cvSet( mat, cvColorToScalar(color, cvGetElemType(mat)), 0 );
167 }
168
169
170 #define cvCvtPixToPlane cvSplit
171 #define cvCvtPlaneToPix cvMerge
172
173 typedef struct CvRandState
174 {
175     CvRNG     state;    /* RNG state (the current seed and carry)*/
176     int       disttype; /* distribution type */
177     CvScalar  param[2]; /* parameters of RNG */
178 }
179 CvRandState;
180
181
182 /* Changes RNG range while preserving RNG state */
183 CV_INLINE  void  cvRandSetRange( CvRandState* state, double param1,
184                                  double param2, int index CV_DEFAULT(-1))
185 {
186     if( !state )
187     {
188         cvError( CV_StsNullPtr, "cvRandSetRange", "Null pointer to RNG state", "cvcompat.h", 0 );
189         return;
190     }
191
192     if( (unsigned)(index + 1) > 4 )
193     {
194         cvError( CV_StsOutOfRange, "cvRandSetRange", "index is not in -1..3", "cvcompat.h", 0 );
195         return;
196     }
197
198     if( index < 0 )
199     {
200         state->param[0].val[0] = state->param[0].val[1] =
201         state->param[0].val[2] = state->param[0].val[3] = param1;
202         state->param[1].val[0] = state->param[1].val[1] =
203         state->param[1].val[2] = state->param[1].val[3] = param2;
204     }
205     else
206     {
207         state->param[0].val[index] = param1;
208         state->param[1].val[index] = param2;
209     }
210 }
211
212
213 CV_INLINE  void  cvRandInit( CvRandState* state, double param1,
214                              double param2, int seed,
215                              int disttype CV_DEFAULT(CV_RAND_UNI))
216 {
217     if( !state )
218     {
219         cvError( CV_StsNullPtr, "cvRandInit", "Null pointer to RNG state", "cvcompat.h", 0 );
220         return;
221     }
222
223     if( disttype != CV_RAND_UNI && disttype != CV_RAND_NORMAL )
224     {
225         cvError( CV_StsBadFlag, "cvRandInit", "Unknown distribution type", "cvcompat.h", 0 );
226         return;
227     }
228
229     state->state = (uint64)(seed ? seed : -1);
230     state->disttype = disttype;
231     cvRandSetRange( state, param1, param2, -1 );
232 }
233
234
235 /* Fills array with random numbers */
236 CV_INLINE void cvRand( CvRandState* state, CvArr* arr )
237 {
238     if( !state )
239     {
240         cvError( CV_StsNullPtr, "cvRand", "Null pointer to RNG state", "cvcompat.h", 0 );
241         return;
242     }
243     cvRandArr( &state->state, arr, state->disttype, state->param[0], state->param[1] );
244 }
245
246 #define cvRandNext( _state ) cvRandInt( &(_state)->state )
247
248 CV_INLINE void cvbRand( CvRandState* state, float* dst, int len )
249 {
250     CvMat mat = cvMat( 1, len, CV_32F, (void*)dst );
251     cvRand( state, &mat );
252 }
253
254
255 CV_INLINE void  cvbCartToPolar( const float* y, const float* x,
256                                 float* magnitude, float* angle, int len )
257 {
258     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
259     CvMat my = mx;
260     CvMat mm = mx;
261     CvMat ma = mx;
262
263     my.data.fl = (float*)y;
264     mm.data.fl = (float*)magnitude;
265     ma.data.fl = (float*)angle;
266
267     cvCartToPolar( &mx, &my, &mm, angle ? &ma : NULL, 1 );
268 }
269
270
271 CV_INLINE void  cvbFastArctan( const float* y, const float* x,
272                                float* angle, int len )
273 {
274     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
275     CvMat my = mx;
276     CvMat ma = mx;
277
278     my.data.fl = (float*)y;
279     ma.data.fl = (float*)angle;
280
281     cvCartToPolar( &mx, &my, NULL, &ma, 1 );
282 }
283
284
285 CV_INLINE  void  cvbSqrt( const float* x, float* y, int len )
286 {
287     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
288     CvMat my = mx;
289     my.data.fl = (float*)y;
290
291     cvPow( &mx, &my, 0.5 );
292 }
293
294
295 CV_INLINE  void  cvbInvSqrt( const float* x, float* y, int len )
296 {
297     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
298     CvMat my = mx;
299     my.data.fl = (float*)y;
300
301     cvPow( &mx, &my, -0.5 );
302 }
303
304
305 CV_INLINE  void  cvbReciprocal( const float* x, float* y, int len )
306 {
307     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
308     CvMat my = mx;
309     my.data.fl = (float*)y;
310
311     cvPow( &mx, &my, -1 );
312 }
313
314
315 CV_INLINE  void  cvbFastExp( const float* x, double* y, int len )
316 {
317     CvMat mx = cvMat( 1, len, CV_32F, (void*)x );
318     CvMat my = cvMat( 1, len, CV_64F, y );
319     cvExp( &mx, &my );
320 }
321
322
323 CV_INLINE  void  cvbFastLog( const double* x, float* y, int len )
324 {
325     CvMat mx = cvMat( 1, len, CV_64F, (void*)x );
326     CvMat my = cvMat( 1, len, CV_32F, y );
327     cvLog( &mx, &my );
328 }
329
330
331 CV_INLINE  CvRect  cvContourBoundingRect( void* point_set, int update CV_DEFAULT(0))
332 {
333     return cvBoundingRect( point_set, update );
334 }
335
336
337 CV_INLINE double cvPseudoInverse( const CvArr* src, CvArr* dst )
338 {
339     return cvInvert( src, dst, CV_SVD );
340 }
341
342 #define cvPseudoInv cvPseudoInverse
343
344 #define cvContourMoments( contour, moments ) \
345     cvMoments( contour, moments, 0 )
346
347 #define cvGetPtrAt              cvPtr2D
348 #define cvGetAt                 cvGet2D
349 #define cvSetAt(arr,val,y,x)    cvSet2D((arr),(y),(x),(val))
350
351 #define cvMeanMask  cvMean
352 #define cvMean_StdDevMask(img,mask,mean,sdv) cvMean_StdDev(img,mean,sdv,mask)
353
354 #define cvNormMask(imgA,imgB,mask,normType) cvNorm(imgA,imgB,normType,mask)
355
356 #define cvMinMaxLocMask(img, mask, min_val, max_val, min_loc, max_loc) \
357         cvMinMaxLoc(img, min_val, max_val, min_loc, max_loc, mask)
358
359 #define cvRemoveMemoryManager  cvSetMemoryManager
360
361 #define cvmSetZero( mat )               cvSetZero( mat )
362 #define cvmSetIdentity( mat )           cvSetIdentity( mat )
363 #define cvmAdd( src1, src2, dst )       cvAdd( src1, src2, dst, 0 )
364 #define cvmSub( src1, src2, dst )       cvSub( src1, src2, dst, 0 )
365 #define cvmCopy( src, dst )             cvCopy( src, dst, 0 )
366 #define cvmMul( src1, src2, dst )       cvMatMulAdd( src1, src2, 0, dst )
367 #define cvmTranspose( src, dst )        cvT( src, dst )
368 #define cvmInvert( src, dst )           cvInv( src, dst )
369 #define cvmMahalanobis(vec1, vec2, mat) cvMahalanobis( vec1, vec2, mat )
370 #define cvmDotProduct( vec1, vec2 )     cvDotProduct( vec1, vec2 )
371 #define cvmCrossProduct(vec1, vec2,dst) cvCrossProduct( vec1, vec2, dst )
372 #define cvmTrace( mat )                 (cvTrace( mat )).val[0]
373 #define cvmMulTransposed( src, dst, order ) cvMulTransposed( src, dst, order )
374 #define cvmEigenVV( mat, evec, eval, eps)   cvEigenVV( mat, evec, eval, eps )
375 #define cvmDet( mat )                   cvDet( mat )
376 #define cvmScale( src, dst, scale )     cvScale( src, dst, scale )
377
378 #define cvCopyImage( src, dst )         cvCopy( src, dst, 0 )
379 #define cvReleaseMatHeader              cvReleaseMat
380
381 /* Calculates exact convex hull of 2d point set */
382 CV_INLINE void cvConvexHull( CvPoint* points, int num_points,
383                              CvRect* CV_UNREFERENCED(bound_rect),
384                              int orientation, int* hull, int* hullsize )
385 {
386     CvMat points1 = cvMat( 1, num_points, CV_32SC2, points );
387     CvMat hull1 = cvMat( 1, num_points, CV_32SC1, hull );
388
389     cvConvexHull2( &points1, &hull1, orientation, 0 );
390     *hullsize = hull1.cols;
391 }
392
393 /* Calculates exact convex hull of 2d point set stored in a sequence */
394 #define cvContourConvexHull( contour, orientation, storage ) \
395     cvConvexHull2( contour, storage, orientation )
396
397 /* Calculates approximate convex hull of 2d point set */
398 #define cvConvexHullApprox( points, num_points, bound_rect, bandwidth,      \
399                             orientation, hull, hullsize )                   \
400 cvConvexHull( points, num_points, bound_rect, orientation, hull, hullsize )
401
402 /* Calculates approximate convex hull of 2d point set stored in a sequence */
403 #define cvContourConvexHullApprox( contour, bandwidth, orientation, storage )   \
404     cvConvexHull2( contour, storage, orientation )
405
406
407 CV_INLINE void cvMinAreaRect( CvPoint* points, int n,
408                               int CV_UNREFERENCED(left), int CV_UNREFERENCED(bottom),
409                               int CV_UNREFERENCED(right), int CV_UNREFERENCED(top),
410                               CvPoint2D32f* anchor,
411                               CvPoint2D32f* vect1,
412                               CvPoint2D32f* vect2 )
413 {
414     CvMat mat = cvMat( 1, n, CV_32SC2, points );
415     CvBox2D box = cvMinAreaRect2( &mat, 0 );
416     CvPoint2D32f pt[4];
417
418     cvBoxPoints( box, pt );
419     *anchor = pt[0];
420     vect1->x = pt[1].x - pt[0].x;
421     vect1->y = pt[1].y - pt[0].y;
422     vect2->x = pt[3].x - pt[0].x;
423     vect2->y = pt[3].y - pt[0].y;
424
425     CV_UNREFERENCED( (left, bottom, right, top) );
426 }
427
428 typedef int CvDisType;
429 typedef int CvChainApproxMethod;
430 typedef int CvContourRetrievalMode;
431
432 CV_INLINE  void  cvFitLine3D( CvPoint3D32f* points, int count, int dist,
433                               void *param, float reps, float aeps, float* line )
434 {
435     CvMat mat = cvMat( 1, count, CV_32FC3, points );
436     float _param = param != NULL ? *(float*)param : 0.f;
437     assert( dist != CV_DIST_USER );
438     cvFitLine( &mat, dist, _param, reps, aeps, line );
439 }
440
441 /* Fits a line into set of 2d points in a robust way (M-estimator technique) */
442 CV_INLINE  void  cvFitLine2D( CvPoint2D32f* points, int count, int dist,
443                               void *param, float reps, float aeps, float* line )
444 {
445     CvMat mat = cvMat( 1, count, CV_32FC2, points );
446     float _param = param != NULL ? *(float*)param : 0.f;
447     assert( dist != CV_DIST_USER );
448     cvFitLine( &mat, dist, _param, reps, aeps, line );
449 }
450
451
452 CV_INLINE  void cvFitEllipse( const CvPoint2D32f* points, int count, CvBox2D* box )
453 {
454     CvMat mat = cvMat( 1, count, CV_32FC2, (void*)points );
455     *box = cvFitEllipse2( &mat );
456 }
457
458 /* Projects 2d points to one of standard coordinate planes
459    (i.e. removes one of coordinates) */
460 CV_INLINE  void  cvProject3D( CvPoint3D32f* points3D, int count,
461                               CvPoint2D32f* points2D,
462                               int xIndx CV_DEFAULT(0),
463                               int yIndx CV_DEFAULT(1))
464 {
465     CvMat src = cvMat( 1, count, CV_32FC3, points3D );
466     CvMat dst = cvMat( 1, count, CV_32FC2, points2D );
467     float m[6] = {0,0,0,0,0,0};
468     CvMat M = cvMat( 2, 3, CV_32F, m );
469
470     assert( (unsigned)xIndx < 3 && (unsigned)yIndx < 3 );
471     m[xIndx] = m[yIndx+3] = 1.f;
472
473     cvTransform( &src, &dst, &M, NULL );
474 }
475
476
477 /* Retrieves value of the particular bin
478    of x-dimensional (x=1,2,3,...) histogram */
479 #define cvQueryHistValue_1D( hist, idx0 ) \
480     ((float)cvGetReal1D( (hist)->bins, (idx0)))
481 #define cvQueryHistValue_2D( hist, idx0, idx1 ) \
482     ((float)cvGetReal2D( (hist)->bins, (idx0), (idx1)))
483 #define cvQueryHistValue_3D( hist, idx0, idx1, idx2 ) \
484     ((float)cvGetReal3D( (hist)->bins, (idx0), (idx1), (idx2)))
485 #define cvQueryHistValue_nD( hist, idx ) \
486     ((float)cvGetRealND( (hist)->bins, (idx)))
487
488 /* Returns pointer to the particular bin of x-dimesional histogram.
489    For sparse histogram the bin is created if it didn't exist before */
490 #define cvGetHistValue_1D( hist, idx0 ) \
491     ((float*)cvPtr1D( (hist)->bins, (idx0), 0))
492 #define cvGetHistValue_2D( hist, idx0, idx1 ) \
493     ((float*)cvPtr2D( (hist)->bins, (idx0), (idx1), 0))
494 #define cvGetHistValue_3D( hist, idx0, idx1, idx2 ) \
495     ((float*)cvPtr3D( (hist)->bins, (idx0), (idx1), (idx2), 0))
496 #define cvGetHistValue_nD( hist, idx ) \
497     ((float*)cvPtrND( (hist)->bins, (idx), 0))
498
499
500 #define CV_IS_SET_ELEM_EXISTS CV_IS_SET_ELEM
501
502
503 CV_INLINE  int  cvHoughLines( CvArr* image, double rho,
504                               double theta, int threshold,
505                               float* lines, int linesNumber )
506 {
507     CvMat linesMat = cvMat( 1, linesNumber, CV_32FC2, lines );
508     cvHoughLines2( image, &linesMat, CV_HOUGH_STANDARD,
509                    rho, theta, threshold, 0, 0 );
510
511     return linesMat.cols;
512 }
513
514
515 CV_INLINE  int  cvHoughLinesP( CvArr* image, double rho,
516                                double theta, int threshold,
517                                int lineLength, int lineGap,
518                                int* lines, int linesNumber )
519 {
520     CvMat linesMat = cvMat( 1, linesNumber, CV_32SC4, lines );
521     cvHoughLines2( image, &linesMat, CV_HOUGH_PROBABILISTIC,
522                    rho, theta, threshold, lineLength, lineGap );
523
524     return linesMat.cols;
525 }
526
527
528 CV_INLINE  int  cvHoughLinesSDiv( CvArr* image, double rho, int srn,
529                                   double theta, int stn, int threshold,
530                                   float* lines, int linesNumber )
531 {
532     CvMat linesMat = cvMat( 1, linesNumber, CV_32FC2, lines );
533     cvHoughLines2( image, &linesMat, CV_HOUGH_MULTI_SCALE,
534                    rho, theta, threshold, srn, stn );
535
536     return linesMat.cols;
537 }
538
539
540 /* Find fundamental matrix */
541 CV_INLINE  void  cvFindFundamentalMatrix( int* points1, int* points2,
542                             int numpoints, int CV_UNREFERENCED(method), float* matrix )
543 {
544     CvMat* pointsMat1;
545     CvMat* pointsMat2;
546     CvMat fundMatr = cvMat(3,3,CV_32F,matrix);
547     int i, curr = 0;
548
549     pointsMat1 = cvCreateMat(3,numpoints,CV_64F);
550     pointsMat2 = cvCreateMat(3,numpoints,CV_64F);
551
552     for( i = 0; i < numpoints; i++ )
553     {
554         cvmSet(pointsMat1,0,i,points1[curr]);//x
555         cvmSet(pointsMat1,1,i,points1[curr+1]);//y
556         cvmSet(pointsMat1,2,i,1.0);
557
558         cvmSet(pointsMat2,0,i,points2[curr]);//x
559         cvmSet(pointsMat2,1,i,points2[curr+1]);//y
560         cvmSet(pointsMat2,2,i,1.0);
561         curr += 2;
562     }
563
564     cvFindFundamentalMat(pointsMat1,pointsMat2,&fundMatr,CV_FM_RANSAC,1,0.99,0);
565
566     cvReleaseMat(&pointsMat1);
567     cvReleaseMat(&pointsMat2);
568 }
569
570
571
572 CV_INLINE int
573 cvFindChessBoardCornerGuesses( const void* arr, void* CV_UNREFERENCED(thresharr),
574                                CvMemStorage * CV_UNREFERENCED(storage),
575                                CvSize pattern_size, CvPoint2D32f * corners,
576                                int *corner_count )
577 {
578     return cvFindChessboardCorners( arr, pattern_size, corners,
579                                     corner_count, CV_CALIB_CB_ADAPTIVE_THRESH );
580 }
581
582
583 /* Calibrates camera using multiple views of calibration pattern */
584 CV_INLINE void cvCalibrateCamera( int image_count, int* _point_counts,
585     CvSize image_size, CvPoint2D32f* _image_points, CvPoint3D32f* _object_points,
586     float* _distortion_coeffs, float* _camera_matrix, float* _translation_vectors,
587     float* _rotation_matrices, int flags )
588 {
589     int i, total = 0;
590     CvMat point_counts = cvMat( image_count, 1, CV_32SC1, _point_counts );
591     CvMat image_points, object_points;
592     CvMat dist_coeffs = cvMat( 4, 1, CV_32FC1, _distortion_coeffs );
593     CvMat camera_matrix = cvMat( 3, 3, CV_32FC1, _camera_matrix );
594     CvMat rotation_matrices = cvMat( image_count, 9, CV_32FC1, _rotation_matrices );
595     CvMat translation_vectors = cvMat( image_count, 3, CV_32FC1, _translation_vectors );
596
597     for( i = 0; i < image_count; i++ )
598         total += _point_counts[i];
599
600     image_points = cvMat( total, 1, CV_32FC2, _image_points );
601     object_points = cvMat( total, 1, CV_32FC3, _object_points );
602
603     cvCalibrateCamera2( &object_points, &image_points, &point_counts, image_size,
604         &camera_matrix, &dist_coeffs, &rotation_matrices, &translation_vectors,
605         flags );
606 }
607
608
609 CV_INLINE void cvCalibrateCamera_64d( int image_count, int* _point_counts,
610     CvSize image_size, CvPoint2D64f* _image_points, CvPoint3D64f* _object_points,
611     double* _distortion_coeffs, double* _camera_matrix, double* _translation_vectors,
612     double* _rotation_matrices, int flags )
613 {
614     int i, total = 0;
615     CvMat point_counts = cvMat( image_count, 1, CV_32SC1, _point_counts );
616     CvMat image_points, object_points;
617     CvMat dist_coeffs = cvMat( 4, 1, CV_64FC1, _distortion_coeffs );
618     CvMat camera_matrix = cvMat( 3, 3, CV_64FC1, _camera_matrix );
619     CvMat rotation_matrices = cvMat( image_count, 9, CV_64FC1, _rotation_matrices );
620     CvMat translation_vectors = cvMat( image_count, 3, CV_64FC1, _translation_vectors );
621
622     for( i = 0; i < image_count; i++ )
623         total += _point_counts[i];
624
625     image_points = cvMat( total, 1, CV_64FC2, _image_points );
626     object_points = cvMat( total, 1, CV_64FC3, _object_points );
627
628     cvCalibrateCamera2( &object_points, &image_points, &point_counts, image_size,
629         &camera_matrix, &dist_coeffs, &rotation_matrices, &translation_vectors,
630         flags );
631 }
632
633
634
635 /* Find 3d position of object given intrinsic camera parameters,
636    3d model of the object and projection of the object into view plane */
637 CV_INLINE void cvFindExtrinsicCameraParams( int point_count,
638     CvSize CV_UNREFERENCED(image_size), CvPoint2D32f* _image_points,
639     CvPoint3D32f* _object_points, float* focal_length,
640     CvPoint2D32f principal_point, float* _distortion_coeffs,
641     float* _rotation_vector, float* _translation_vector )
642 {
643     CvMat image_points = cvMat( point_count, 1, CV_32FC2, _image_points );
644     CvMat object_points = cvMat( point_count, 1, CV_32FC3, _object_points );
645     CvMat dist_coeffs = cvMat( 4, 1, CV_32FC1, _distortion_coeffs );
646     float a[9];
647     CvMat camera_matrix = cvMat( 3, 3, CV_32FC1, a );
648     CvMat rotation_vector = cvMat( 1, 1, CV_32FC3, _rotation_vector );
649     CvMat translation_vector = cvMat( 1, 1, CV_32FC3, _translation_vector );
650
651     a[0] = focal_length[0]; a[4] = focal_length[1];
652     a[2] = principal_point.x; a[5] = principal_point.y;
653     a[1] = a[3] = a[6] = a[7] = 0.f;
654     a[8] = 1.f;
655
656     cvFindExtrinsicCameraParams2( &object_points, &image_points, &camera_matrix,
657         &dist_coeffs, &rotation_vector, &translation_vector );
658 }
659
660
661 /* Variant of the previous function that takes double-precision parameters */
662 CV_INLINE void cvFindExtrinsicCameraParams_64d( int point_count,
663     CvSize CV_UNREFERENCED(image_size), CvPoint2D64f* _image_points,
664     CvPoint3D64f* _object_points, double* focal_length,
665     CvPoint2D64f principal_point, double* _distortion_coeffs,
666     double* _rotation_vector, double* _translation_vector )
667 {
668     CvMat image_points = cvMat( point_count, 1, CV_64FC2, _image_points );
669     CvMat object_points = cvMat( point_count, 1, CV_64FC3, _object_points );
670     CvMat dist_coeffs = cvMat( 4, 1, CV_64FC1, _distortion_coeffs );
671     double a[9];
672     CvMat camera_matrix = cvMat( 3, 3, CV_64FC1, a );
673     CvMat rotation_vector = cvMat( 1, 1, CV_64FC3, _rotation_vector );
674     CvMat translation_vector = cvMat( 1, 1, CV_64FC3, _translation_vector );
675
676     a[0] = focal_length[0]; a[4] = focal_length[1];
677     a[2] = principal_point.x; a[5] = principal_point.y;
678     a[1] = a[3] = a[6] = a[7] = 0.;
679     a[8] = 1.;
680
681     cvFindExtrinsicCameraParams2( &object_points, &image_points, &camera_matrix,
682         &dist_coeffs, &rotation_vector, &translation_vector );
683 }
684
685
686 /* Rodrigues transform */
687 #define CV_RODRIGUES_M2V  0
688 #define CV_RODRIGUES_V2M  1
689
690 /* Converts rotation_matrix matrix to rotation_matrix vector or vice versa */
691 CV_INLINE void  cvRodrigues( CvMat* rotation_matrix, CvMat* rotation_vector,
692                              CvMat* jacobian, int conv_type )
693 {
694     if( conv_type == CV_RODRIGUES_V2M )
695         cvRodrigues2( rotation_vector, rotation_matrix, jacobian );
696     else
697         cvRodrigues2( rotation_matrix, rotation_vector, jacobian );
698 }
699
700
701 /* Does reprojection of 3d object points to the view plane */
702 CV_INLINE void  cvProjectPoints( int point_count, CvPoint3D64f* _object_points,
703     double* _rotation_vector, double*  _translation_vector,
704     double* focal_length, CvPoint2D64f principal_point,
705     double* _distortion, CvPoint2D64f* _image_points,
706     double* _deriv_points_rotation_matrix,
707     double* _deriv_points_translation_vect,
708     double* _deriv_points_focal,
709     double* _deriv_points_principal_point,
710     double* _deriv_points_distortion_coeffs )
711 {
712     CvMat object_points = cvMat( point_count, 1, CV_64FC3, _object_points );
713     CvMat image_points = cvMat( point_count, 1, CV_64FC2, _image_points );
714     CvMat rotation_vector = cvMat( 3, 1, CV_64FC1, _rotation_vector );
715     CvMat translation_vector = cvMat( 3, 1, CV_64FC1, _translation_vector );
716     double a[9];
717     CvMat camera_matrix = cvMat( 3, 3, CV_64FC1, a );
718     CvMat dist_coeffs = cvMat( 4, 1, CV_64FC1, _distortion );
719     CvMat dpdr = cvMat( 2*point_count, 3, CV_64FC1, _deriv_points_rotation_matrix );
720     CvMat dpdt = cvMat( 2*point_count, 3, CV_64FC1, _deriv_points_translation_vect );
721     CvMat dpdf = cvMat( 2*point_count, 2, CV_64FC1, _deriv_points_focal );
722     CvMat dpdc = cvMat( 2*point_count, 2, CV_64FC1, _deriv_points_principal_point );
723     CvMat dpdk = cvMat( 2*point_count, 4, CV_64FC1, _deriv_points_distortion_coeffs );
724
725     a[0] = focal_length[0]; a[4] = focal_length[1];
726     a[2] = principal_point.x; a[5] = principal_point.y;
727     a[1] = a[3] = a[6] = a[7] = 0.;
728     a[8] = 1.;
729
730     cvProjectPoints2( &object_points, &rotation_vector, &translation_vector,
731                       &camera_matrix, &dist_coeffs, &image_points,
732                       &dpdr, &dpdt, &dpdf, &dpdc, &dpdk );
733 }
734
735
736 /* Simpler version of the previous function */
737 CV_INLINE void  cvProjectPointsSimple( int point_count, CvPoint3D64f* _object_points,
738     double* _rotation_matrix, double*  _translation_vector,
739     double* _camera_matrix, double* _distortion, CvPoint2D64f* _image_points )
740 {
741     CvMat object_points = cvMat( point_count, 1, CV_64FC3, _object_points );
742     CvMat image_points = cvMat( point_count, 1, CV_64FC2, _image_points );
743     CvMat rotation_matrix = cvMat( 3, 3, CV_64FC1, _rotation_matrix );
744     CvMat translation_vector = cvMat( 3, 1, CV_64FC1, _translation_vector );
745     CvMat camera_matrix = cvMat( 3, 3, CV_64FC1, _camera_matrix );
746     CvMat dist_coeffs = cvMat( 4, 1, CV_64FC1, _distortion );
747
748     cvProjectPoints2( &object_points, &rotation_matrix, &translation_vector,
749                       &camera_matrix, &dist_coeffs, &image_points,
750                       0, 0, 0, 0, 0 );
751 }
752
753
754 CV_INLINE void cvUnDistortOnce( const CvArr* src, CvArr* dst,
755                                 const float* intrinsic_matrix,
756                                 const float* distortion_coeffs,
757                                 int CV_UNREFERENCED(interpolate) )
758 {
759     CvMat _a = cvMat( 3, 3, CV_32F, (void*)intrinsic_matrix );
760     CvMat _k = cvMat( 4, 1, CV_32F, (void*)distortion_coeffs );
761     cvUndistort2( src, dst, &_a, &_k );
762 }
763
764
765 /* the two functions below have quite hackerish implementations, use with care
766    (or, which is better, switch to cvUndistortInitMap and cvRemap instead */
767 CV_INLINE void cvUnDistortInit( const CvArr* CV_UNREFERENCED(src),
768                                 CvArr* undistortion_map,
769                                 const float* A, const float* k,
770                                 int CV_UNREFERENCED(interpolate) )
771 {
772     union { uchar* ptr; float* fl; } data;
773     CvSize sz;
774     cvGetRawData( undistortion_map, &data.ptr, 0, &sz );
775     assert( sz.width >= 8 );
776     /* just save the intrinsic parameters to the map */
777     data.fl[0] = A[0]; data.fl[1] = A[4];
778     data.fl[2] = A[2]; data.fl[3] = A[5];
779     data.fl[4] = k[0]; data.fl[5] = k[1];
780     data.fl[6] = k[2]; data.fl[7] = k[3];
781 }
782
783 CV_INLINE void  cvUnDistort( const CvArr* src, CvArr* dst,
784                              const CvArr* undistortion_map,
785                              int CV_UNREFERENCED(interpolate) )
786 {
787     union { uchar* ptr; float* fl; } data;
788     float a[] = {0,0,0,0,0,0,0,0,1};
789     CvSize sz;
790     cvGetRawData( undistortion_map, &data.ptr, 0, &sz );
791     assert( sz.width >= 8 );
792     a[0] = data.fl[0]; a[4] = data.fl[1];
793     a[2] = data.fl[2]; a[5] = data.fl[3];
794     cvUnDistortOnce( src, dst, a, data.fl + 4, 1 );
795 }
796
797
798 CV_INLINE  float  cvCalcEMD( const float* signature1, int size1,
799                              const float* signature2, int size2,
800                              int dims, int dist_type CV_DEFAULT(CV_DIST_L2),
801                              CvDistanceFunction dist_func CV_DEFAULT(0),
802                              float* lower_bound CV_DEFAULT(0),
803                              void* user_param CV_DEFAULT(0))
804 {
805     CvMat sign1 = cvMat( size1, dims + 1, CV_32FC1, (void*)signature1 );
806     CvMat sign2 = cvMat( size2, dims + 1, CV_32FC1, (void*)signature2 );
807
808     return cvCalcEMD2( &sign1, &sign2, dist_type, dist_func, 0, 0, lower_bound, user_param );
809 }
810
811
812 CV_INLINE  void  cvKMeans( int num_clusters, float** samples,
813                            int num_samples, int vec_size,
814                            CvTermCriteria termcrit, int* cluster_idx )
815 {
816     CvMat* samples_mat = cvCreateMat( num_samples, vec_size, CV_32FC1 );
817     CvMat cluster_idx_mat = cvMat( num_samples, 1, CV_32SC1, cluster_idx );
818     int i;
819     for( i = 0; i < num_samples; i++ )
820         memcpy( samples_mat->data.fl + i*vec_size, samples[i], vec_size*sizeof(float));
821     cvKMeans2( samples_mat, num_clusters, &cluster_idx_mat, termcrit );
822     cvReleaseMat( &samples_mat );
823 }
824
825
826 CV_INLINE void  cvStartScanGraph( CvGraph* graph, CvGraphScanner* scanner,
827                                   CvGraphVtx* vtx CV_DEFAULT(NULL),
828                                   int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS))
829 {
830     CvGraphScanner* temp_scanner;
831
832     if( !scanner )
833         cvError( CV_StsNullPtr, "cvStartScanGraph", "Null scanner pointer", "cvcompat.h", 0 );
834
835     temp_scanner = cvCreateGraphScanner( graph, vtx, mask );
836     *scanner = *temp_scanner;
837     cvFree( &temp_scanner );
838 }
839
840
841 CV_INLINE  void  cvEndScanGraph( CvGraphScanner* scanner )
842 {
843     if( !scanner )
844         cvError( CV_StsNullPtr, "cvEndScanGraph", "Null scanner pointer", "cvcompat.h", 0 );
845
846     if( scanner->stack )
847     {
848         CvGraphScanner* temp_scanner = (CvGraphScanner*)cvAlloc( sizeof(*temp_scanner) );
849         *temp_scanner = *scanner;
850         cvReleaseGraphScanner( &temp_scanner );
851         memset( scanner, 0, sizeof(*scanner) );
852     }
853 }
854
855
856 #define cvKalmanUpdateByTime  cvKalmanPredict
857 #define cvKalmanUpdateByMeasurement cvKalmanCorrect
858
859 /* old drawing functions */
860 CV_INLINE  void  cvLineAA( CvArr* img, CvPoint pt1, CvPoint pt2,
861                            double color, int scale CV_DEFAULT(0))
862 {
863     cvLine( img, pt1, pt2, cvColorToScalar(color, cvGetElemType(img)), 1, CV_AA, scale );
864 }
865
866 CV_INLINE  void  cvCircleAA( CvArr* img, CvPoint center, int radius,
867                              double color, int scale CV_DEFAULT(0) )
868 {
869     cvCircle( img, center, radius, cvColorToScalar(color, cvGetElemType(img)), 1, CV_AA, scale );
870 }
871
872 CV_INLINE  void  cvEllipseAA( CvArr* img, CvPoint center, CvSize axes,
873                               double angle, double start_angle,
874                               double end_angle, double color,
875                               int scale CV_DEFAULT(0) )
876 {
877     cvEllipse( img, center, axes, angle, start_angle, end_angle,
878                cvColorToScalar(color, cvGetElemType(img)), 1, CV_AA, scale );
879 }
880
881 CV_INLINE  void  cvPolyLineAA( CvArr* img, CvPoint** pts, int* npts, int contours,
882                                int is_closed, double color, int scale CV_DEFAULT(0) )
883 {
884     cvPolyLine( img, pts, npts, contours, is_closed,
885                 cvColorToScalar(color, cvGetElemType(img)),
886                 1, CV_AA, scale );
887 }
888
889
890 #define cvMake2DPoints cvConvertPointsHomogenious
891 #define cvMake3DPoints cvConvertPointsHomogenious
892
893 #define cvWarpPerspectiveQMatrix cvGetPerspectiveTransform
894
895 /****************************************************************************************\
896 *                                   Pixel Access Macros                                  *
897 \****************************************************************************************/
898
899 typedef struct _CvPixelPosition8u
900 {
901     uchar*  currline;      /* pointer to the start of the current pixel line   */
902     uchar*  topline;       /* pointer to the start of the top pixel line       */
903     uchar*  bottomline;    /* pointer to the start of the first line           */
904                                     /* which is below the image                         */
905     int     x;                      /* current x coordinate ( in pixels )               */
906     int     width;                  /* width of the image  ( in pixels )                */
907     int     height;                 /* height of the image  ( in pixels )               */
908     int     step;                   /* distance between lines ( in elements of single   */
909                                     /* plane )                                          */
910     int     step_arr[3];            /* array: ( 0, -step, step ). It is used for        */
911                                     /* vertical moving                                  */
912 } CvPixelPosition8u;
913
914 /* this structure differs from the above only in data type */
915 typedef struct _CvPixelPosition8s
916 {
917     schar*  currline;
918     schar*  topline;
919     schar*  bottomline;
920     int     x;
921     int     width;
922     int     height;
923     int     step;
924     int     step_arr[3];
925 } CvPixelPosition8s;
926
927 /* this structure differs from the CvPixelPosition8u only in data type */
928 typedef struct _CvPixelPosition32f
929 {
930     float*  currline;
931     float*  topline;
932     float*  bottomline;
933     int     x;
934     int     width;
935     int     height;
936     int     step;
937     int     step_arr[3];
938 } CvPixelPosition32f;
939
940
941 /* Initialize one of the CvPixelPosition structures.   */
942 /*  pos    - initialized structure                     */
943 /*  origin - pointer to the left-top corner of the ROI */
944 /*  step   - width of the whole image in bytes         */
945 /*  roi    - width & height of the ROI                 */
946 /*  x, y   - initial position                          */
947 #define CV_INIT_PIXEL_POS(pos, origin, _step, roi, _x, _y, orientation)    \
948     (                                                                        \
949     (pos).step = (_step)/sizeof((pos).currline[0]) * (orientation ? -1 : 1), \
950     (pos).width = (roi).width,                                               \
951     (pos).height = (roi).height,                                             \
952     (pos).bottomline = (origin) + (pos).step*(pos).height,                   \
953     (pos).topline = (origin) - (pos).step,                                   \
954     (pos).step_arr[0] = 0,                                                   \
955     (pos).step_arr[1] = -(pos).step,                                         \
956     (pos).step_arr[2] = (pos).step,                                          \
957     (pos).x = (_x),                                                          \
958     (pos).currline = (origin) + (pos).step*(_y) )
959
960
961 /* Move to specified point ( absolute shift ) */
962 /*  pos    - position structure               */
963 /*  x, y   - coordinates of the new position  */
964 /*  cs     - number of the image channels     */
965 #define CV_MOVE_TO( pos, _x, _y, cs )                                                   \
966 ((pos).currline = (_y) >= 0 && (_y) < (pos).height ? (pos).topline + ((_y)+1)*(pos).step : 0, \
967  (pos).x = (_x) >= 0 && (_x) < (pos).width ? (_x) : 0, (pos).currline + (_x) * (cs) )
968
969 /* Get current coordinates                    */
970 /*  pos    - position structure               */
971 /*  x, y   - coordinates of the new position  */
972 /*  cs     - number of the image channels     */
973 #define CV_GET_CURRENT( pos, cs )  ((pos).currline + (pos).x * (cs))
974
975 /* Move by one pixel relatively to current position */
976 /*  pos    - position structure                     */
977 /*  cs     - number of the image channels           */
978
979 /* left */
980 #define CV_MOVE_LEFT( pos, cs ) \
981  ( --(pos).x >= 0 ? (pos).currline + (pos).x*(cs) : 0 )
982
983 /* right */
984 #define CV_MOVE_RIGHT( pos, cs ) \
985  ( ++(pos).x < (pos).width ? (pos).currline + (pos).x*(cs) : 0 )
986
987 /* up */
988 #define CV_MOVE_UP( pos, cs ) \
989  (((pos).currline -= (pos).step) != (pos).topline ? (pos).currline + (pos).x*(cs) : 0 )
990
991 /* down */
992 #define CV_MOVE_DOWN( pos, cs ) \
993  (((pos).currline += (pos).step) != (pos).bottomline ? (pos).currline + (pos).x*(cs) : 0 )
994
995 /* left up */
996 #define CV_MOVE_LU( pos, cs ) ( CV_MOVE_LEFT(pos, cs), CV_MOVE_UP(pos, cs))
997
998 /* right up */
999 #define CV_MOVE_RU( pos, cs ) ( CV_MOVE_RIGHT(pos, cs), CV_MOVE_UP(pos, cs))
1000
1001 /* left down */
1002 #define CV_MOVE_LD( pos, cs ) ( CV_MOVE_LEFT(pos, cs), CV_MOVE_DOWN(pos, cs))
1003
1004 /* right down */
1005 #define CV_MOVE_RD( pos, cs ) ( CV_MOVE_RIGHT(pos, cs), CV_MOVE_DOWN(pos, cs))
1006
1007
1008
1009 /* Move by one pixel relatively to current position with wrapping when the position     */
1010 /* achieves image boundary                                                              */
1011 /*  pos    - position structure                                                         */
1012 /*  cs     - number of the image channels                                               */
1013
1014 /* left */
1015 #define CV_MOVE_LEFT_WRAP( pos, cs ) \
1016  ((pos).currline + ( --(pos).x >= 0 ? (pos).x : ((pos).x = (pos).width-1))*(cs))
1017
1018 /* right */
1019 #define CV_MOVE_RIGHT_WRAP( pos, cs ) \
1020  ((pos).currline + ( ++(pos).x < (pos).width ? (pos).x : ((pos).x = 0))*(cs) )
1021
1022 /* up */
1023 #define CV_MOVE_UP_WRAP( pos, cs ) \
1024     ((((pos).currline -= (pos).step) != (pos).topline ? \
1025     (pos).currline : ((pos).currline = (pos).bottomline - (pos).step)) + (pos).x*(cs) )
1026
1027 /* down */
1028 #define CV_MOVE_DOWN_WRAP( pos, cs ) \
1029     ((((pos).currline += (pos).step) != (pos).bottomline ? \
1030     (pos).currline : ((pos).currline = (pos).topline + (pos).step)) + (pos).x*(cs) )
1031
1032 /* left up */
1033 #define CV_MOVE_LU_WRAP( pos, cs ) ( CV_MOVE_LEFT_WRAP(pos, cs), CV_MOVE_UP_WRAP(pos, cs))
1034 /* right up */
1035 #define CV_MOVE_RU_WRAP( pos, cs ) ( CV_MOVE_RIGHT_WRAP(pos, cs), CV_MOVE_UP_WRAP(pos, cs))
1036 /* left down */
1037 #define CV_MOVE_LD_WRAP( pos, cs ) ( CV_MOVE_LEFT_WRAP(pos, cs), CV_MOVE_DOWN_WRAP(pos, cs))
1038 /* right down */
1039 #define CV_MOVE_RD_WRAP( pos, cs ) ( CV_MOVE_RIGHT_WRAP(pos, cs), CV_MOVE_DOWN_WRAP(pos, cs))
1040
1041 /* Numeric constants which used for moving in arbitrary direction  */
1042 #define CV_SHIFT_NONE   2
1043 #define CV_SHIFT_LEFT   1
1044 #define CV_SHIFT_RIGHT  3
1045 #define CV_SHIFT_UP     6
1046 #define CV_SHIFT_DOWN  10
1047 #define CV_SHIFT_LU     5
1048 #define CV_SHIFT_RU     7
1049 #define CV_SHIFT_LD     9
1050 #define CV_SHIFT_RD    11
1051
1052 /* Move by one pixel in specified direction                                     */
1053 /*  pos    - position structure                                                 */
1054 /*  shift  - direction ( it's value must be one of the CV_SHIFT_\85 constants ) */
1055 /*  cs     - number of the image channels                                       */
1056 #define CV_MOVE_PARAM( pos, shift, cs )                                             \
1057     ( (pos).currline += (pos).step_arr[(shift)>>2], (pos).x += ((shift)&3)-2,       \
1058     ((pos).currline != (pos).topline && (pos).currline != (pos).bottomline &&       \
1059     (pos).x >= 0 && (pos).x < (pos).width) ? (pos).currline + (pos).x*(cs) : 0 )
1060
1061 /* Move by one pixel in specified direction with wrapping when the               */
1062 /* position achieves image boundary                                              */
1063 /*  pos    - position structure                                                  */
1064 /*  shift  - direction ( it's value must be one of the CV_SHIFT_\85 constants )  */
1065 /*  cs     - number of the image channels                                        */
1066 #define CV_MOVE_PARAM_WRAP( pos, shift, cs )                                        \
1067     ( (pos).currline += (pos).step_arr[(shift)>>2],                                 \
1068     (pos).currline = ((pos).currline == (pos).topline ?                             \
1069     (pos).bottomline - (pos).step :                                                 \
1070     (pos).currline == (pos).bottomline ?                                            \
1071     (pos).topline + (pos).step : (pos).currline),                                   \
1072                                                                                     \
1073     (pos).x += ((shift)&3)-2,                                                       \
1074     (pos).x = ((pos).x < 0 ? (pos).width-1 : (pos).x >= (pos).width ? 0 : (pos).x), \
1075                                                                                     \
1076     (pos).currline + (pos).x*(cs) )
1077
1078 #endif/*_CVCOMPAT_H_*/