include/opencv2/legacy/legacy.hpp
Go to the documentation of this file.
00001 /*M///////////////////////////////////////////////////////////////////////////////////////
00002 //
00003 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
00004 //
00005 //  By downloading, copying, installing or using the software you agree to this license.
00006 //  If you do not agree to this license, do not download, install,
00007 //  copy or use the software.
00008 //
00009 //
00010 //                        Intel License Agreement
00011 //                For Open Source Computer Vision Library
00012 //
00013 // Copyright (C) 2000, Intel Corporation, all rights reserved.
00014 // Third party copyrights are property of their respective owners.
00015 //
00016 // Redistribution and use in source and binary forms, with or without modification,
00017 // are permitted provided that the following conditions are met:
00018 //
00019 //   * Redistribution's of source code must retain the above copyright notice,
00020 //     this list of conditions and the following disclaimer.
00021 //
00022 //   * Redistribution's in binary form must reproduce the above copyright notice,
00023 //     this list of conditions and the following disclaimer in the documentation
00024 //     and/or other materials provided with the distribution.
00025 //
00026 //   * The name of Intel Corporation may not be used to endorse or promote products
00027 //     derived from this software without specific prior written permission.
00028 //
00029 // This software is provided by the copyright holders and contributors "as is" and
00030 // any express or implied warranties, including, but not limited to, the implied
00031 // warranties of merchantability and fitness for a particular purpose are disclaimed.
00032 // In no event shall the Intel Corporation or contributors be liable for any direct,
00033 // indirect, incidental, special, exemplary, or consequential damages
00034 // (including, but not limited to, procurement of substitute goods or services;
00035 // loss of use, data, or profits; or business interruption) however caused
00036 // and on any theory of liability, whether in contract, strict liability,
00037 // or tort (including negligence or otherwise) arising in any way out of
00038 // the use of this software, even if advised of the possibility of such damage.
00039 //
00040 //M*/
00041 
00042 #ifndef __OPENCV_LEGACY_HPP__
00043 #define __OPENCV_LEGACY_HPP__
00044 
00045 #include "opencv2/imgproc/imgproc.hpp"
00046 #include "opencv2/imgproc/imgproc_c.h"
00047 #include "opencv2/features2d/features2d.hpp"
00048 #include "opencv2/calib3d/calib3d.hpp"
00049 #include "opencv2/ml/ml.hpp"
00050 
00051 #ifdef __cplusplus
00052 extern "C" {
00053 #endif
00054 
00055 CVAPI(CvSeq*) cvSegmentImage( const CvArr* srcarr, CvArr* dstarr,
00056                                     double canny_threshold,
00057                                     double ffill_threshold,
00058                                     CvMemStorage* storage );
00059 
00060 /****************************************************************************************\
00061 *                                  Eigen objects                                         *
00062 \****************************************************************************************/
00063 
00064 typedef int (CV_CDECL * CvCallback)(int index, void* buffer, void* user_data);
00065 typedef union
00066 {
00067     CvCallback callback;
00068     void* data;
00069 }
00070 CvInput;
00071 
00072 #define CV_EIGOBJ_NO_CALLBACK     0
00073 #define CV_EIGOBJ_INPUT_CALLBACK  1
00074 #define CV_EIGOBJ_OUTPUT_CALLBACK 2
00075 #define CV_EIGOBJ_BOTH_CALLBACK   3
00076 
00077 /* Calculates covariation matrix of a set of arrays */
00078 CVAPI(void)  cvCalcCovarMatrixEx( int nObjects, void* input, int ioFlags,
00079                                   int ioBufSize, uchar* buffer, void* userData,
00080                                   IplImage* avg, float* covarMatrix );
00081 
00082 /* Calculates eigen values and vectors of covariation matrix of a set of
00083    arrays */
00084 CVAPI(void)  cvCalcEigenObjects( int nObjects, void* input, void* output,
00085                                  int ioFlags, int ioBufSize, void* userData,
00086                                  CvTermCriteria* calcLimit, IplImage* avg,
00087                                  float* eigVals );
00088 
00089 /* Calculates dot product (obj - avg) * eigObj (i.e. projects image to eigen vector) */
00090 CVAPI(double)  cvCalcDecompCoeff( IplImage* obj, IplImage* eigObj, IplImage* avg );
00091 
00092 /* Projects image to eigen space (finds all decomposion coefficients */
00093 CVAPI(void)  cvEigenDecomposite( IplImage* obj, int nEigObjs, void* eigInput,
00094                                  int ioFlags, void* userData, IplImage* avg,
00095                                  float* coeffs );
00096 
00097 /* Projects original objects used to calculate eigen space basis to that space */
00098 CVAPI(void)  cvEigenProjection( void* eigInput, int nEigObjs, int ioFlags,
00099                                 void* userData, float* coeffs, IplImage* avg,
00100                                 IplImage* proj );
00101 
00102 /****************************************************************************************\
00103 *                                       1D/2D HMM                                        *
00104 \****************************************************************************************/
00105 
00106 typedef struct CvImgObsInfo
00107 {
00108     int obs_x;
00109     int obs_y;
00110     int obs_size;
00111     float* obs;//consequtive observations
00112 
00113     int* state;/* arr of pairs superstate/state to which observation belong */
00114     int* mix;  /* number of mixture to which observation belong */
00115 
00116 } CvImgObsInfo;/*struct for 1 image*/
00117 
00118 typedef CvImgObsInfo Cv1DObsInfo;
00119 
00120 typedef struct CvEHMMState
00121 {
00122     int num_mix;        /*number of mixtures in this state*/
00123     float* mu;          /*mean vectors corresponding to each mixture*/
00124     float* inv_var;     /* square root of inversed variances corresp. to each mixture*/
00125     float* log_var_val; /* sum of 0.5 (LN2PI + ln(variance[i]) ) for i=1,n */
00126     float* weight;      /*array of mixture weights. Summ of all weights in state is 1. */
00127 
00128 } CvEHMMState;
00129 
00130 typedef struct CvEHMM
00131 {
00132     int level; /* 0 - lowest(i.e its states are real states), ..... */
00133     int num_states; /* number of HMM states */
00134     float*  transP;/*transition probab. matrices for states */
00135     float** obsProb; /* if level == 0 - array of brob matrices corresponding to hmm
00136                         if level == 1 - martix of matrices */
00137     union
00138     {
00139         CvEHMMState* state; /* if level == 0 points to real states array,
00140                                if not - points to embedded hmms */
00141         struct CvEHMM* ehmm; /* pointer to an embedded model or NULL, if it is a leaf */
00142     } u;
00143 
00144 } CvEHMM;
00145 
00146 /*CVAPI(int)  icvCreate1DHMM( CvEHMM** this_hmm,
00147                                    int state_number, int* num_mix, int obs_size );
00148 
00149 CVAPI(int)  icvRelease1DHMM( CvEHMM** phmm );
00150 
00151 CVAPI(int)  icvUniform1DSegm( Cv1DObsInfo* obs_info, CvEHMM* hmm );
00152 
00153 CVAPI(int)  icvInit1DMixSegm( Cv1DObsInfo** obs_info_array, int num_img, CvEHMM* hmm);
00154 
00155 CVAPI(int)  icvEstimate1DHMMStateParams( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm);
00156 
00157 CVAPI(int)  icvEstimate1DObsProb( CvImgObsInfo* obs_info, CvEHMM* hmm );
00158 
00159 CVAPI(int)  icvEstimate1DTransProb( Cv1DObsInfo** obs_info_array,
00160                                            int num_seq,
00161                                            CvEHMM* hmm );
00162 
00163 CVAPI(float)  icvViterbi( Cv1DObsInfo* obs_info, CvEHMM* hmm);
00164 
00165 CVAPI(int)  icv1DMixSegmL2( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm );*/
00166 
00167 /*********************************** Embedded HMMs *************************************/
00168 
00169 /* Creates 2D HMM */
00170 CVAPI(CvEHMM*)  cvCreate2DHMM( int* stateNumber, int* numMix, int obsSize );
00171 
00172 /* Releases HMM */
00173 CVAPI(void)  cvRelease2DHMM( CvEHMM** hmm );
00174 
00175 #define CV_COUNT_OBS(roi, win, delta, numObs )                                       \
00176 {                                                                                    \
00177    (numObs)->width  =((roi)->width  -(win)->width  +(delta)->width)/(delta)->width;  \
00178    (numObs)->height =((roi)->height -(win)->height +(delta)->height)/(delta)->height;\
00179 }
00180 
00181 /* Creates storage for observation vectors */
00182 CVAPI(CvImgObsInfo*)  cvCreateObsInfo( CvSize numObs, int obsSize );
00183 
00184 /* Releases storage for observation vectors */
00185 CVAPI(void)  cvReleaseObsInfo( CvImgObsInfo** obs_info );
00186 
00187 
00188 /* The function takes an image on input and and returns the sequnce of observations
00189    to be used with an embedded HMM; Each observation is top-left block of DCT
00190    coefficient matrix */
00191 CVAPI(void)  cvImgToObs_DCT( const CvArr* arr, float* obs, CvSize dctSize,
00192                              CvSize obsSize, CvSize delta );
00193 
00194 
00195 /* Uniformly segments all observation vectors extracted from image */
00196 CVAPI(void)  cvUniformImgSegm( CvImgObsInfo* obs_info, CvEHMM* ehmm );
00197 
00198 /* Does mixture segmentation of the states of embedded HMM */
00199 CVAPI(void)  cvInitMixSegm( CvImgObsInfo** obs_info_array,
00200                             int num_img, CvEHMM* hmm );
00201 
00202 /* Function calculates means, variances, weights of every Gaussian mixture
00203    of every low-level state of embedded HMM */
00204 CVAPI(void)  cvEstimateHMMStateParams( CvImgObsInfo** obs_info_array,
00205                                        int num_img, CvEHMM* hmm );
00206 
00207 /* Function computes transition probability matrices of embedded HMM
00208    given observations segmentation */
00209 CVAPI(void)  cvEstimateTransProb( CvImgObsInfo** obs_info_array,
00210                                   int num_img, CvEHMM* hmm );
00211 
00212 /* Function computes probabilities of appearing observations at any state
00213    (i.e. computes P(obs|state) for every pair(obs,state)) */
00214 CVAPI(void)  cvEstimateObsProb( CvImgObsInfo* obs_info,
00215                                 CvEHMM* hmm );
00216 
00217 /* Runs Viterbi algorithm for embedded HMM */
00218 CVAPI(float)  cvEViterbi( CvImgObsInfo* obs_info, CvEHMM* hmm );
00219 
00220 
00221 /* Function clusters observation vectors from several images
00222    given observations segmentation.
00223    Euclidean distance used for clustering vectors.
00224    Centers of clusters are given means of every mixture */
00225 CVAPI(void)  cvMixSegmL2( CvImgObsInfo** obs_info_array,
00226                           int num_img, CvEHMM* hmm );
00227 
00228 /****************************************************************************************\
00229 *               A few functions from old stereo gesture recognition demosions            *
00230 \****************************************************************************************/
00231 
00232 /* Creates hand mask image given several points on the hand */
00233 CVAPI(void)  cvCreateHandMask( CvSeq* hand_points,
00234                                    IplImage *img_mask, CvRect *roi);
00235 
00236 /* Finds hand region in range image data */
00237 CVAPI(void)  cvFindHandRegion (CvPoint3D32f* points, int count,
00238                                 CvSeq* indexs,
00239                                 float* line, CvSize2D32f size, int flag,
00240                                 CvPoint3D32f* center,
00241                                 CvMemStorage* storage, CvSeq **numbers);
00242 
00243 /* Finds hand region in range image data (advanced version) */
00244 CVAPI(void)  cvFindHandRegionA( CvPoint3D32f* points, int count,
00245                                 CvSeq* indexs,
00246                                 float* line, CvSize2D32f size, int jc,
00247                                 CvPoint3D32f* center,
00248                                 CvMemStorage* storage, CvSeq **numbers);
00249 
00250 /* Calculates the cooficients of the homography matrix */
00251 CVAPI(void)  cvCalcImageHomography( float* line, CvPoint3D32f* center,
00252                                     float* intrinsic, float* homography );
00253 
00254 /****************************************************************************************\
00255 *                           More operations on sequences                                 *
00256 \****************************************************************************************/
00257 
00258 /*****************************************************************************************/
00259 
00260 #define CV_CURRENT_INT( reader ) (*((int *)(reader).ptr))
00261 #define CV_PREV_INT( reader ) (*((int *)(reader).prev_elem))
00262 
00263 #define  CV_GRAPH_WEIGHTED_VERTEX_FIELDS() CV_GRAPH_VERTEX_FIELDS()\
00264     float weight;
00265 
00266 #define  CV_GRAPH_WEIGHTED_EDGE_FIELDS() CV_GRAPH_EDGE_FIELDS()
00267 
00268 typedef struct CvGraphWeightedVtx
00269 {
00270     CV_GRAPH_WEIGHTED_VERTEX_FIELDS()
00271 } CvGraphWeightedVtx;
00272 
00273 typedef struct CvGraphWeightedEdge
00274 {
00275     CV_GRAPH_WEIGHTED_EDGE_FIELDS()
00276 } CvGraphWeightedEdge;
00277 
00278 typedef enum CvGraphWeightType
00279 {
00280     CV_NOT_WEIGHTED,
00281     CV_WEIGHTED_VTX,
00282     CV_WEIGHTED_EDGE,
00283     CV_WEIGHTED_ALL
00284 } CvGraphWeightType;
00285 
00286 
00287 /* Calculates histogram of a contour */
00288 CVAPI(void)  cvCalcPGH( const CvSeq* contour, CvHistogram* hist );
00289 
00290 #define CV_DOMINANT_IPAN 1
00291 
00292 /* Finds high-curvature points of the contour */
00293 CVAPI(CvSeq*) cvFindDominantPoints( CvSeq* contour, CvMemStorage* storage,
00294                                    int method CV_DEFAULT(CV_DOMINANT_IPAN),
00295                                    double parameter1 CV_DEFAULT(0),
00296                                    double parameter2 CV_DEFAULT(0),
00297                                    double parameter3 CV_DEFAULT(0),
00298                                    double parameter4 CV_DEFAULT(0));
00299 
00300 /*****************************************************************************************/
00301 
00302 
00303 /*******************************Stereo correspondence*************************************/
00304 
00305 typedef struct CvCliqueFinder
00306 {
00307     CvGraph* graph;
00308     int**    adj_matr;
00309     int N; //graph size
00310 
00311     // stacks, counters etc/
00312     int k; //stack size
00313     int* current_comp;
00314     int** All;
00315 
00316     int* ne;
00317     int* ce;
00318     int* fixp; //node with minimal disconnections
00319     int* nod;
00320     int* s; //for selected candidate
00321     int status;
00322     int best_score;
00323     int weighted;
00324     int weighted_edges;
00325     float best_weight;
00326     float* edge_weights;
00327     float* vertex_weights;
00328     float* cur_weight;
00329     float* cand_weight;
00330 
00331 } CvCliqueFinder;
00332 
00333 #define CLIQUE_TIME_OFF 2
00334 #define CLIQUE_FOUND 1
00335 #define CLIQUE_END   0
00336 
00337 /*CVAPI(void) cvStartFindCliques( CvGraph* graph, CvCliqueFinder* finder, int reverse,
00338                                    int weighted CV_DEFAULT(0),  int weighted_edges CV_DEFAULT(0));
00339 CVAPI(int) cvFindNextMaximalClique( CvCliqueFinder* finder, int* clock_rest CV_DEFAULT(0) );
00340 CVAPI(void) cvEndFindCliques( CvCliqueFinder* finder );
00341 
00342 CVAPI(void) cvBronKerbosch( CvGraph* graph );*/
00343 
00344 
00345 /*F///////////////////////////////////////////////////////////////////////////////////////
00346 //
00347 //    Name:    cvSubgraphWeight
00348 //    Purpose: finds weight of subgraph in a graph
00349 //    Context:
00350 //    Parameters:
00351 //      graph - input graph.
00352 //      subgraph - sequence of pairwise different ints.  These are indices of vertices of subgraph.
00353 //      weight_type - describes the way we measure weight.
00354 //            one of the following:
00355 //            CV_NOT_WEIGHTED - weight of a clique is simply its size
00356 //            CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices
00357 //            CV_WEIGHTED_EDGE - the same but edges
00358 //            CV_WEIGHTED_ALL - the same but both edges and vertices
00359 //      weight_vtx - optional vector of floats, with size = graph->total.
00360 //            If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL
00361 //            weights of vertices must be provided.  If weight_vtx not zero
00362 //            these weights considered to be here, otherwise function assumes
00363 //            that vertices of graph are inherited from CvGraphWeightedVtx.
00364 //      weight_edge - optional matrix of floats, of width and height = graph->total.
00365 //            If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL
00366 //            weights of edges ought to be supplied.  If weight_edge is not zero
00367 //            function finds them here, otherwise function expects
00368 //            edges of graph to be inherited from CvGraphWeightedEdge.
00369 //            If this parameter is not zero structure of the graph is determined from matrix
00370 //            rather than from CvGraphEdge's.  In particular, elements corresponding to
00371 //            absent edges should be zero.
00372 //    Returns:
00373 //      weight of subgraph.
00374 //    Notes:
00375 //F*/
00376 /*CVAPI(float) cvSubgraphWeight( CvGraph *graph, CvSeq *subgraph,
00377                                   CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED),
00378                                   CvVect32f weight_vtx CV_DEFAULT(0),
00379                                   CvMatr32f weight_edge CV_DEFAULT(0) );*/
00380 
00381 
00382 /*F///////////////////////////////////////////////////////////////////////////////////////
00383 //
00384 //    Name:    cvFindCliqueEx
00385 //    Purpose: tries to find clique with maximum possible weight in a graph
00386 //    Context:
00387 //    Parameters:
00388 //      graph - input graph.
00389 //      storage - memory storage to be used by the result.
00390 //      is_complementary - optional flag showing whether function should seek for clique
00391 //            in complementary graph.
00392 //      weight_type - describes our notion about weight.
00393 //            one of the following:
00394 //            CV_NOT_WEIGHTED - weight of a clique is simply its size
00395 //            CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices
00396 //            CV_WEIGHTED_EDGE - the same but edges
00397 //            CV_WEIGHTED_ALL - the same but both edges and vertices
00398 //      weight_vtx - optional vector of floats, with size = graph->total.
00399 //            If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL
00400 //            weights of vertices must be provided.  If weight_vtx not zero
00401 //            these weights considered to be here, otherwise function assumes
00402 //            that vertices of graph are inherited from CvGraphWeightedVtx.
00403 //      weight_edge - optional matrix of floats, of width and height = graph->total.
00404 //            If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL
00405 //            weights of edges ought to be supplied.  If weight_edge is not zero
00406 //            function finds them here, otherwise function expects
00407 //            edges of graph to be inherited from CvGraphWeightedEdge.
00408 //            Note that in case of CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL
00409 //            nonzero is_complementary implies nonzero weight_edge.
00410 //      start_clique - optional sequence of pairwise different ints.  They are indices of
00411 //            vertices that shall be present in the output clique.
00412 //      subgraph_of_ban - optional sequence of (maybe equal) ints.  They are indices of
00413 //            vertices that shall not be present in the output clique.
00414 //      clique_weight_ptr - optional output parameter.  Weight of found clique stored here.
00415 //      num_generations - optional number of generations in evolutionary part of algorithm,
00416 //            zero forces to return first found clique.
00417 //      quality - optional parameter determining degree of required quality/speed tradeoff.
00418 //            Must be in the range from 0 to 9.
00419 //            0 is fast and dirty, 9 is slow but hopefully yields good clique.
00420 //    Returns:
00421 //      sequence of pairwise different ints.
00422 //      These are indices of vertices that form found clique.
00423 //    Notes:
00424 //      in cases of CV_WEIGHTED_EDGE and CV_WEIGHTED_ALL weights should be nonnegative.
00425 //      start_clique has a priority over subgraph_of_ban.
00426 //F*/
00427 /*CVAPI(CvSeq*) cvFindCliqueEx( CvGraph *graph, CvMemStorage *storage,
00428                                  int is_complementary CV_DEFAULT(0),
00429                                  CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED),
00430                                  CvVect32f weight_vtx CV_DEFAULT(0),
00431                                  CvMatr32f weight_edge CV_DEFAULT(0),
00432                                  CvSeq *start_clique CV_DEFAULT(0),
00433                                  CvSeq *subgraph_of_ban CV_DEFAULT(0),
00434                                  float *clique_weight_ptr CV_DEFAULT(0),
00435                                  int num_generations CV_DEFAULT(3),
00436                                  int quality CV_DEFAULT(2) );*/
00437 
00438 
00439 #define CV_UNDEF_SC_PARAM         12345 //default value of parameters
00440 
00441 #define CV_IDP_BIRCHFIELD_PARAM1  25
00442 #define CV_IDP_BIRCHFIELD_PARAM2  5
00443 #define CV_IDP_BIRCHFIELD_PARAM3  12
00444 #define CV_IDP_BIRCHFIELD_PARAM4  15
00445 #define CV_IDP_BIRCHFIELD_PARAM5  25
00446 
00447 
00448 #define  CV_DISPARITY_BIRCHFIELD  0
00449 
00450 
00451 /*F///////////////////////////////////////////////////////////////////////////
00452 //
00453 //    Name:    cvFindStereoCorrespondence
00454 //    Purpose: find stereo correspondence on stereo-pair
00455 //    Context:
00456 //    Parameters:
00457 //      leftImage - left image of stereo-pair (format 8uC1).
00458 //      rightImage - right image of stereo-pair (format 8uC1).
00459 //   mode - mode of correspondence retrieval (now CV_DISPARITY_BIRCHFIELD only)
00460 //      dispImage - destination disparity image
00461 //      maxDisparity - maximal disparity
00462 //      param1, param2, param3, param4, param5 - parameters of algorithm
00463 //    Returns:
00464 //    Notes:
00465 //      Images must be rectified.
00466 //      All images must have format 8uC1.
00467 //F*/
00468 CVAPI(void)
00469 cvFindStereoCorrespondence(
00470                    const  CvArr* leftImage, const  CvArr* rightImage,
00471                    int     mode,
00472                    CvArr*  dispImage,
00473                    int     maxDisparity,
00474                    double  param1 CV_DEFAULT(CV_UNDEF_SC_PARAM),
00475                    double  param2 CV_DEFAULT(CV_UNDEF_SC_PARAM),
00476                    double  param3 CV_DEFAULT(CV_UNDEF_SC_PARAM),
00477                    double  param4 CV_DEFAULT(CV_UNDEF_SC_PARAM),
00478                    double  param5 CV_DEFAULT(CV_UNDEF_SC_PARAM) );
00479 
00480 /*****************************************************************************************/
00481 /************ Epiline functions *******************/
00482 
00483 
00484 
00485 typedef struct CvStereoLineCoeff
00486 {
00487     double Xcoef;
00488     double XcoefA;
00489     double XcoefB;
00490     double XcoefAB;
00491 
00492     double Ycoef;
00493     double YcoefA;
00494     double YcoefB;
00495     double YcoefAB;
00496 
00497     double Zcoef;
00498     double ZcoefA;
00499     double ZcoefB;
00500     double ZcoefAB;
00501 }CvStereoLineCoeff;
00502 
00503 
00504 typedef struct CvCamera
00505 {
00506     float   imgSize[2]; /* size of the camera view, used during calibration */
00507     float   matrix[9]; /* intinsic camera parameters:  [ fx 0 cx; 0 fy cy; 0 0 1 ] */
00508     float   distortion[4]; /* distortion coefficients - two coefficients for radial distortion
00509                               and another two for tangential: [ k1 k2 p1 p2 ] */
00510     float   rotMatr[9];
00511     float   transVect[3]; /* rotation matrix and transition vector relatively
00512                              to some reference point in the space. */
00513 } CvCamera;
00514 
00515 typedef struct CvStereoCamera
00516 {
00517     CvCamera* camera[2]; /* two individual camera parameters */
00518     float fundMatr[9]; /* fundamental matrix */
00519 
00520     /* New part for stereo */
00521     CvPoint3D32f epipole[2];
00522     CvPoint2D32f quad[2][4]; /* coordinates of destination quadrangle after
00523                                 epipolar geometry rectification */
00524     double coeffs[2][3][3];/* coefficients for transformation */
00525     CvPoint2D32f border[2][4];
00526     CvSize warpSize;
00527     CvStereoLineCoeff* lineCoeffs;
00528     int needSwapCameras;/* flag set to 1 if need to swap cameras for good reconstruction */
00529     float rotMatrix[9];
00530     float transVector[3];
00531 } CvStereoCamera;
00532 
00533 
00534 typedef struct CvContourOrientation
00535 {
00536     float egvals[2];
00537     float egvects[4];
00538 
00539     float max, min; // minimum and maximum projections
00540     int imax, imin;
00541 } CvContourOrientation;
00542 
00543 #define CV_CAMERA_TO_WARP 1
00544 #define CV_WARP_TO_CAMERA 2
00545 
00546 CVAPI(int) icvConvertWarpCoordinates(double coeffs[3][3],
00547                                 CvPoint2D32f* cameraPoint,
00548                                 CvPoint2D32f* warpPoint,
00549                                 int direction);
00550 
00551 CVAPI(int) icvGetSymPoint3D(  CvPoint3D64f pointCorner,
00552                             CvPoint3D64f point1,
00553                             CvPoint3D64f point2,
00554                             CvPoint3D64f *pointSym2);
00555 
00556 CVAPI(void) icvGetPieceLength3D(CvPoint3D64f point1,CvPoint3D64f point2,double* dist);
00557 
00558 CVAPI(int) icvCompute3DPoint(    double alpha,double betta,
00559                             CvStereoLineCoeff* coeffs,
00560                             CvPoint3D64f* point);
00561 
00562 CVAPI(int) icvCreateConvertMatrVect( double*     rotMatr1,
00563                                 double*     transVect1,
00564                                 double*     rotMatr2,
00565                                 double*     transVect2,
00566                                 double*     convRotMatr,
00567                                 double*     convTransVect);
00568 
00569 CVAPI(int) icvConvertPointSystem(CvPoint3D64f  M2,
00570                             CvPoint3D64f* M1,
00571                             double*     rotMatr,
00572                             double*     transVect
00573                             );
00574 
00575 CVAPI(int) icvComputeCoeffForStereo(  CvStereoCamera* stereoCamera);
00576 
00577 CVAPI(int) icvGetCrossPieceVector(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f v2_start,CvPoint2D32f v2_end,CvPoint2D32f *cross);
00578 CVAPI(int) icvGetCrossLineDirect(CvPoint2D32f p1,CvPoint2D32f p2,float a,float b,float c,CvPoint2D32f* cross);
00579 CVAPI(float) icvDefinePointPosition(CvPoint2D32f point1,CvPoint2D32f point2,CvPoint2D32f point);
00580 CVAPI(int) icvStereoCalibration( int numImages,
00581                             int* nums,
00582                             CvSize imageSize,
00583                             CvPoint2D32f* imagePoints1,
00584                             CvPoint2D32f* imagePoints2,
00585                             CvPoint3D32f* objectPoints,
00586                             CvStereoCamera* stereoparams
00587                            );
00588 
00589 
00590 CVAPI(int) icvComputeRestStereoParams(CvStereoCamera *stereoparams);
00591 
00592 CVAPI(void) cvComputePerspectiveMap( const double coeffs[3][3], CvArr* rectMapX, CvArr* rectMapY );
00593 
00594 CVAPI(int) icvComCoeffForLine(   CvPoint2D64f point1,
00595                             CvPoint2D64f point2,
00596                             CvPoint2D64f point3,
00597                             CvPoint2D64f point4,
00598                             double*    camMatr1,
00599                             double*    rotMatr1,
00600                             double*    transVect1,
00601                             double*    camMatr2,
00602                             double*    rotMatr2,
00603                             double*    transVect2,
00604                             CvStereoLineCoeff*    coeffs,
00605                             int* needSwapCameras);
00606 
00607 CVAPI(int) icvGetDirectionForPoint(  CvPoint2D64f point,
00608                                 double* camMatr,
00609                                 CvPoint3D64f* direct);
00610 
00611 CVAPI(int) icvGetCrossLines(CvPoint3D64f point11,CvPoint3D64f point12,
00612                        CvPoint3D64f point21,CvPoint3D64f point22,
00613                        CvPoint3D64f* midPoint);
00614 
00615 CVAPI(int) icvComputeStereoLineCoeffs(   CvPoint3D64f pointA,
00616                                     CvPoint3D64f pointB,
00617                                     CvPoint3D64f pointCam1,
00618                                     double gamma,
00619                                     CvStereoLineCoeff*    coeffs);
00620 
00621 /*CVAPI(int) icvComputeFundMatrEpipoles ( double* camMatr1,
00622                                     double*     rotMatr1,
00623                                     double*     transVect1,
00624                                     double*     camMatr2,
00625                                     double*     rotMatr2,
00626                                     double*     transVect2,
00627                                     CvPoint2D64f* epipole1,
00628                                     CvPoint2D64f* epipole2,
00629                                     double*     fundMatr);*/
00630 
00631 CVAPI(int) icvGetAngleLine( CvPoint2D64f startPoint, CvSize imageSize,CvPoint2D64f *point1,CvPoint2D64f *point2);
00632 
00633 CVAPI(void) icvGetCoefForPiece(   CvPoint2D64f p_start,CvPoint2D64f p_end,
00634                         double *a,double *b,double *c,
00635                         int* result);
00636 
00637 /*CVAPI(void) icvGetCommonArea( CvSize imageSize,
00638                     CvPoint2D64f epipole1,CvPoint2D64f epipole2,
00639                     double* fundMatr,
00640                     double* coeff11,double* coeff12,
00641                     double* coeff21,double* coeff22,
00642                     int* result);*/
00643 
00644 CVAPI(void) icvComputeeInfiniteProject1(double*    rotMatr,
00645                                      double*    camMatr1,
00646                                      double*    camMatr2,
00647                                      CvPoint2D32f point1,
00648                                      CvPoint2D32f *point2);
00649 
00650 CVAPI(void) icvComputeeInfiniteProject2(double*    rotMatr,
00651                                      double*    camMatr1,
00652                                      double*    camMatr2,
00653                                      CvPoint2D32f* point1,
00654                                      CvPoint2D32f point2);
00655 
00656 CVAPI(void) icvGetCrossDirectDirect(  double* direct1,double* direct2,
00657                             CvPoint2D64f *cross,int* result);
00658 
00659 CVAPI(void) icvGetCrossPieceDirect(   CvPoint2D64f p_start,CvPoint2D64f p_end,
00660                             double a,double b,double c,
00661                             CvPoint2D64f *cross,int* result);
00662 
00663 CVAPI(void) icvGetCrossPiecePiece( CvPoint2D64f p1_start,CvPoint2D64f p1_end,
00664                             CvPoint2D64f p2_start,CvPoint2D64f p2_end,
00665                             CvPoint2D64f* cross,
00666                             int* result);
00667 
00668 CVAPI(void) icvGetPieceLength(CvPoint2D64f point1,CvPoint2D64f point2,double* dist);
00669 
00670 CVAPI(void) icvGetCrossRectDirect(    CvSize imageSize,
00671                             double a,double b,double c,
00672                             CvPoint2D64f *start,CvPoint2D64f *end,
00673                             int* result);
00674 
00675 CVAPI(void) icvProjectPointToImage(   CvPoint3D64f point,
00676                             double* camMatr,double* rotMatr,double* transVect,
00677                             CvPoint2D64f* projPoint);
00678 
00679 CVAPI(void) icvGetQuadsTransform( CvSize        imageSize,
00680                         double*     camMatr1,
00681                         double*     rotMatr1,
00682                         double*     transVect1,
00683                         double*     camMatr2,
00684                         double*     rotMatr2,
00685                         double*     transVect2,
00686                         CvSize*       warpSize,
00687                         double quad1[4][2],
00688                         double quad2[4][2],
00689                         double*     fundMatr,
00690                         CvPoint3D64f* epipole1,
00691                         CvPoint3D64f* epipole2
00692                         );
00693 
00694 CVAPI(void) icvGetQuadsTransformStruct(  CvStereoCamera* stereoCamera);
00695 
00696 CVAPI(void) icvComputeStereoParamsForCameras(CvStereoCamera* stereoCamera);
00697 
00698 CVAPI(void) icvGetCutPiece(   double* areaLineCoef1,double* areaLineCoef2,
00699                     CvPoint2D64f epipole,
00700                     CvSize imageSize,
00701                     CvPoint2D64f* point11,CvPoint2D64f* point12,
00702                     CvPoint2D64f* point21,CvPoint2D64f* point22,
00703                     int* result);
00704 
00705 CVAPI(void) icvGetMiddleAnglePoint(   CvPoint2D64f basePoint,
00706                             CvPoint2D64f point1,CvPoint2D64f point2,
00707                             CvPoint2D64f* midPoint);
00708 
00709 CVAPI(void) icvGetNormalDirect(double* direct,CvPoint2D64f point,double* normDirect);
00710 
00711 CVAPI(double) icvGetVect(CvPoint2D64f basePoint,CvPoint2D64f point1,CvPoint2D64f point2);
00712 
00713 CVAPI(void) icvProjectPointToDirect(  CvPoint2D64f point,double* lineCoeff,
00714                             CvPoint2D64f* projectPoint);
00715 
00716 CVAPI(void) icvGetDistanceFromPointToDirect( CvPoint2D64f point,double* lineCoef,double*dist);
00717 
00718 CVAPI(IplImage*) icvCreateIsometricImage( IplImage* src, IplImage* dst,
00719                               int desired_depth, int desired_num_channels );
00720 
00721 CVAPI(void) cvDeInterlace( const CvArr* frame, CvArr* fieldEven, CvArr* fieldOdd );
00722 
00723 /*CVAPI(int) icvSelectBestRt(           int           numImages,
00724                                     int*          numPoints,
00725                                     CvSize        imageSize,
00726                                     CvPoint2D32f* imagePoints1,
00727                                     CvPoint2D32f* imagePoints2,
00728                                     CvPoint3D32f* objectPoints,
00729 
00730                                     CvMatr32f     cameraMatrix1,
00731                                     CvVect32f     distortion1,
00732                                     CvMatr32f     rotMatrs1,
00733                                     CvVect32f     transVects1,
00734 
00735                                     CvMatr32f     cameraMatrix2,
00736                                     CvVect32f     distortion2,
00737                                     CvMatr32f     rotMatrs2,
00738                                     CvVect32f     transVects2,
00739 
00740                                     CvMatr32f     bestRotMatr,
00741                                     CvVect32f     bestTransVect
00742                                     );*/
00743 
00744 
00745 /****************************************************************************************\
00746 *                                     Contour Tree                                       *
00747 \****************************************************************************************/
00748 
00749 /* Contour tree header */
00750 typedef struct CvContourTree
00751 {
00752     CV_SEQUENCE_FIELDS()
00753     CvPoint p1;            /* the first point of the binary tree root segment */
00754     CvPoint p2;            /* the last point of the binary tree root segment */
00755 } CvContourTree;
00756 
00757 /* Builds hierarhical representation of a contour */
00758 CVAPI(CvContourTree*)  cvCreateContourTree( const CvSeq* contour,
00759                                             CvMemStorage* storage,
00760                                             double threshold );
00761 
00762 /* Reconstruct (completelly or partially) contour a from contour tree */
00763 CVAPI(CvSeq*)  cvContourFromContourTree( const CvContourTree* tree,
00764                                          CvMemStorage* storage,
00765                                          CvTermCriteria criteria );
00766 
00767 /* Compares two contour trees */
00768 enum { CV_CONTOUR_TREES_MATCH_I1 = 1 };
00769 
00770 CVAPI(double)  cvMatchContourTrees( const CvContourTree* tree1,
00771                                     const CvContourTree* tree2,
00772                                     int method, double threshold );
00773 
00774 /****************************************************************************************\
00775 *                                   Contour Morphing                                     *
00776 \****************************************************************************************/
00777 
00778 /* finds correspondence between two contours */
00779 CvSeq* cvCalcContoursCorrespondence( const CvSeq* contour1,
00780                                      const CvSeq* contour2,
00781                                      CvMemStorage* storage);
00782 
00783 /* morphs contours using the pre-calculated correspondence:
00784    alpha=0 ~ contour1, alpha=1 ~ contour2 */
00785 CvSeq* cvMorphContours( const CvSeq* contour1, const CvSeq* contour2,
00786                         CvSeq* corr, double alpha,
00787                         CvMemStorage* storage );
00788 
00789 
00790 /****************************************************************************************\
00791 *                                   Active Contours                                      *
00792 \****************************************************************************************/
00793 
00794 #define  CV_VALUE  1
00795 #define  CV_ARRAY  2
00796 /* Updates active contour in order to minimize its cummulative
00797    (internal and external) energy. */
00798 CVAPI(void)  cvSnakeImage( const IplImage* image, CvPoint* points,
00799                            int  length, float* alpha,
00800                            float* beta, float* gamma,
00801                            int coeff_usage, CvSize  win,
00802                            CvTermCriteria criteria, int calc_gradient CV_DEFAULT(1));
00803 
00804 /****************************************************************************************\
00805 *                                    Texture Descriptors                                 *
00806 \****************************************************************************************/
00807 
00808 #define CV_GLCM_OPTIMIZATION_NONE                   -2
00809 #define CV_GLCM_OPTIMIZATION_LUT                    -1
00810 #define CV_GLCM_OPTIMIZATION_HISTOGRAM              0
00811 
00812 #define CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST    10
00813 #define CV_GLCMDESC_OPTIMIZATION_ALLOWTRIPLENEST    11
00814 #define CV_GLCMDESC_OPTIMIZATION_HISTOGRAM          4
00815 
00816 #define CV_GLCMDESC_ENTROPY                         0
00817 #define CV_GLCMDESC_ENERGY                          1
00818 #define CV_GLCMDESC_HOMOGENITY                      2
00819 #define CV_GLCMDESC_CONTRAST                        3
00820 #define CV_GLCMDESC_CLUSTERTENDENCY                 4
00821 #define CV_GLCMDESC_CLUSTERSHADE                    5
00822 #define CV_GLCMDESC_CORRELATION                     6
00823 #define CV_GLCMDESC_CORRELATIONINFO1                7
00824 #define CV_GLCMDESC_CORRELATIONINFO2                8
00825 #define CV_GLCMDESC_MAXIMUMPROBABILITY              9
00826 
00827 #define CV_GLCM_ALL                                 0
00828 #define CV_GLCM_GLCM                                1
00829 #define CV_GLCM_DESC                                2
00830 
00831 typedef struct CvGLCM CvGLCM;
00832 
00833 CVAPI(CvGLCM*) cvCreateGLCM( const IplImage* srcImage,
00834                                 int stepMagnitude,
00835                                 const int* stepDirections CV_DEFAULT(0),
00836                                 int numStepDirections CV_DEFAULT(0),
00837                                 int optimizationType CV_DEFAULT(CV_GLCM_OPTIMIZATION_NONE));
00838 
00839 CVAPI(void) cvReleaseGLCM( CvGLCM** GLCM, int flag CV_DEFAULT(CV_GLCM_ALL));
00840 
00841 CVAPI(void) cvCreateGLCMDescriptors( CvGLCM* destGLCM,
00842                                         int descriptorOptimizationType
00843                                         CV_DEFAULT(CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST));
00844 
00845 CVAPI(double) cvGetGLCMDescriptor( CvGLCM* GLCM, int step, int descriptor );
00846 
00847 CVAPI(void) cvGetGLCMDescriptorStatistics( CvGLCM* GLCM, int descriptor,
00848                                               double* average, double* standardDeviation );
00849 
00850 CVAPI(IplImage*) cvCreateGLCMImage( CvGLCM* GLCM, int step );
00851 
00852 /****************************************************************************************\
00853 *                                  Face eyes&mouth tracking                              *
00854 \****************************************************************************************/
00855 
00856 
00857 typedef struct CvFaceTracker CvFaceTracker;
00858 
00859 #define CV_NUM_FACE_ELEMENTS    3
00860 enum CV_FACE_ELEMENTS
00861 {
00862     CV_FACE_MOUTH = 0,
00863     CV_FACE_LEFT_EYE = 1,
00864     CV_FACE_RIGHT_EYE = 2
00865 };
00866 
00867 CVAPI(CvFaceTracker*) cvInitFaceTracker(CvFaceTracker* pFaceTracking, const IplImage* imgGray,
00868                                                 CvRect* pRects, int nRects);
00869 CVAPI(int) cvTrackFace( CvFaceTracker* pFaceTracker, IplImage* imgGray,
00870                               CvRect* pRects, int nRects,
00871                               CvPoint* ptRotate, double* dbAngleRotate);
00872 CVAPI(void) cvReleaseFaceTracker(CvFaceTracker** ppFaceTracker);
00873 
00874 
00875 typedef struct CvFace
00876 {
00877     CvRect MouthRect;
00878     CvRect LeftEyeRect;
00879     CvRect RightEyeRect;
00880 } CvFaceData;
00881 
00882 CvSeq * cvFindFace(IplImage * Image,CvMemStorage* storage);
00883 CvSeq * cvPostBoostingFindFace(IplImage * Image,CvMemStorage* storage);
00884 
00885 
00886 /****************************************************************************************\
00887 *                                         3D Tracker                                     *
00888 \****************************************************************************************/
00889 
00890 typedef unsigned char CvBool;
00891 
00892 typedef struct Cv3dTracker2dTrackedObject
00893 {
00894     int id;
00895     CvPoint2D32f p; // pgruebele: So we do not loose precision, this needs to be float
00896 } Cv3dTracker2dTrackedObject;
00897 
00898 CV_INLINE Cv3dTracker2dTrackedObject cv3dTracker2dTrackedObject(int id, CvPoint2D32f p)
00899 {
00900     Cv3dTracker2dTrackedObject r;
00901     r.id = id;
00902     r.p = p;
00903     return r;
00904 }
00905 
00906 typedef struct Cv3dTrackerTrackedObject
00907 {
00908     int id;
00909     CvPoint3D32f p;             // location of the tracked object
00910 } Cv3dTrackerTrackedObject;
00911 
00912 CV_INLINE Cv3dTrackerTrackedObject cv3dTrackerTrackedObject(int id, CvPoint3D32f p)
00913 {
00914     Cv3dTrackerTrackedObject r;
00915     r.id = id;
00916     r.p = p;
00917     return r;
00918 }
00919 
00920 typedef struct Cv3dTrackerCameraInfo
00921 {
00922     CvBool valid;
00923     float mat[4][4];              /* maps camera coordinates to world coordinates */
00924     CvPoint2D32f principal_point; /* copied from intrinsics so this structure */
00925                                   /* has all the info we need */
00926 } Cv3dTrackerCameraInfo;
00927 
00928 typedef struct Cv3dTrackerCameraIntrinsics
00929 {
00930     CvPoint2D32f principal_point;
00931     float focal_length[2];
00932     float distortion[4];
00933 } Cv3dTrackerCameraIntrinsics;
00934 
00935 CVAPI(CvBool) cv3dTrackerCalibrateCameras(int num_cameras,
00936                      const Cv3dTrackerCameraIntrinsics camera_intrinsics[], /* size is num_cameras */
00937                      CvSize etalon_size,
00938                      float square_size,
00939                      IplImage *samples[],                                   /* size is num_cameras */
00940                      Cv3dTrackerCameraInfo camera_info[]);                  /* size is num_cameras */
00941 
00942 CVAPI(int)  cv3dTrackerLocateObjects(int num_cameras, int num_objects,
00943                    const Cv3dTrackerCameraInfo camera_info[],        /* size is num_cameras */
00944                    const Cv3dTracker2dTrackedObject tracking_info[], /* size is num_objects*num_cameras */
00945                    Cv3dTrackerTrackedObject tracked_objects[]);      /* size is num_objects */
00946 /****************************************************************************************
00947  tracking_info is a rectangular array; one row per camera, num_objects elements per row.
00948  The id field of any unused slots must be -1. Ids need not be ordered or consecutive. On
00949  completion, the return value is the number of objects located; i.e., the number of objects
00950  visible by more than one camera. The id field of any unused slots in tracked objects is
00951  set to -1.
00952 ****************************************************************************************/
00953 
00954 
00955 /****************************************************************************************\
00956 *                           Skeletons and Linear-Contour Models                          *
00957 \****************************************************************************************/
00958 
00959 typedef enum CvLeeParameters
00960 {
00961     CV_LEE_INT = 0,
00962     CV_LEE_FLOAT = 1,
00963     CV_LEE_DOUBLE = 2,
00964     CV_LEE_AUTO = -1,
00965     CV_LEE_ERODE = 0,
00966     CV_LEE_ZOOM = 1,
00967     CV_LEE_NON = 2
00968 } CvLeeParameters;
00969 
00970 #define CV_NEXT_VORONOISITE2D( SITE ) ((SITE)->edge[0]->site[((SITE)->edge[0]->site[0] == (SITE))])
00971 #define CV_PREV_VORONOISITE2D( SITE ) ((SITE)->edge[1]->site[((SITE)->edge[1]->site[0] == (SITE))])
00972 #define CV_FIRST_VORONOIEDGE2D( SITE ) ((SITE)->edge[0])
00973 #define CV_LAST_VORONOIEDGE2D( SITE ) ((SITE)->edge[1])
00974 #define CV_NEXT_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[(EDGE)->site[0] != (SITE)])
00975 #define CV_PREV_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[2 + ((EDGE)->site[0] != (SITE))])
00976 #define CV_VORONOIEDGE2D_BEGINNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] != (SITE))])
00977 #define CV_VORONOIEDGE2D_ENDNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] == (SITE))])
00978 #define CV_TWIN_VORONOISITE2D( SITE, EDGE ) ( (EDGE)->site[((EDGE)->site[0] == (SITE))])
00979 
00980 #define CV_VORONOISITE2D_FIELDS()    \
00981     struct CvVoronoiNode2D *node[2]; \
00982     struct CvVoronoiEdge2D *edge[2];
00983 
00984 typedef struct CvVoronoiSite2D
00985 {
00986     CV_VORONOISITE2D_FIELDS()
00987     struct CvVoronoiSite2D *next[2];
00988 } CvVoronoiSite2D;
00989 
00990 #define CV_VORONOIEDGE2D_FIELDS()    \
00991     struct CvVoronoiNode2D *node[2]; \
00992     struct CvVoronoiSite2D *site[2]; \
00993     struct CvVoronoiEdge2D *next[4];
00994 
00995 typedef struct CvVoronoiEdge2D
00996 {
00997     CV_VORONOIEDGE2D_FIELDS()
00998 } CvVoronoiEdge2D;
00999 
01000 #define CV_VORONOINODE2D_FIELDS()       \
01001     CV_SET_ELEM_FIELDS(CvVoronoiNode2D) \
01002     CvPoint2D32f pt;                    \
01003     float radius;
01004 
01005 typedef struct CvVoronoiNode2D
01006 {
01007     CV_VORONOINODE2D_FIELDS()
01008 } CvVoronoiNode2D;
01009 
01010 #define CV_VORONOIDIAGRAM2D_FIELDS() \
01011     CV_GRAPH_FIELDS()                \
01012     CvSet *sites;
01013 
01014 typedef struct CvVoronoiDiagram2D
01015 {
01016     CV_VORONOIDIAGRAM2D_FIELDS()
01017 } CvVoronoiDiagram2D;
01018 
01019 /* Computes Voronoi Diagram for given polygons with holes */
01020 CVAPI(int)  cvVoronoiDiagramFromContour(CvSeq* ContourSeq,
01021                                            CvVoronoiDiagram2D** VoronoiDiagram,
01022                                            CvMemStorage* VoronoiStorage,
01023                                            CvLeeParameters contour_type CV_DEFAULT(CV_LEE_INT),
01024                                            int contour_orientation CV_DEFAULT(-1),
01025                                            int attempt_number CV_DEFAULT(10));
01026 
01027 /* Computes Voronoi Diagram for domains in given image */
01028 CVAPI(int)  cvVoronoiDiagramFromImage(IplImage* pImage,
01029                                          CvSeq** ContourSeq,
01030                                          CvVoronoiDiagram2D** VoronoiDiagram,
01031                                          CvMemStorage* VoronoiStorage,
01032                                          CvLeeParameters regularization_method CV_DEFAULT(CV_LEE_NON),
01033                                          float approx_precision CV_DEFAULT(CV_LEE_AUTO));
01034 
01035 /* Deallocates the storage */
01036 CVAPI(void) cvReleaseVoronoiStorage(CvVoronoiDiagram2D* VoronoiDiagram,
01037                                           CvMemStorage** pVoronoiStorage);
01038 
01039 /*********************** Linear-Contour Model ****************************/
01040 
01041 struct CvLCMEdge;
01042 struct CvLCMNode;
01043 
01044 typedef struct CvLCMEdge
01045 {
01046     CV_GRAPH_EDGE_FIELDS()
01047     CvSeq* chain;
01048     float width;
01049     int index1;
01050     int index2;
01051 } CvLCMEdge;
01052 
01053 typedef struct CvLCMNode
01054 {
01055     CV_GRAPH_VERTEX_FIELDS()
01056     CvContour* contour;
01057 } CvLCMNode;
01058 
01059 
01060 /* Computes hybrid model from Voronoi Diagram */
01061 CVAPI(CvGraph*) cvLinearContorModelFromVoronoiDiagram(CvVoronoiDiagram2D* VoronoiDiagram,
01062                                                          float maxWidth);
01063 
01064 /* Releases hybrid model storage */
01065 CVAPI(int) cvReleaseLinearContorModelStorage(CvGraph** Graph);
01066 
01067 
01068 /* two stereo-related functions */
01069 
01070 CVAPI(void) cvInitPerspectiveTransform( CvSize size, const CvPoint2D32f vertex[4], double matrix[3][3],
01071                                               CvArr* rectMap );
01072 
01073 /*CVAPI(void) cvInitStereoRectification( CvStereoCamera* params,
01074                                              CvArr* rectMap1, CvArr* rectMap2,
01075                                              int do_undistortion );*/
01076 
01077 /*************************** View Morphing Functions ************************/
01078 
01079 typedef struct CvMatrix3
01080 {
01081     float m[3][3];
01082 } CvMatrix3;
01083 
01084 /* The order of the function corresponds to the order they should appear in
01085    the view morphing pipeline */
01086 
01087 /* Finds ending points of scanlines on left and right images of stereo-pair */
01088 CVAPI(void)  cvMakeScanlines( const CvMatrix3* matrix, CvSize  img_size,
01089                               int*  scanlines1, int*  scanlines2,
01090                               int*  lengths1, int*  lengths2,
01091                               int*  line_count );
01092 
01093 /* Grab pixel values from scanlines and stores them sequentially
01094    (some sort of perspective image transform) */
01095 CVAPI(void)  cvPreWarpImage( int       line_count,
01096                              IplImage* img,
01097                              uchar*    dst,
01098                              int*      dst_nums,
01099                              int*      scanlines);
01100 
01101 /* Approximate each grabbed scanline by a sequence of runs
01102    (lossy run-length compression) */
01103 CVAPI(void)  cvFindRuns( int    line_count,
01104                          uchar* prewarp1,
01105                          uchar* prewarp2,
01106                          int*   line_lengths1,
01107                          int*   line_lengths2,
01108                          int*   runs1,
01109                          int*   runs2,
01110                          int*   num_runs1,
01111                          int*   num_runs2);
01112 
01113 /* Compares two sets of compressed scanlines */
01114 CVAPI(void)  cvDynamicCorrespondMulti( int  line_count,
01115                                        int* first,
01116                                        int* first_runs,
01117                                        int* second,
01118                                        int* second_runs,
01119                                        int* first_corr,
01120                                        int* second_corr);
01121 
01122 /* Finds scanline ending coordinates for some intermediate "virtual" camera position */
01123 CVAPI(void)  cvMakeAlphaScanlines( int*  scanlines1,
01124                                    int*  scanlines2,
01125                                    int*  scanlinesA,
01126                                    int*  lengths,
01127                                    int   line_count,
01128                                    float alpha);
01129 
01130 /* Blends data of the left and right image scanlines to get
01131    pixel values of "virtual" image scanlines */
01132 CVAPI(void)  cvMorphEpilinesMulti( int    line_count,
01133                                    uchar* first_pix,
01134                                    int*   first_num,
01135                                    uchar* second_pix,
01136                                    int*   second_num,
01137                                    uchar* dst_pix,
01138                                    int*   dst_num,
01139                                    float  alpha,
01140                                    int*   first,
01141                                    int*   first_runs,
01142                                    int*   second,
01143                                    int*   second_runs,
01144                                    int*   first_corr,
01145                                    int*   second_corr);
01146 
01147 /* Does reverse warping of the morphing result to make
01148    it fill the destination image rectangle */
01149 CVAPI(void)  cvPostWarpImage( int       line_count,
01150                               uchar*    src,
01151                               int*      src_nums,
01152                               IplImage* img,
01153                               int*      scanlines);
01154 
01155 /* Deletes Moire (missed pixels that appear due to discretization) */
01156 CVAPI(void)  cvDeleteMoire( IplImage*  img );
01157 
01158 
01159 typedef struct CvConDensation
01160 {
01161     int MP;
01162     int DP;
01163     float* DynamMatr;       /* Matrix of the linear Dynamics system  */
01164     float* State;           /* Vector of State                       */
01165     int SamplesNum;         /* Number of the Samples                 */
01166     float** flSamples;      /* arr of the Sample Vectors             */
01167     float** flNewSamples;   /* temporary array of the Sample Vectors */
01168     float* flConfidence;    /* Confidence for each Sample            */
01169     float* flCumulative;    /* Cumulative confidence                 */
01170     float* Temp;            /* Temporary vector                      */
01171     float* RandomSample;    /* RandomVector to update sample set     */
01172     struct CvRandState* RandS; /* Array of structures to generate random vectors */
01173 } CvConDensation;
01174 
01175 /* Creates ConDensation filter state */
01176 CVAPI(CvConDensation*)  cvCreateConDensation( int dynam_params,
01177                                              int measure_params,
01178                                              int sample_count );
01179 
01180 /* Releases ConDensation filter state */
01181 CVAPI(void)  cvReleaseConDensation( CvConDensation** condens );
01182 
01183 /* Updates ConDensation filter by time (predict future state of the system) */
01184 CVAPI(void)  cvConDensUpdateByTime( CvConDensation* condens);
01185 
01186 /* Initializes ConDensation filter samples  */
01187 CVAPI(void)  cvConDensInitSampleSet( CvConDensation* condens, CvMat* lower_bound, CvMat* upper_bound );
01188 
01189 CV_INLINE int iplWidth( const IplImage* img )
01190 {
01191     return !img ? 0 : !img->roi ? img->width : img->roi->width;
01192 }
01193 
01194 CV_INLINE int iplHeight( const IplImage* img )
01195 {
01196     return !img ? 0 : !img->roi ? img->height : img->roi->height;
01197 }
01198 
01199 #ifdef __cplusplus
01200 }
01201 #endif
01202 
01203 #ifdef __cplusplus
01204 
01205 /****************************************************************************************\
01206 *                                   Calibration engine                                   *
01207 \****************************************************************************************/
01208 
01209 typedef enum CvCalibEtalonType
01210 {
01211     CV_CALIB_ETALON_USER = -1,
01212     CV_CALIB_ETALON_CHESSBOARD = 0,
01213     CV_CALIB_ETALON_CHECKERBOARD = CV_CALIB_ETALON_CHESSBOARD
01214 }
01215 CvCalibEtalonType;
01216 
01217 class CV_EXPORTS CvCalibFilter
01218 {
01219 public:
01220     /* Constructor & destructor */
01221     CvCalibFilter();
01222     virtual ~CvCalibFilter();
01223 
01224     /* Sets etalon type - one for all cameras.
01225        etalonParams is used in case of pre-defined etalons (such as chessboard).
01226        Number of elements in etalonParams is determined by etalonType.
01227        E.g., if etalon type is CV_ETALON_TYPE_CHESSBOARD then:
01228          etalonParams[0] is number of squares per one side of etalon
01229          etalonParams[1] is number of squares per another side of etalon
01230          etalonParams[2] is linear size of squares in the board in arbitrary units.
01231        pointCount & points are used in case of
01232        CV_CALIB_ETALON_USER (user-defined) etalon. */
01233     virtual bool
01234         SetEtalon( CvCalibEtalonType etalonType, double* etalonParams,
01235                    int pointCount = 0, CvPoint2D32f* points = 0 );
01236 
01237     /* Retrieves etalon parameters/or and points */
01238     virtual CvCalibEtalonType
01239         GetEtalon( int* paramCount = 0, const double** etalonParams = 0,
01240                    int* pointCount = 0, const CvPoint2D32f** etalonPoints = 0 ) const;
01241 
01242     /* Sets number of cameras calibrated simultaneously. It is equal to 1 initially */
01243     virtual void SetCameraCount( int cameraCount );
01244 
01245     /* Retrieves number of cameras */
01246     int GetCameraCount() const { return cameraCount; }
01247 
01248     /* Starts cameras calibration */
01249     virtual bool SetFrames( int totalFrames );
01250 
01251     /* Stops cameras calibration */
01252     virtual void Stop( bool calibrate = false );
01253 
01254     /* Retrieves number of cameras */
01255     bool IsCalibrated() const { return isCalibrated; }
01256 
01257     /* Feeds another serie of snapshots (one per each camera) to filter.
01258        Etalon points on these images are found automatically.
01259        If the function can't locate points, it returns false */
01260     virtual bool FindEtalon( IplImage** imgs );
01261 
01262     /* The same but takes matrices */
01263     virtual bool FindEtalon( CvMat** imgs );
01264 
01265     /* Lower-level function for feeding filter with already found etalon points.
01266        Array of point arrays for each camera is passed. */
01267     virtual bool Push( const CvPoint2D32f** points = 0 );
01268 
01269     /* Returns total number of accepted frames and, optionally,
01270        total number of frames to collect */
01271     virtual int GetFrameCount( int* framesTotal = 0 ) const;
01272 
01273     /* Retrieves camera parameters for specified camera.
01274        If camera is not calibrated the function returns 0 */
01275     virtual const CvCamera* GetCameraParams( int idx = 0 ) const;
01276 
01277     virtual const CvStereoCamera* GetStereoParams() const;
01278 
01279     /* Sets camera parameters for all cameras */
01280     virtual bool SetCameraParams( CvCamera* params );
01281 
01282     /* Saves all camera parameters to file */
01283     virtual bool SaveCameraParams( const char* filename );
01284 
01285     /* Loads all camera parameters from file */
01286     virtual bool LoadCameraParams( const char* filename );
01287 
01288     /* Undistorts images using camera parameters. Some of src pointers can be NULL. */
01289     virtual bool Undistort( IplImage** src, IplImage** dst );
01290 
01291     /* Undistorts images using camera parameters. Some of src pointers can be NULL. */
01292     virtual bool Undistort( CvMat** src, CvMat** dst );
01293 
01294     /* Returns array of etalon points detected/partally detected
01295        on the latest frame for idx-th camera */
01296     virtual bool GetLatestPoints( int idx, CvPoint2D32f** pts,
01297                                                   int* count, bool* found );
01298 
01299     /* Draw the latest detected/partially detected etalon */
01300     virtual void DrawPoints( IplImage** dst );
01301 
01302     /* Draw the latest detected/partially detected etalon */
01303     virtual void DrawPoints( CvMat** dst );
01304 
01305     virtual bool Rectify( IplImage** srcarr, IplImage** dstarr );
01306     virtual bool Rectify( CvMat** srcarr, CvMat** dstarr );
01307 
01308 protected:
01309 
01310     enum { MAX_CAMERAS = 3 };
01311 
01312     /* etalon data */
01313     CvCalibEtalonType  etalonType;
01314     int     etalonParamCount;
01315     double* etalonParams;
01316     int     etalonPointCount;
01317     CvPoint2D32f* etalonPoints;
01318     CvSize  imgSize;
01319     CvMat*  grayImg;
01320     CvMat*  tempImg;
01321     CvMemStorage* storage;
01322 
01323     /* camera data */
01324     int     cameraCount;
01325     CvCamera cameraParams[MAX_CAMERAS];
01326     CvStereoCamera stereo;
01327     CvPoint2D32f* points[MAX_CAMERAS];
01328     CvMat*  undistMap[MAX_CAMERAS][2];
01329     CvMat*  undistImg;
01330     int     latestCounts[MAX_CAMERAS];
01331     CvPoint2D32f* latestPoints[MAX_CAMERAS];
01332     CvMat*  rectMap[MAX_CAMERAS][2];
01333 
01334     /* Added by Valery */
01335     //CvStereoCamera stereoParams;
01336 
01337     int     maxPoints;
01338     int     framesTotal;
01339     int     framesAccepted;
01340     bool    isCalibrated;
01341 };
01342 
01343 #include <iosfwd>
01344 #include <limits>
01345 
01346 class CV_EXPORTS CvImage
01347 {
01348 public:
01349     CvImage() : image(0), refcount(0) {}
01350     CvImage( CvSize _size, int _depth, int _channels )
01351     {
01352         image = cvCreateImage( _size, _depth, _channels );
01353         refcount = image ? new int(1) : 0;
01354     }
01355 
01356     CvImage( IplImage* img ) : image(img)
01357     {
01358         refcount = image ? new int(1) : 0;
01359     }
01360 
01361     CvImage( const CvImage& img ) : image(img.image), refcount(img.refcount)
01362     {
01363         if( refcount ) ++(*refcount);
01364     }
01365 
01366     CvImage( const char* filename, const char* imgname=0, int color=-1 ) : image(0), refcount(0)
01367     { load( filename, imgname, color ); }
01368 
01369     CvImage( CvFileStorage* fs, const char* mapname, const char* imgname ) : image(0), refcount(0)
01370     { read( fs, mapname, imgname ); }
01371 
01372     CvImage( CvFileStorage* fs, const char* seqname, int idx ) : image(0), refcount(0)
01373     { read( fs, seqname, idx ); }
01374 
01375     ~CvImage()
01376     {
01377         if( refcount && !(--*refcount) )
01378         {
01379             cvReleaseImage( &image );
01380             delete refcount;
01381         }
01382     }
01383 
01384     CvImage clone() { return CvImage(image ? cvCloneImage(image) : 0); }
01385 
01386     void create( CvSize _size, int _depth, int _channels )
01387     {
01388         if( !image || !refcount ||
01389            image->width != _size.width || image->height != _size.height ||
01390            image->depth != _depth || image->nChannels != _channels )
01391             attach( cvCreateImage( _size, _depth, _channels ));
01392     }
01393 
01394     void release() { detach(); }
01395     void clear() { detach(); }
01396 
01397     void attach( IplImage* img, bool use_refcount=true )
01398     {
01399         if( refcount && --*refcount == 0 )
01400         {
01401             cvReleaseImage( &image );
01402             delete refcount;
01403         }
01404         image = img;
01405         refcount = use_refcount && image ? new int(1) : 0;
01406     }
01407 
01408     void detach()
01409     {
01410         if( refcount && --*refcount == 0 )
01411         {
01412             cvReleaseImage( &image );
01413             delete refcount;
01414         }
01415         image = 0;
01416         refcount = 0;
01417     }
01418 
01419     bool load( const char* filename, const char* imgname=0, int color=-1 );
01420     bool read( CvFileStorage* fs, const char* mapname, const char* imgname );
01421     bool read( CvFileStorage* fs, const char* seqname, int idx );
01422     void save( const char* filename, const char* imgname, const int* params=0 );
01423     void write( CvFileStorage* fs, const char* imgname );
01424 
01425     void show( const char* window_name );
01426     bool is_valid() { return image != 0; }
01427 
01428     int width() const { return image ? image->width : 0; }
01429     int height() const { return image ? image->height : 0; }
01430 
01431     CvSize size() const { return image ? cvSize(image->width, image->height) : cvSize(0,0); }
01432 
01433     CvSize roi_size() const
01434     {
01435         return !image ? cvSize(0,0) :
01436         !image->roi ? cvSize(image->width,image->height) :
01437         cvSize(image->roi->width, image->roi->height);
01438     }
01439 
01440     CvRect roi() const
01441     {
01442         return !image ? cvRect(0,0,0,0) :
01443         !image->roi ? cvRect(0,0,image->width,image->height) :
01444         cvRect(image->roi->xOffset,image->roi->yOffset,
01445                image->roi->width,image->roi->height);
01446     }
01447 
01448     int coi() const { return !image || !image->roi ? 0 : image->roi->coi; }
01449 
01450     void set_roi(CvRect _roi) { cvSetImageROI(image,_roi); }
01451     void reset_roi() { cvResetImageROI(image); }
01452     void set_coi(int _coi) { cvSetImageCOI(image,_coi); }
01453     int depth() const { return image ? image->depth : 0; }
01454     int channels() const { return image ? image->nChannels : 0; }
01455     int pix_size() const { return image ? ((image->depth & 255)>>3)*image->nChannels : 0; }
01456 
01457     uchar* data() { return image ? (uchar*)image->imageData : 0; }
01458     const uchar* data() const { return image ? (const uchar*)image->imageData : 0; }
01459     int step() const { return image ? image->widthStep : 0; }
01460     int origin() const { return image ? image->origin : 0; }
01461 
01462     uchar* roi_row(int y)
01463     {
01464         assert(0<=y);
01465         assert(!image ?
01466                1 : image->roi ?
01467                y<image->roi->height : y<image->height);
01468 
01469         return !image ? 0 :
01470         !image->roi ?
01471         (uchar*)(image->imageData + y*image->widthStep) :
01472         (uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep +
01473                  image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels);
01474     }
01475 
01476     const uchar* roi_row(int y) const
01477     {
01478         assert(0<=y);
01479         assert(!image ?
01480                1 : image->roi ?
01481                y<image->roi->height : y<image->height);
01482 
01483         return !image ? 0 :
01484         !image->roi ?
01485         (const uchar*)(image->imageData + y*image->widthStep) :
01486         (const uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep +
01487                        image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels);
01488     }
01489 
01490     operator const IplImage* () const { return image; }
01491     operator IplImage* () { return image; }
01492 
01493     CvImage& operator = (const CvImage& img)
01494     {
01495         if( img.refcount )
01496             ++*img.refcount;
01497         if( refcount && !(--*refcount) )
01498             cvReleaseImage( &image );
01499         image=img.image;
01500         refcount=img.refcount;
01501         return *this;
01502     }
01503 
01504 protected:
01505     IplImage* image;
01506     int* refcount;
01507 };
01508 
01509 
01510 class CV_EXPORTS CvMatrix
01511 {
01512 public:
01513     CvMatrix() : matrix(0) {}
01514     CvMatrix( int _rows, int _cols, int _type )
01515     { matrix = cvCreateMat( _rows, _cols, _type ); }
01516 
01517     CvMatrix( int _rows, int _cols, int _type, CvMat* hdr,
01518              void* _data=0, int _step=CV_AUTOSTEP )
01519     { matrix = cvInitMatHeader( hdr, _rows, _cols, _type, _data, _step ); }
01520 
01521     CvMatrix( int rows, int cols, int type, CvMemStorage* storage, bool alloc_data=true );
01522 
01523     CvMatrix( int _rows, int _cols, int _type, void* _data, int _step=CV_AUTOSTEP )
01524     { matrix = cvCreateMatHeader( _rows, _cols, _type );
01525         cvSetData( matrix, _data, _step ); }
01526 
01527     CvMatrix( CvMat* m )
01528     { matrix = m; }
01529 
01530     CvMatrix( const CvMatrix& m )
01531     {
01532         matrix = m.matrix;
01533         addref();
01534     }
01535 
01536     CvMatrix( const char* filename, const char* matname=0, int color=-1 ) : matrix(0)
01537     {  load( filename, matname, color ); }
01538 
01539     CvMatrix( CvFileStorage* fs, const char* mapname, const char* matname ) : matrix(0)
01540     {  read( fs, mapname, matname ); }
01541 
01542     CvMatrix( CvFileStorage* fs, const char* seqname, int idx ) : matrix(0)
01543     {  read( fs, seqname, idx ); }
01544 
01545     ~CvMatrix()
01546     {
01547         release();
01548     }
01549 
01550     CvMatrix clone() { return CvMatrix(matrix ? cvCloneMat(matrix) : 0); }
01551 
01552     void set( CvMat* m, bool add_ref )
01553     {
01554         release();
01555         matrix = m;
01556         if( add_ref )
01557             addref();
01558     }
01559 
01560     void create( int _rows, int _cols, int _type )
01561     {
01562         if( !matrix || !matrix->refcount ||
01563            matrix->rows != _rows || matrix->cols != _cols ||
01564            CV_MAT_TYPE(matrix->type) != _type )
01565             set( cvCreateMat( _rows, _cols, _type ), false );
01566     }
01567 
01568     void addref() const
01569     {
01570         if( matrix )
01571         {
01572             if( matrix->hdr_refcount )
01573                 ++matrix->hdr_refcount;
01574             else if( matrix->refcount )
01575                 ++*matrix->refcount;
01576         }
01577     }
01578 
01579     void release()
01580     {
01581         if( matrix )
01582         {
01583             if( matrix->hdr_refcount )
01584             {
01585                 if( --matrix->hdr_refcount == 0 )
01586                     cvReleaseMat( &matrix );
01587             }
01588             else if( matrix->refcount )
01589             {
01590                 if( --*matrix->refcount == 0 )
01591                     cvFree( &matrix->refcount );
01592             }
01593             matrix = 0;
01594         }
01595     }
01596 
01597     void clear()
01598     {
01599         release();
01600     }
01601 
01602     bool load( const char* filename, const char* matname=0, int color=-1 );
01603     bool read( CvFileStorage* fs, const char* mapname, const char* matname );
01604     bool read( CvFileStorage* fs, const char* seqname, int idx );
01605     void save( const char* filename, const char* matname, const int* params=0 );
01606     void write( CvFileStorage* fs, const char* matname );
01607 
01608     void show( const char* window_name );
01609 
01610     bool is_valid() { return matrix != 0; }
01611 
01612     int rows() const { return matrix ? matrix->rows : 0; }
01613     int cols() const { return matrix ? matrix->cols : 0; }
01614 
01615     CvSize size() const
01616     {
01617         return !matrix ? cvSize(0,0) : cvSize(matrix->rows,matrix->cols);
01618     }
01619 
01620     int type() const { return matrix ? CV_MAT_TYPE(matrix->type) : 0; }
01621     int depth() const { return matrix ? CV_MAT_DEPTH(matrix->type) : 0; }
01622     int channels() const { return matrix ? CV_MAT_CN(matrix->type) : 0; }
01623     int pix_size() const { return matrix ? CV_ELEM_SIZE(matrix->type) : 0; }
01624 
01625     uchar* data() { return matrix ? matrix->data.ptr : 0; }
01626     const uchar* data() const { return matrix ? matrix->data.ptr : 0; }
01627     int step() const { return matrix ? matrix->step : 0; }
01628 
01629     void set_data( void* _data, int _step=CV_AUTOSTEP )
01630     { cvSetData( matrix, _data, _step ); }
01631 
01632     uchar* row(int i) { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; }
01633     const uchar* row(int i) const
01634     { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; }
01635 
01636     operator const CvMat* () const { return matrix; }
01637     operator CvMat* () { return matrix; }
01638 
01639     CvMatrix& operator = (const CvMatrix& _m)
01640     {
01641         _m.addref();
01642         release();
01643         matrix = _m.matrix;
01644         return *this;
01645     }
01646 
01647 protected:
01648     CvMat* matrix;
01649 };
01650 
01651 /****************************************************************************************\
01652  *                                       CamShiftTracker                                  *
01653  \****************************************************************************************/
01654 
01655 class CV_EXPORTS CvCamShiftTracker
01656 {
01657 public:
01658 
01659     CvCamShiftTracker();
01660     virtual ~CvCamShiftTracker();
01661 
01662     /**** Characteristics of the object that are calculated by track_object method *****/
01663     float   get_orientation() const // orientation of the object in degrees
01664     { return m_box.angle; }
01665     float   get_length() const // the larger linear size of the object
01666     { return m_box.size.height; }
01667     float   get_width() const // the smaller linear size of the object
01668     { return m_box.size.width; }
01669     CvPoint2D32f get_center() const // center of the object
01670     { return m_box.center; }
01671     CvRect get_window() const // bounding rectangle for the object
01672     { return m_comp.rect; }
01673 
01674     /*********************** Tracking parameters ************************/
01675     int     get_threshold() const // thresholding value that applied to back project
01676     { return m_threshold; }
01677 
01678     int     get_hist_dims( int* dims = 0 ) const // returns number of histogram dimensions and sets
01679     { return m_hist ? cvGetDims( m_hist->bins, dims ) : 0; }
01680 
01681     int     get_min_ch_val( int channel ) const // get the minimum allowed value of the specified channel
01682     { return m_min_ch_val[channel]; }
01683 
01684     int     get_max_ch_val( int channel ) const // get the maximum allowed value of the specified channel
01685     { return m_max_ch_val[channel]; }
01686 
01687     // set initial object rectangle (must be called before initial calculation of the histogram)
01688     bool    set_window( CvRect window)
01689     { m_comp.rect = window; return true; }
01690 
01691     bool    set_threshold( int threshold ) // threshold applied to the histogram bins
01692     { m_threshold = threshold; return true; }
01693 
01694     bool    set_hist_bin_range( int dim, int min_val, int max_val );
01695 
01696     bool    set_hist_dims( int c_dims, int* dims );// set the histogram parameters
01697 
01698     bool    set_min_ch_val( int channel, int val ) // set the minimum allowed value of the specified channel
01699     { m_min_ch_val[channel] = val; return true; }
01700     bool    set_max_ch_val( int channel, int val ) // set the maximum allowed value of the specified channel
01701     { m_max_ch_val[channel] = val; return true; }
01702 
01703     /************************ The processing methods *********************************/
01704     // update object position
01705     virtual bool  track_object( const IplImage* cur_frame );
01706 
01707     // update object histogram
01708     virtual bool  update_histogram( const IplImage* cur_frame );
01709 
01710     // reset histogram
01711     virtual void  reset_histogram();
01712 
01713     /************************ Retrieving internal data *******************************/
01714     // get back project image
01715     virtual IplImage* get_back_project()
01716     { return m_back_project; }
01717 
01718     float query( int* bin ) const
01719     { return m_hist ? (float)cvGetRealND(m_hist->bins, bin) : 0.f; }
01720 
01721 protected:
01722 
01723     // internal method for color conversion: fills m_color_planes group
01724     virtual void color_transform( const IplImage* img );
01725 
01726     CvHistogram* m_hist;
01727 
01728     CvBox2D    m_box;
01729     CvConnectedComp m_comp;
01730 
01731     float      m_hist_ranges_data[CV_MAX_DIM][2];
01732     float*     m_hist_ranges[CV_MAX_DIM];
01733 
01734     int        m_min_ch_val[CV_MAX_DIM];
01735     int        m_max_ch_val[CV_MAX_DIM];
01736     int        m_threshold;
01737 
01738     IplImage*  m_color_planes[CV_MAX_DIM];
01739     IplImage*  m_back_project;
01740     IplImage*  m_temp;
01741     IplImage*  m_mask;
01742 };
01743 
01744 /****************************************************************************************\
01745 *                              Expectation - Maximization                                *
01746 \****************************************************************************************/
01747 struct CV_EXPORTS_W_MAP CvEMParams
01748 {
01749     CvEMParams();
01750     CvEMParams( int nclusters, int cov_mat_type=cv::EM::COV_MAT_DIAGONAL,
01751                 int start_step=cv::EM::START_AUTO_STEP,
01752                 CvTermCriteria term_crit=cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON),
01753                 const CvMat* probs=0, const CvMat* weights=0, const CvMat* means=0, const CvMat** covs=0 );
01754 
01755     CV_PROP_RW int nclusters;
01756     CV_PROP_RW int cov_mat_type;
01757     CV_PROP_RW int start_step;
01758     const CvMat* probs;
01759     const CvMat* weights;
01760     const CvMat* means;
01761     const CvMat** covs;
01762     CV_PROP_RW CvTermCriteria term_crit;
01763 };
01764 
01765 
01766 class CV_EXPORTS_W CvEM : public CvStatModel
01767 {
01768 public:
01769     // Type of covariation matrices
01770     enum { COV_MAT_SPHERICAL=cv::EM::COV_MAT_SPHERICAL,
01771            COV_MAT_DIAGONAL =cv::EM::COV_MAT_DIAGONAL,
01772            COV_MAT_GENERIC  =cv::EM::COV_MAT_GENERIC };
01773 
01774     // The initial step
01775     enum { START_E_STEP=cv::EM::START_E_STEP,
01776            START_M_STEP=cv::EM::START_M_STEP,
01777            START_AUTO_STEP=cv::EM::START_AUTO_STEP };
01778 
01779     CV_WRAP CvEM();
01780     CvEM( const CvMat* samples, const CvMat* sampleIdx=0,
01781           CvEMParams params=CvEMParams(), CvMat* labels=0 );
01782 
01783     virtual ~CvEM();
01784 
01785     virtual bool train( const CvMat* samples, const CvMat* sampleIdx=0,
01786                         CvEMParams params=CvEMParams(), CvMat* labels=0 );
01787 
01788     virtual float predict( const CvMat* sample, CV_OUT CvMat* probs ) const;
01789 
01790     CV_WRAP CvEM( const cv::Mat& samples, const cv::Mat& sampleIdx=cv::Mat(),
01791                   CvEMParams params=CvEMParams() );
01792 
01793     CV_WRAP virtual bool train( const cv::Mat& samples,
01794                                 const cv::Mat& sampleIdx=cv::Mat(),
01795                                 CvEMParams params=CvEMParams(),
01796                                 CV_OUT cv::Mat* labels=0 );
01797 
01798     CV_WRAP virtual float predict( const cv::Mat& sample, CV_OUT cv::Mat* probs=0 ) const;
01799     CV_WRAP virtual double calcLikelihood( const cv::Mat &sample ) const;
01800 
01801     CV_WRAP int getNClusters() const;
01802     CV_WRAP cv::Mat getMeans() const;
01803     CV_WRAP void getCovs(CV_OUT std::vector<cv::Mat>& covs) const;
01804     CV_WRAP cv::Mat getWeights() const;
01805     CV_WRAP cv::Mat getProbs() const;
01806 
01807     CV_WRAP inline double getLikelihood() const { return emObj.isTrained() ? logLikelihood : DBL_MAX; }
01808 
01809     CV_WRAP virtual void clear();
01810 
01811     int get_nclusters() const;
01812     const CvMat* get_means() const;
01813     const CvMat** get_covs() const;
01814     const CvMat* get_weights() const;
01815     const CvMat* get_probs() const;
01816 
01817     inline double get_log_likelihood() const { return getLikelihood(); }
01818 
01819     virtual void read( CvFileStorage* fs, CvFileNode* node );
01820     virtual void write( CvFileStorage* fs, const char* name ) const;
01821 
01822 protected:
01823     void set_mat_hdrs();
01824 
01825     cv::EM emObj;
01826     cv::Mat probs;
01827     double logLikelihood;
01828 
01829     CvMat meansHdr;
01830     std::vector<CvMat> covsHdrs;
01831     std::vector<CvMat*> covsPtrs;
01832     CvMat weightsHdr;
01833     CvMat probsHdr;
01834 };
01835 
01836 namespace cv
01837 {
01838 
01839 typedef CvEMParams EMParams;
01840 typedef CvEM ExpectationMaximization;
01841 
01845 class CV_EXPORTS PatchGenerator
01846 {
01847 public:
01848     PatchGenerator();
01849     PatchGenerator(double _backgroundMin, double _backgroundMax,
01850                    double _noiseRange, bool _randomBlur=true,
01851                    double _lambdaMin=0.6, double _lambdaMax=1.5,
01852                    double _thetaMin=-CV_PI, double _thetaMax=CV_PI,
01853                    double _phiMin=-CV_PI, double _phiMax=CV_PI );
01854     void operator()(const Mat& image, Point2f pt, Mat& patch, Size patchSize, RNG& rng) const;
01855     void operator()(const Mat& image, const Mat& transform, Mat& patch,
01856                     Size patchSize, RNG& rng) const;
01857     void warpWholeImage(const Mat& image, Mat& matT, Mat& buf,
01858                         CV_OUT Mat& warped, int border, RNG& rng) const;
01859     void generateRandomTransform(Point2f srcCenter, Point2f dstCenter,
01860                                  CV_OUT Mat& transform, RNG& rng,
01861                                  bool inverse=false) const;
01862     void setAffineParam(double lambda, double theta, double phi);
01863 
01864     double backgroundMin, backgroundMax;
01865     double noiseRange;
01866     bool randomBlur;
01867     double lambdaMin, lambdaMax;
01868     double thetaMin, thetaMax;
01869     double phiMin, phiMax;
01870 };
01871 
01872 
01873 class CV_EXPORTS LDetector
01874 {
01875 public:
01876     LDetector();
01877     LDetector(int _radius, int _threshold, int _nOctaves,
01878               int _nViews, double _baseFeatureSize, double _clusteringDistance);
01879     void operator()(const Mat& image,
01880                     CV_OUT vector<KeyPoint>& keypoints,
01881                     int maxCount=0, bool scaleCoords=true) const;
01882     void operator()(const vector<Mat>& pyr,
01883                     CV_OUT vector<KeyPoint>& keypoints,
01884                     int maxCount=0, bool scaleCoords=true) const;
01885     void getMostStable2D(const Mat& image, CV_OUT vector<KeyPoint>& keypoints,
01886                          int maxCount, const PatchGenerator& patchGenerator) const;
01887     void setVerbose(bool verbose);
01888 
01889     void read(const FileNode& node);
01890     void write(FileStorage& fs, const String& name=String()) const;
01891 
01892     int radius;
01893     int threshold;
01894     int nOctaves;
01895     int nViews;
01896     bool verbose;
01897 
01898     double baseFeatureSize;
01899     double clusteringDistance;
01900 };
01901 
01902 typedef LDetector YAPE;
01903 
01904 class CV_EXPORTS FernClassifier
01905 {
01906 public:
01907     FernClassifier();
01908     FernClassifier(const FileNode& node);
01909     FernClassifier(const vector<vector<Point2f> >& points,
01910                    const vector<Mat>& refimgs,
01911                    const vector<vector<int> >& labels=vector<vector<int> >(),
01912                    int _nclasses=0, int _patchSize=PATCH_SIZE,
01913                    int _signatureSize=DEFAULT_SIGNATURE_SIZE,
01914                    int _nstructs=DEFAULT_STRUCTS,
01915                    int _structSize=DEFAULT_STRUCT_SIZE,
01916                    int _nviews=DEFAULT_VIEWS,
01917                    int _compressionMethod=COMPRESSION_NONE,
01918                    const PatchGenerator& patchGenerator=PatchGenerator());
01919     virtual ~FernClassifier();
01920     virtual void read(const FileNode& n);
01921     virtual void write(FileStorage& fs, const String& name=String()) const;
01922     virtual void trainFromSingleView(const Mat& image,
01923                                      const vector<KeyPoint>& keypoints,
01924                                      int _patchSize=PATCH_SIZE,
01925                                      int _signatureSize=DEFAULT_SIGNATURE_SIZE,
01926                                      int _nstructs=DEFAULT_STRUCTS,
01927                                      int _structSize=DEFAULT_STRUCT_SIZE,
01928                                      int _nviews=DEFAULT_VIEWS,
01929                                      int _compressionMethod=COMPRESSION_NONE,
01930                                      const PatchGenerator& patchGenerator=PatchGenerator());
01931     virtual void train(const vector<vector<Point2f> >& points,
01932                        const vector<Mat>& refimgs,
01933                        const vector<vector<int> >& labels=vector<vector<int> >(),
01934                        int _nclasses=0, int _patchSize=PATCH_SIZE,
01935                        int _signatureSize=DEFAULT_SIGNATURE_SIZE,
01936                        int _nstructs=DEFAULT_STRUCTS,
01937                        int _structSize=DEFAULT_STRUCT_SIZE,
01938                        int _nviews=DEFAULT_VIEWS,
01939                        int _compressionMethod=COMPRESSION_NONE,
01940                        const PatchGenerator& patchGenerator=PatchGenerator());
01941     virtual int operator()(const Mat& img, Point2f kpt, vector<float>& signature) const;
01942     virtual int operator()(const Mat& patch, vector<float>& signature) const;
01943     virtual void clear();
01944     virtual bool empty() const;
01945     void setVerbose(bool verbose);
01946 
01947     int getClassCount() const;
01948     int getStructCount() const;
01949     int getStructSize() const;
01950     int getSignatureSize() const;
01951     int getCompressionMethod() const;
01952     Size getPatchSize() const;
01953 
01954     struct Feature
01955     {
01956         uchar x1, y1, x2, y2;
01957         Feature() : x1(0), y1(0), x2(0), y2(0) {}
01958         Feature(int _x1, int _y1, int _x2, int _y2)
01959         : x1((uchar)_x1), y1((uchar)_y1), x2((uchar)_x2), y2((uchar)_y2)
01960         {}
01961         template<typename _Tp> bool operator ()(const Mat_<_Tp>& patch) const
01962         { return patch(y1,x1) > patch(y2, x2); }
01963     };
01964 
01965     enum
01966     {
01967         PATCH_SIZE = 31,
01968         DEFAULT_STRUCTS = 50,
01969         DEFAULT_STRUCT_SIZE = 9,
01970         DEFAULT_VIEWS = 5000,
01971         DEFAULT_SIGNATURE_SIZE = 176,
01972         COMPRESSION_NONE = 0,
01973         COMPRESSION_RANDOM_PROJ = 1,
01974         COMPRESSION_PCA = 2,
01975         DEFAULT_COMPRESSION_METHOD = COMPRESSION_NONE
01976     };
01977 
01978 protected:
01979     virtual void prepare(int _nclasses, int _patchSize, int _signatureSize,
01980                          int _nstructs, int _structSize,
01981                          int _nviews, int _compressionMethod);
01982     virtual void finalize(RNG& rng);
01983     virtual int getLeaf(int fidx, const Mat& patch) const;
01984 
01985     bool verbose;
01986     int nstructs;
01987     int structSize;
01988     int nclasses;
01989     int signatureSize;
01990     int compressionMethod;
01991     int leavesPerStruct;
01992     Size patchSize;
01993     vector<Feature> features;
01994     vector<int> classCounters;
01995     vector<float> posteriors;
01996 };
01997 
01998 
01999 /****************************************************************************************\
02000  *                                 Calonder Classifier                                    *
02001  \****************************************************************************************/
02002 
02003 struct RTreeNode;
02004 
02005 struct CV_EXPORTS BaseKeypoint
02006 {
02007     int x;
02008     int y;
02009     IplImage* image;
02010 
02011     BaseKeypoint()
02012     : x(0), y(0), image(NULL)
02013     {}
02014 
02015     BaseKeypoint(int _x, int _y, IplImage* _image)
02016     : x(_x), y(_y), image(_image)
02017     {}
02018 };
02019 
02020 class CV_EXPORTS RandomizedTree
02021 {
02022 public:
02023     friend class RTreeClassifier;
02024 
02025     static const uchar PATCH_SIZE = 32;
02026     static const int DEFAULT_DEPTH = 9;
02027     static const int DEFAULT_VIEWS = 5000;
02028     static const size_t DEFAULT_REDUCED_NUM_DIM = 176;
02029     static float GET_LOWER_QUANT_PERC() { return .03f; }
02030     static float GET_UPPER_QUANT_PERC() { return .92f; }
02031 
02032     RandomizedTree();
02033     ~RandomizedTree();
02034 
02035     void train(vector<BaseKeypoint> const& base_set, RNG &rng,
02036                int depth, int views, size_t reduced_num_dim, int num_quant_bits);
02037     void train(vector<BaseKeypoint> const& base_set, RNG &rng,
02038                PatchGenerator &make_patch, int depth, int views, size_t reduced_num_dim,
02039                int num_quant_bits);
02040 
02041     // following two funcs are EXPERIMENTAL (do not use unless you know exactly what you do)
02042     static void quantizeVector(float *vec, int dim, int N, float bnds[2], int clamp_mode=0);
02043     static void quantizeVector(float *src, int dim, int N, float bnds[2], uchar *dst);
02044 
02045     // patch_data must be a 32x32 array (no row padding)
02046     float* getPosterior(uchar* patch_data);
02047     const float* getPosterior(uchar* patch_data) const;
02048     uchar* getPosterior2(uchar* patch_data);
02049     const uchar* getPosterior2(uchar* patch_data) const;
02050 
02051     void read(const char* file_name, int num_quant_bits);
02052     void read(std::istream &is, int num_quant_bits);
02053     void write(const char* file_name) const;
02054     void write(std::ostream &os) const;
02055 
02056     int classes() { return classes_; }
02057     int depth() { return depth_; }
02058 
02059     //void setKeepFloatPosteriors(bool b) { keep_float_posteriors_ = b; }
02060     void discardFloatPosteriors() { freePosteriors(1); }
02061 
02062     inline void applyQuantization(int num_quant_bits) { makePosteriors2(num_quant_bits); }
02063 
02064     // debug
02065     void savePosteriors(std::string url, bool append=false);
02066     void savePosteriors2(std::string url, bool append=false);
02067 
02068 private:
02069     int classes_;
02070     int depth_;
02071     int num_leaves_;
02072     vector<RTreeNode> nodes_;
02073     float **posteriors_;        // 16-bytes aligned posteriors
02074     uchar **posteriors2_;     // 16-bytes aligned posteriors
02075     vector<int> leaf_counts_;
02076 
02077     void createNodes(int num_nodes, RNG &rng);
02078     void allocPosteriorsAligned(int num_leaves, int num_classes);
02079     void freePosteriors(int which);    // which: 1=posteriors_, 2=posteriors2_, 3=both
02080     void init(int classes, int depth, RNG &rng);
02081     void addExample(int class_id, uchar* patch_data);
02082     void finalize(size_t reduced_num_dim, int num_quant_bits);
02083     int getIndex(uchar* patch_data) const;
02084     inline float* getPosteriorByIndex(int index);
02085     inline const float* getPosteriorByIndex(int index) const;
02086     inline uchar* getPosteriorByIndex2(int index);
02087     inline const uchar* getPosteriorByIndex2(int index) const;
02088     //void makeRandomMeasMatrix(float *cs_phi, PHI_DISTR_TYPE dt, size_t reduced_num_dim);
02089     void convertPosteriorsToChar();
02090     void makePosteriors2(int num_quant_bits);
02091     void compressLeaves(size_t reduced_num_dim);
02092     void estimateQuantPercForPosteriors(float perc[2]);
02093 };
02094 
02095 
02096 inline uchar* getData(IplImage* image)
02097 {
02098     return reinterpret_cast<uchar*>(image->imageData);
02099 }
02100 
02101 inline float* RandomizedTree::getPosteriorByIndex(int index)
02102 {
02103     return const_cast<float*>(const_cast<const RandomizedTree*>(this)->getPosteriorByIndex(index));
02104 }
02105 
02106 inline const float* RandomizedTree::getPosteriorByIndex(int index) const
02107 {
02108     return posteriors_[index];
02109 }
02110 
02111 inline uchar* RandomizedTree::getPosteriorByIndex2(int index)
02112 {
02113     return const_cast<uchar*>(const_cast<const RandomizedTree*>(this)->getPosteriorByIndex2(index));
02114 }
02115 
02116 inline const uchar* RandomizedTree::getPosteriorByIndex2(int index) const
02117 {
02118     return posteriors2_[index];
02119 }
02120 
02121 struct CV_EXPORTS RTreeNode
02122 {
02123     short offset1, offset2;
02124 
02125     RTreeNode() {}
02126     RTreeNode(uchar x1, uchar y1, uchar x2, uchar y2)
02127     : offset1(y1*RandomizedTree::PATCH_SIZE + x1),
02128     offset2(y2*RandomizedTree::PATCH_SIZE + x2)
02129     {}
02130 
02132     inline bool operator() (uchar* patch_data) const
02133     {
02134         return patch_data[offset1] > patch_data[offset2];
02135     }
02136 };
02137 
02138 class CV_EXPORTS RTreeClassifier
02139 {
02140 public:
02141     static const int DEFAULT_TREES = 48;
02142     static const size_t DEFAULT_NUM_QUANT_BITS = 4;
02143 
02144     RTreeClassifier();
02145     void train(vector<BaseKeypoint> const& base_set,
02146                RNG &rng,
02147                int num_trees = RTreeClassifier::DEFAULT_TREES,
02148                int depth = RandomizedTree::DEFAULT_DEPTH,
02149                int views = RandomizedTree::DEFAULT_VIEWS,
02150                size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM,
02151                int num_quant_bits = DEFAULT_NUM_QUANT_BITS);
02152     void train(vector<BaseKeypoint> const& base_set,
02153                RNG &rng,
02154                PatchGenerator &make_patch,
02155                int num_trees = RTreeClassifier::DEFAULT_TREES,
02156                int depth = RandomizedTree::DEFAULT_DEPTH,
02157                int views = RandomizedTree::DEFAULT_VIEWS,
02158                size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM,
02159                int num_quant_bits = DEFAULT_NUM_QUANT_BITS);
02160 
02161     // sig must point to a memory block of at least classes()*sizeof(float|uchar) bytes
02162     void getSignature(IplImage *patch, uchar *sig) const;
02163     void getSignature(IplImage *patch, float *sig) const;
02164     void getSparseSignature(IplImage *patch, float *sig, float thresh) const;
02165     // TODO: deprecated in favor of getSignature overload, remove
02166     void getFloatSignature(IplImage *patch, float *sig) const { getSignature(patch, sig); }
02167 
02168     static int countNonZeroElements(float *vec, int n, double tol=1e-10);
02169     static inline void safeSignatureAlloc(uchar **sig, int num_sig=1, int sig_len=176);
02170     static inline uchar* safeSignatureAlloc(int num_sig=1, int sig_len=176);
02171 
02172     inline int classes() const { return classes_; }
02173     inline int original_num_classes() const { return original_num_classes_; }
02174 
02175     void setQuantization(int num_quant_bits);
02176     void discardFloatPosteriors();
02177 
02178     void read(const char* file_name);
02179     void read(std::istream &is);
02180     void write(const char* file_name) const;
02181     void write(std::ostream &os) const;
02182 
02183     // experimental and debug
02184     void saveAllFloatPosteriors(std::string file_url);
02185     void saveAllBytePosteriors(std::string file_url);
02186     void setFloatPosteriorsFromTextfile_176(std::string url);
02187     float countZeroElements();
02188 
02189     vector<RandomizedTree> trees_;
02190 
02191 private:
02192     int classes_;
02193     int num_quant_bits_;
02194     mutable uchar **posteriors_;
02195     mutable unsigned short *ptemp_;
02196     int original_num_classes_;
02197     bool keep_floats_;
02198 };
02199 
02200 /****************************************************************************************\
02201 *                                     One-Way Descriptor                                 *
02202 \****************************************************************************************/
02203 
02204 // CvAffinePose: defines a parameterized affine transformation of an image patch.
02205 // An image patch is rotated on angle phi (in degrees), then scaled lambda1 times
02206 // along horizontal and lambda2 times along vertical direction, and then rotated again
02207 // on angle (theta - phi).
02208 class CV_EXPORTS CvAffinePose
02209 {
02210 public:
02211     float phi;
02212     float theta;
02213     float lambda1;
02214     float lambda2;
02215 };
02216 
02217 class CV_EXPORTS OneWayDescriptor
02218 {
02219 public:
02220     OneWayDescriptor();
02221     ~OneWayDescriptor();
02222 
02223     // allocates memory for given descriptor parameters
02224     void Allocate(int pose_count, CvSize size, int nChannels);
02225 
02226     // GenerateSamples: generates affine transformed patches with averaging them over small transformation variations.
02227     // If external poses and transforms were specified, uses them instead of generating random ones
02228     // - pose_count: the number of poses to be generated
02229     // - frontal: the input patch (can be a roi in a larger image)
02230     // - norm: if nonzero, normalizes the output patch so that the sum of pixel intensities is 1
02231     void GenerateSamples(int pose_count, IplImage* frontal, int norm = 0);
02232 
02233     // GenerateSamplesFast: generates affine transformed patches with averaging them over small transformation variations.
02234     // Uses precalculated transformed pca components.
02235     // - frontal: the input patch (can be a roi in a larger image)
02236     // - pca_hr_avg: pca average vector
02237     // - pca_hr_eigenvectors: pca eigenvectors
02238     // - pca_descriptors: an array of precomputed descriptors of pca components containing their affine transformations
02239     //   pca_descriptors[0] corresponds to the average, pca_descriptors[1]-pca_descriptors[pca_dim] correspond to eigenvectors
02240     void GenerateSamplesFast(IplImage* frontal, CvMat* pca_hr_avg,
02241                              CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors);
02242 
02243     // sets the poses and corresponding transforms
02244     void SetTransforms(CvAffinePose* poses, CvMat** transforms);
02245 
02246     // Initialize: builds a descriptor.
02247     // - pose_count: the number of poses to build. If poses were set externally, uses them rather than generating random ones
02248     // - frontal: input patch. Can be a roi in a larger image
02249     // - feature_name: the feature name to be associated with the descriptor
02250     // - norm: if 1, the affine transformed patches are normalized so that their sum is 1
02251     void Initialize(int pose_count, IplImage* frontal, const char* feature_name = 0, int norm = 0);
02252 
02253     // InitializeFast: builds a descriptor using precomputed descriptors of pca components
02254     // - pose_count: the number of poses to build
02255     // - frontal: input patch. Can be a roi in a larger image
02256     // - feature_name: the feature name to be associated with the descriptor
02257     // - pca_hr_avg: average vector for PCA
02258     // - pca_hr_eigenvectors: PCA eigenvectors (one vector per row)
02259     // - pca_descriptors: precomputed descriptors of PCA components, the first descriptor for the average vector
02260     // followed by the descriptors for eigenvectors
02261     void InitializeFast(int pose_count, IplImage* frontal, const char* feature_name,
02262                         CvMat* pca_hr_avg, CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors);
02263 
02264     // ProjectPCASample: unwarps an image patch into a vector and projects it into PCA space
02265     // - patch: input image patch
02266     // - avg: PCA average vector
02267     // - eigenvectors: PCA eigenvectors, one per row
02268     // - pca_coeffs: output PCA coefficients
02269     void ProjectPCASample(IplImage* patch, CvMat* avg, CvMat* eigenvectors, CvMat* pca_coeffs) const;
02270 
02271     // InitializePCACoeffs: projects all warped patches into PCA space
02272     // - avg: PCA average vector
02273     // - eigenvectors: PCA eigenvectors, one per row
02274     void InitializePCACoeffs(CvMat* avg, CvMat* eigenvectors);
02275 
02276     // EstimatePose: finds the closest match between an input patch and a set of patches with different poses
02277     // - patch: input image patch
02278     // - pose_idx: the output index of the closest pose
02279     // - distance: the distance to the closest pose (L2 distance)
02280     void EstimatePose(IplImage* patch, int& pose_idx, float& distance) const;
02281 
02282     // EstimatePosePCA: finds the closest match between an input patch and a set of patches with different poses.
02283     // The distance between patches is computed in PCA space
02284     // - patch: input image patch
02285     // - pose_idx: the output index of the closest pose
02286     // - distance: distance to the closest pose (L2 distance in PCA space)
02287     // - avg: PCA average vector. If 0, matching without PCA is used
02288     // - eigenvectors: PCA eigenvectors, one per row
02289     void EstimatePosePCA(CvArr* patch, int& pose_idx, float& distance, CvMat* avg, CvMat* eigenvalues) const;
02290 
02291     // GetPatchSize: returns the size of each image patch after warping (2 times smaller than the input patch)
02292     CvSize GetPatchSize() const
02293     {
02294         return m_patch_size;
02295     }
02296 
02297     // GetInputPatchSize: returns the required size of the patch that the descriptor is built from
02298     // (2 time larger than the patch after warping)
02299     CvSize GetInputPatchSize() const
02300     {
02301         return cvSize(m_patch_size.width*2, m_patch_size.height*2);
02302     }
02303 
02304     // GetPatch: returns a patch corresponding to specified pose index
02305     // - index: pose index
02306     // - return value: the patch corresponding to specified pose index
02307     IplImage* GetPatch(int index);
02308 
02309     // GetPose: returns a pose corresponding to specified pose index
02310     // - index: pose index
02311     // - return value: the pose corresponding to specified pose index
02312     CvAffinePose GetPose(int index) const;
02313 
02314     // Save: saves all patches with different poses to a specified path
02315     void Save(const char* path);
02316 
02317     // ReadByName: reads a descriptor from a file storage
02318     // - fs: file storage
02319     // - parent: parent node
02320     // - name: node name
02321     // - return value: 1 if succeeded, 0 otherwise
02322     int ReadByName(CvFileStorage* fs, CvFileNode* parent, const char* name);
02323 
02324     // ReadByName: reads a descriptor from a file node
02325     // - parent: parent node
02326     // - name: node name
02327     // - return value: 1 if succeeded, 0 otherwise
02328     int ReadByName(const FileNode &parent, const char* name);
02329 
02330     // Write: writes a descriptor into a file storage
02331     // - fs: file storage
02332     // - name: node name
02333     void Write(CvFileStorage* fs, const char* name);
02334 
02335     // GetFeatureName: returns a name corresponding to a feature
02336     const char* GetFeatureName() const;
02337 
02338     // GetCenter: returns the center of the feature
02339     CvPoint GetCenter() const;
02340 
02341     void SetPCADimHigh(int pca_dim_high) {m_pca_dim_high = pca_dim_high;};
02342     void SetPCADimLow(int pca_dim_low) {m_pca_dim_low = pca_dim_low;};
02343 
02344     int GetPCADimLow() const;
02345     int GetPCADimHigh() const;
02346 
02347     CvMat** GetPCACoeffs() const {return m_pca_coeffs;}
02348 
02349 protected:
02350     int m_pose_count; // the number of poses
02351     CvSize m_patch_size; // size of each image
02352     IplImage** m_samples; // an array of length m_pose_count containing the patch in different poses
02353     IplImage* m_input_patch;
02354     IplImage* m_train_patch;
02355     CvMat** m_pca_coeffs; // an array of length m_pose_count containing pca decomposition of the patch in different poses
02356     CvAffinePose* m_affine_poses; // an array of poses
02357     CvMat** m_transforms; // an array of affine transforms corresponding to poses
02358 
02359     string m_feature_name; // the name of the feature associated with the descriptor
02360     CvPoint m_center; // the coordinates of the feature (the center of the input image ROI)
02361 
02362     int m_pca_dim_high; // the number of descriptor pca components to use for generating affine poses
02363     int m_pca_dim_low; // the number of pca components to use for comparison
02364 };
02365 
02366 
02367 // OneWayDescriptorBase: encapsulates functionality for training/loading a set of one way descriptors
02368 // and finding the nearest closest descriptor to an input feature
02369 class CV_EXPORTS OneWayDescriptorBase
02370 {
02371 public:
02372 
02373     // creates an instance of OneWayDescriptor from a set of training files
02374     // - patch_size: size of the input (large) patch
02375     // - pose_count: the number of poses to generate for each descriptor
02376     // - train_path: path to training files
02377     // - pca_config: the name of the file that contains PCA for small patches (2 times smaller
02378     // than patch_size each dimension
02379     // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size)
02380     // - pca_desc_config: the name of the file that contains descriptors of PCA components
02381     OneWayDescriptorBase(CvSize patch_size, int pose_count, const char* train_path = 0, const char* pca_config = 0,
02382                          const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1,
02383                          int pca_dim_high = 100, int pca_dim_low = 100);
02384 
02385     OneWayDescriptorBase(CvSize patch_size, int pose_count, const string &pca_filename, const string &train_path = string(), const string &images_list = string(),
02386                          float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1,
02387                          int pca_dim_high = 100, int pca_dim_low = 100);
02388 
02389 
02390     virtual ~OneWayDescriptorBase();
02391     void clear ();
02392 
02393 
02394     // Allocate: allocates memory for a given number of descriptors
02395     void Allocate(int train_feature_count);
02396 
02397     // AllocatePCADescriptors: allocates memory for pca descriptors
02398     void AllocatePCADescriptors();
02399 
02400     // returns patch size
02401     CvSize GetPatchSize() const {return m_patch_size;};
02402     // returns the number of poses for each descriptor
02403     int GetPoseCount() const {return m_pose_count;};
02404 
02405     // returns the number of pyramid levels
02406     int GetPyrLevels() const {return m_pyr_levels;};
02407 
02408     // returns the number of descriptors
02409     int GetDescriptorCount() const {return m_train_feature_count;};
02410 
02411     // CreateDescriptorsFromImage: creates descriptors for each of the input features
02412     // - src: input image
02413     // - features: input features
02414     // - pyr_levels: the number of pyramid levels
02415     void CreateDescriptorsFromImage(IplImage* src, const vector<KeyPoint>& features);
02416 
02417     // CreatePCADescriptors: generates descriptors for PCA components, needed for fast generation of feature descriptors
02418     void CreatePCADescriptors();
02419 
02420     // returns a feature descriptor by feature index
02421     const OneWayDescriptor* GetDescriptor(int desc_idx) const {return &m_descriptors[desc_idx];};
02422 
02423     // FindDescriptor: finds the closest descriptor
02424     // - patch: input image patch
02425     // - desc_idx: output index of the closest descriptor to the input patch
02426     // - pose_idx: output index of the closest pose of the closest descriptor to the input patch
02427     // - distance: distance from the input patch to the closest feature pose
02428     // - _scales: scales of the input patch for each descriptor
02429     // - scale_ranges: input scales variation (float[2])
02430     void FindDescriptor(IplImage* patch, int& desc_idx, int& pose_idx, float& distance, float* _scale = 0, float* scale_ranges = 0) const;
02431 
02432     // - patch: input image patch
02433     // - n: number of the closest indexes
02434     // - desc_idxs: output indexes of the closest descriptor to the input patch (n)
02435     // - pose_idx: output indexes of the closest pose of the closest descriptor to the input patch (n)
02436     // - distances: distance from the input patch to the closest feature pose (n)
02437     // - _scales: scales of the input patch
02438     // - scale_ranges: input scales variation (float[2])
02439     void FindDescriptor(IplImage* patch, int n, vector<int>& desc_idxs, vector<int>& pose_idxs,
02440                         vector<float>& distances, vector<float>& _scales, float* scale_ranges = 0) const;
02441 
02442     // FindDescriptor: finds the closest descriptor
02443     // - src: input image
02444     // - pt: center of the feature
02445     // - desc_idx: output index of the closest descriptor to the input patch
02446     // - pose_idx: output index of the closest pose of the closest descriptor to the input patch
02447     // - distance: distance from the input patch to the closest feature pose
02448     void FindDescriptor(IplImage* src, cv::Point2f pt, int& desc_idx, int& pose_idx, float& distance) const;
02449 
02450     // InitializePoses: generates random poses
02451     void InitializePoses();
02452 
02453     // InitializeTransformsFromPoses: generates 2x3 affine matrices from poses (initializes m_transforms)
02454     void InitializeTransformsFromPoses();
02455 
02456     // InitializePoseTransforms: subsequently calls InitializePoses and InitializeTransformsFromPoses
02457     void InitializePoseTransforms();
02458 
02459     // InitializeDescriptor: initializes a descriptor
02460     // - desc_idx: descriptor index
02461     // - train_image: image patch (ROI is supported)
02462     // - feature_label: feature textual label
02463     void InitializeDescriptor(int desc_idx, IplImage* train_image, const char* feature_label);
02464 
02465     void InitializeDescriptor(int desc_idx, IplImage* train_image, const KeyPoint& keypoint, const char* feature_label);
02466 
02467     // InitializeDescriptors: load features from an image and create descriptors for each of them
02468     void InitializeDescriptors(IplImage* train_image, const vector<KeyPoint>& features,
02469                                const char* feature_label = "", int desc_start_idx = 0);
02470 
02471     // Write: writes this object to a file storage
02472     // - fs: output filestorage
02473     void Write (FileStorage &fs) const;
02474 
02475     // Read: reads OneWayDescriptorBase object from a file node
02476     // - fn: input file node
02477     void Read (const FileNode &fn);
02478 
02479     // LoadPCADescriptors: loads PCA descriptors from a file
02480     // - filename: input filename
02481     int LoadPCADescriptors(const char* filename);
02482 
02483     // LoadPCADescriptors: loads PCA descriptors from a file node
02484     // - fn: input file node
02485     int LoadPCADescriptors(const FileNode &fn);
02486 
02487     // SavePCADescriptors: saves PCA descriptors to a file
02488     // - filename: output filename
02489     void SavePCADescriptors(const char* filename);
02490 
02491     // SavePCADescriptors: saves PCA descriptors to a file storage
02492     // - fs: output file storage
02493     void SavePCADescriptors(CvFileStorage* fs) const;
02494 
02495     // GeneratePCA: calculate and save PCA components and descriptors
02496     // - img_path: path to training PCA images directory
02497     // - images_list: filename with filenames of training PCA images
02498     void GeneratePCA(const char* img_path, const char* images_list, int pose_count=500);
02499 
02500     // SetPCAHigh: sets the high resolution pca matrices (copied to internal structures)
02501     void SetPCAHigh(CvMat* avg, CvMat* eigenvectors);
02502 
02503     // SetPCALow: sets the low resolution pca matrices (copied to internal structures)
02504     void SetPCALow(CvMat* avg, CvMat* eigenvectors);
02505 
02506     int GetLowPCA(CvMat** avg, CvMat** eigenvectors)
02507     {
02508         *avg = m_pca_avg;
02509         *eigenvectors = m_pca_eigenvectors;
02510         return m_pca_dim_low;
02511     };
02512 
02513     int GetPCADimLow() const {return m_pca_dim_low;};
02514     int GetPCADimHigh() const {return m_pca_dim_high;};
02515 
02516     void ConvertDescriptorsArrayToTree(); // Converting pca_descriptors array to KD tree
02517 
02518     // GetPCAFilename: get default PCA filename
02519     static string GetPCAFilename () { return "pca.yml"; }
02520 
02521     virtual bool empty() const { return m_train_feature_count <= 0 ? true : false; }
02522 
02523 protected:
02524     CvSize m_patch_size; // patch size
02525     int m_pose_count; // the number of poses for each descriptor
02526     int m_train_feature_count; // the number of the training features
02527     OneWayDescriptor* m_descriptors; // array of train feature descriptors
02528     CvMat* m_pca_avg; // PCA average Vector for small patches
02529     CvMat* m_pca_eigenvectors; // PCA eigenvectors for small patches
02530     CvMat* m_pca_hr_avg; // PCA average Vector for large patches
02531     CvMat* m_pca_hr_eigenvectors; // PCA eigenvectors for large patches
02532     OneWayDescriptor* m_pca_descriptors; // an array of PCA descriptors
02533 
02534     cv::flann::Index* m_pca_descriptors_tree;
02535     CvMat* m_pca_descriptors_matrix;
02536 
02537     CvAffinePose* m_poses; // array of poses
02538     CvMat** m_transforms; // array of affine transformations corresponding to poses
02539 
02540     int m_pca_dim_high;
02541     int m_pca_dim_low;
02542 
02543     int m_pyr_levels;
02544     float scale_min;
02545     float scale_max;
02546     float scale_step;
02547 
02548     // SavePCAall: saves PCA components and descriptors to a file storage
02549     // - fs: output file storage
02550     void SavePCAall (FileStorage &fs) const;
02551 
02552     // LoadPCAall: loads PCA components and descriptors from a file node
02553     // - fn: input file node
02554     void LoadPCAall (const FileNode &fn);
02555 };
02556 
02557 class CV_EXPORTS OneWayDescriptorObject : public OneWayDescriptorBase
02558 {
02559 public:
02560     // creates an instance of OneWayDescriptorObject from a set of training files
02561     // - patch_size: size of the input (large) patch
02562     // - pose_count: the number of poses to generate for each descriptor
02563     // - train_path: path to training files
02564     // - pca_config: the name of the file that contains PCA for small patches (2 times smaller
02565     // than patch_size each dimension
02566     // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size)
02567     // - pca_desc_config: the name of the file that contains descriptors of PCA components
02568     OneWayDescriptorObject(CvSize patch_size, int pose_count, const char* train_path, const char* pca_config,
02569                            const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1);
02570 
02571     OneWayDescriptorObject(CvSize patch_size, int pose_count, const string &pca_filename,
02572                            const string &train_path = string (), const string &images_list = string (),
02573                            float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1);
02574 
02575 
02576     virtual ~OneWayDescriptorObject();
02577 
02578     // Allocate: allocates memory for a given number of features
02579     // - train_feature_count: the total number of features
02580     // - object_feature_count: the number of features extracted from the object
02581     void Allocate(int train_feature_count, int object_feature_count);
02582 
02583 
02584     void SetLabeledFeatures(const vector<KeyPoint>& features) {m_train_features = features;};
02585     vector<KeyPoint>& GetLabeledFeatures() {return m_train_features;};
02586     const vector<KeyPoint>& GetLabeledFeatures() const {return m_train_features;};
02587     vector<KeyPoint> _GetLabeledFeatures() const;
02588 
02589     // IsDescriptorObject: returns 1 if descriptor with specified index is positive, otherwise 0
02590     int IsDescriptorObject(int desc_idx) const;
02591 
02592     // MatchPointToPart: returns the part number of a feature if it matches one of the object parts, otherwise -1
02593     int MatchPointToPart(CvPoint pt) const;
02594 
02595     // GetDescriptorPart: returns the part number of the feature corresponding to a specified descriptor
02596     // - desc_idx: descriptor index
02597     int GetDescriptorPart(int desc_idx) const;
02598 
02599 
02600     void InitializeObjectDescriptors(IplImage* train_image, const vector<KeyPoint>& features,
02601                                      const char* feature_label, int desc_start_idx = 0, float scale = 1.0f,
02602                                      int is_background = 0);
02603 
02604     // GetObjectFeatureCount: returns the number of object features
02605     int GetObjectFeatureCount() const {return m_object_feature_count;};
02606 
02607 protected:
02608     int* m_part_id; // contains part id for each of object descriptors
02609     vector<KeyPoint> m_train_features; // train features
02610     int m_object_feature_count; // the number of the positive features
02611 
02612 };
02613 
02614 
02615 /*
02616  *  OneWayDescriptorMatcher
02617  */
02618 class OneWayDescriptorMatcher;
02619 typedef OneWayDescriptorMatcher OneWayDescriptorMatch;
02620 
02621 class CV_EXPORTS OneWayDescriptorMatcher : public GenericDescriptorMatcher
02622 {
02623 public:
02624     class CV_EXPORTS Params
02625     {
02626     public:
02627         static const int POSE_COUNT = 500;
02628         static const int PATCH_WIDTH = 24;
02629         static const int PATCH_HEIGHT = 24;
02630         static float GET_MIN_SCALE() { return 0.7f; }
02631         static float GET_MAX_SCALE() { return 1.5f; }
02632         static float GET_STEP_SCALE() { return 1.2f; }
02633 
02634         Params( int poseCount = POSE_COUNT,
02635                Size patchSize = Size(PATCH_WIDTH, PATCH_HEIGHT),
02636                string pcaFilename = string(),
02637                string trainPath = string(), string trainImagesList = string(),
02638                float minScale = GET_MIN_SCALE(), float maxScale = GET_MAX_SCALE(),
02639                float stepScale = GET_STEP_SCALE() );
02640 
02641         int poseCount;
02642         Size patchSize;
02643         string pcaFilename;
02644         string trainPath;
02645         string trainImagesList;
02646 
02647         float minScale, maxScale, stepScale;
02648     };
02649 
02650     OneWayDescriptorMatcher( const Params& params=Params() );
02651     virtual ~OneWayDescriptorMatcher();
02652 
02653     void initialize( const Params& params, const Ptr<OneWayDescriptorBase>& base=Ptr<OneWayDescriptorBase>() );
02654 
02655     // Clears keypoints storing in collection and OneWayDescriptorBase
02656     virtual void clear();
02657 
02658     virtual void train();
02659 
02660     virtual bool isMaskSupported();
02661 
02662     virtual void read( const FileNode &fn );
02663     virtual void write( FileStorage& fs ) const;
02664 
02665     virtual bool empty() const;
02666 
02667     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const;
02668 
02669 protected:
02670     // Matches a set of keypoints from a single image of the training set. A rectangle with a center in a keypoint
02671     // and size (patch_width/2*scale, patch_height/2*scale) is cropped from the source image for each
02672     // keypoint. scale is iterated from DescriptorOneWayParams::min_scale to DescriptorOneWayParams::max_scale.
02673     // The minimum distance to each training patch with all its affine poses is found over all scales.
02674     // The class ID of a match is returned for each keypoint. The distance is calculated over PCA components
02675     // loaded with DescriptorOneWay::Initialize, kd tree is used for finding minimum distances.
02676     virtual void knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
02677                               vector<vector<DMatch> >& matches, int k,
02678                               const vector<Mat>& masks, bool compactResult );
02679     virtual void radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
02680                                  vector<vector<DMatch> >& matches, float maxDistance,
02681                                  const vector<Mat>& masks, bool compactResult );
02682 
02683     Ptr<OneWayDescriptorBase> base;
02684     Params params;
02685     int prevTrainCount;
02686 };
02687 
02688 /*
02689  *  FernDescriptorMatcher
02690  */
02691 class FernDescriptorMatcher;
02692 typedef FernDescriptorMatcher FernDescriptorMatch;
02693 
02694 class CV_EXPORTS FernDescriptorMatcher : public GenericDescriptorMatcher
02695 {
02696 public:
02697     class CV_EXPORTS Params
02698     {
02699     public:
02700         Params( int nclasses=0,
02701                int patchSize=FernClassifier::PATCH_SIZE,
02702                int signatureSize=FernClassifier::DEFAULT_SIGNATURE_SIZE,
02703                int nstructs=FernClassifier::DEFAULT_STRUCTS,
02704                int structSize=FernClassifier::DEFAULT_STRUCT_SIZE,
02705                int nviews=FernClassifier::DEFAULT_VIEWS,
02706                int compressionMethod=FernClassifier::COMPRESSION_NONE,
02707                const PatchGenerator& patchGenerator=PatchGenerator() );
02708 
02709         Params( const string& filename );
02710 
02711         int nclasses;
02712         int patchSize;
02713         int signatureSize;
02714         int nstructs;
02715         int structSize;
02716         int nviews;
02717         int compressionMethod;
02718         PatchGenerator patchGenerator;
02719 
02720         string filename;
02721     };
02722 
02723     FernDescriptorMatcher( const Params& params=Params() );
02724     virtual ~FernDescriptorMatcher();
02725 
02726     virtual void clear();
02727 
02728     virtual void train();
02729 
02730     virtual bool isMaskSupported();
02731 
02732     virtual void read( const FileNode &fn );
02733     virtual void write( FileStorage& fs ) const;
02734     virtual bool empty() const;
02735 
02736     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const;
02737 
02738 protected:
02739     virtual void knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
02740                               vector<vector<DMatch> >& matches, int k,
02741                               const vector<Mat>& masks, bool compactResult );
02742     virtual void radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
02743                                  vector<vector<DMatch> >& matches, float maxDistance,
02744                                  const vector<Mat>& masks, bool compactResult );
02745 
02746     void trainFernClassifier();
02747     void calcBestProbAndMatchIdx( const Mat& image, const Point2f& pt,
02748                                  float& bestProb, int& bestMatchIdx, vector<float>& signature );
02749     Ptr<FernClassifier> classifier;
02750     Params params;
02751     int prevTrainCount;
02752 };
02753 
02754 
02755 /*
02756  * CalonderDescriptorExtractor
02757  */
02758 template<typename T>
02759 class CV_EXPORTS CalonderDescriptorExtractor : public DescriptorExtractor
02760 {
02761 public:
02762     CalonderDescriptorExtractor( const string& classifierFile );
02763 
02764     virtual void read( const FileNode &fn );
02765     virtual void write( FileStorage &fs ) const;
02766 
02767     virtual int descriptorSize() const { return classifier_.classes(); }
02768     virtual int descriptorType() const { return DataType<T>::type; }
02769 
02770     virtual bool empty() const;
02771 
02772 protected:
02773     virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
02774 
02775     RTreeClassifier classifier_;
02776     static const int BORDER_SIZE = 16;
02777 };
02778 
02779 template<typename T>
02780 CalonderDescriptorExtractor<T>::CalonderDescriptorExtractor(const std::string& classifier_file)
02781 {
02782     classifier_.read( classifier_file.c_str() );
02783 }
02784 
02785 template<typename T>
02786 void CalonderDescriptorExtractor<T>::computeImpl( const Mat& image,
02787                                                  vector<KeyPoint>& keypoints,
02788                                                  Mat& descriptors) const
02789 {
02790     // Cannot compute descriptors for keypoints on the image border.
02791     KeyPointsFilter::runByImageBorder(keypoints, image.size(), BORDER_SIZE);
02792 
02794     descriptors.create((int)keypoints.size(), classifier_.classes(), cv::DataType<T>::type);
02795 
02796     int patchSize = RandomizedTree::PATCH_SIZE;
02797     int offset = patchSize / 2;
02798     for (size_t i = 0; i < keypoints.size(); ++i)
02799     {
02800         cv::Point2f pt = keypoints[i].pt;
02801         IplImage ipl = image( Rect((int)(pt.x - offset), (int)(pt.y - offset), patchSize, patchSize) );
02802         classifier_.getSignature( &ipl, descriptors.ptr<T>((int)i));
02803     }
02804 }
02805 
02806 template<typename T>
02807 void CalonderDescriptorExtractor<T>::read( const FileNode& )
02808 {}
02809 
02810 template<typename T>
02811 void CalonderDescriptorExtractor<T>::write( FileStorage& ) const
02812 {}
02813 
02814 template<typename T>
02815 bool CalonderDescriptorExtractor<T>::empty() const
02816 {
02817     return classifier_.trees_.empty();
02818 }
02819 
02820 
02822 
02823 template<class Distance>
02824 class CV_EXPORTS BruteForceMatcher : public BFMatcher
02825 {
02826 public:
02827     BruteForceMatcher( Distance d = Distance() ) : BFMatcher(Distance::normType, false) {(void)d;}
02828     virtual ~BruteForceMatcher() {}
02829 };
02830 
02831 
02832 /****************************************************************************************\
02833 *                                Planar Object Detection                                 *
02834 \****************************************************************************************/
02835 
02836 class CV_EXPORTS PlanarObjectDetector
02837 {
02838 public:
02839     PlanarObjectDetector();
02840     PlanarObjectDetector(const FileNode& node);
02841     PlanarObjectDetector(const vector<Mat>& pyr, int _npoints=300,
02842                          int _patchSize=FernClassifier::PATCH_SIZE,
02843                          int _nstructs=FernClassifier::DEFAULT_STRUCTS,
02844                          int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE,
02845                          int _nviews=FernClassifier::DEFAULT_VIEWS,
02846                          const LDetector& detector=LDetector(),
02847                          const PatchGenerator& patchGenerator=PatchGenerator());
02848     virtual ~PlanarObjectDetector();
02849     virtual void train(const vector<Mat>& pyr, int _npoints=300,
02850                        int _patchSize=FernClassifier::PATCH_SIZE,
02851                        int _nstructs=FernClassifier::DEFAULT_STRUCTS,
02852                        int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE,
02853                        int _nviews=FernClassifier::DEFAULT_VIEWS,
02854                        const LDetector& detector=LDetector(),
02855                        const PatchGenerator& patchGenerator=PatchGenerator());
02856     virtual void train(const vector<Mat>& pyr, const vector<KeyPoint>& keypoints,
02857                        int _patchSize=FernClassifier::PATCH_SIZE,
02858                        int _nstructs=FernClassifier::DEFAULT_STRUCTS,
02859                        int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE,
02860                        int _nviews=FernClassifier::DEFAULT_VIEWS,
02861                        const LDetector& detector=LDetector(),
02862                        const PatchGenerator& patchGenerator=PatchGenerator());
02863     Rect getModelROI() const;
02864     vector<KeyPoint> getModelPoints() const;
02865     const LDetector& getDetector() const;
02866     const FernClassifier& getClassifier() const;
02867     void setVerbose(bool verbose);
02868 
02869     void read(const FileNode& node);
02870     void write(FileStorage& fs, const String& name=String()) const;
02871     bool operator()(const Mat& image, CV_OUT Mat& H, CV_OUT vector<Point2f>& corners) const;
02872     bool operator()(const vector<Mat>& pyr, const vector<KeyPoint>& keypoints,
02873                     CV_OUT Mat& H, CV_OUT vector<Point2f>& corners,
02874                     CV_OUT vector<int>* pairs=0) const;
02875 
02876 protected:
02877     bool verbose;
02878     Rect modelROI;
02879     vector<KeyPoint> modelPoints;
02880     LDetector ldetector;
02881     FernClassifier fernClassifier;
02882 };
02883 
02884 }
02885 
02886 // 2009-01-12, Xavier Delacour <xavier.delacour@gmail.com>
02887 
02888 struct lsh_hash {
02889     int h1, h2;
02890 };
02891 
02892 struct CvLSHOperations
02893 {
02894     virtual ~CvLSHOperations() {}
02895 
02896     virtual int vector_add(const void* data) = 0;
02897     virtual void vector_remove(int i) = 0;
02898     virtual const void* vector_lookup(int i) = 0;
02899     virtual void vector_reserve(int n) = 0;
02900     virtual unsigned int vector_count() = 0;
02901 
02902     virtual void hash_insert(lsh_hash h, int l, int i) = 0;
02903     virtual void hash_remove(lsh_hash h, int l, int i) = 0;
02904     virtual int hash_lookup(lsh_hash h, int l, int* ret_i, int ret_i_max) = 0;
02905 };
02906 
02907 #endif
02908 
02909 #ifdef __cplusplus
02910 extern "C" {
02911 #endif
02912 
02913 /* Splits color or grayscale image into multiple connected components
02914  of nearly the same color/brightness using modification of Burt algorithm.
02915  comp with contain a pointer to sequence (CvSeq)
02916  of connected components (CvConnectedComp) */
02917 CVAPI(void) cvPyrSegmentation( IplImage* src, IplImage* dst,
02918                               CvMemStorage* storage, CvSeq** comp,
02919                               int level, double threshold1,
02920                               double threshold2 );
02921 
02922 /****************************************************************************************\
02923 *                              Planar subdivisions                                       *
02924 \****************************************************************************************/
02925 
02926 /* Initializes Delaunay triangulation */
02927 CVAPI(void)  cvInitSubdivDelaunay2D( CvSubdiv2D* subdiv, CvRect rect );
02928 
02929 /* Creates new subdivision */
02930 CVAPI(CvSubdiv2D*)  cvCreateSubdiv2D( int subdiv_type, int header_size,
02931                                      int vtx_size, int quadedge_size,
02932                                      CvMemStorage* storage );
02933 
02934 /************************* high-level subdivision functions ***************************/
02935 
02936 /* Simplified Delaunay diagram creation */
02937 CV_INLINE  CvSubdiv2D* cvCreateSubdivDelaunay2D( CvRect rect, CvMemStorage* storage )
02938 {
02939     CvSubdiv2D* subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv),
02940                                           sizeof(CvSubdiv2DPoint), sizeof(CvQuadEdge2D), storage );
02941 
02942     cvInitSubdivDelaunay2D( subdiv, rect );
02943     return subdiv;
02944 }
02945 
02946 
02947 /* Inserts new point to the Delaunay triangulation */
02948 CVAPI(CvSubdiv2DPoint*)  cvSubdivDelaunay2DInsert( CvSubdiv2D* subdiv, CvPoint2D32f pt);
02949 
02950 /* Locates a point within the Delaunay triangulation (finds the edge
02951  the point is left to or belongs to, or the triangulation point the given
02952  point coinsides with */
02953 CVAPI(CvSubdiv2DPointLocation)  cvSubdiv2DLocate(
02954                                                  CvSubdiv2D* subdiv, CvPoint2D32f pt,
02955                                                  CvSubdiv2DEdge* edge,
02956                                                  CvSubdiv2DPoint** vertex CV_DEFAULT(NULL) );
02957 
02958 /* Calculates Voronoi tesselation (i.e. coordinates of Voronoi points) */
02959 CVAPI(void)  cvCalcSubdivVoronoi2D( CvSubdiv2D* subdiv );
02960 
02961 
02962 /* Removes all Voronoi points from the tesselation */
02963 CVAPI(void)  cvClearSubdivVoronoi2D( CvSubdiv2D* subdiv );
02964 
02965 
02966 /* Finds the nearest to the given point vertex in subdivision. */
02967 CVAPI(CvSubdiv2DPoint*) cvFindNearestPoint2D( CvSubdiv2D* subdiv, CvPoint2D32f pt );
02968 
02969 
02970 /************ Basic quad-edge navigation and operations ************/
02971 
02972 CV_INLINE  CvSubdiv2DEdge  cvSubdiv2DNextEdge( CvSubdiv2DEdge edge )
02973 {
02974     return  CV_SUBDIV2D_NEXT_EDGE(edge);
02975 }
02976 
02977 
02978 CV_INLINE  CvSubdiv2DEdge  cvSubdiv2DRotateEdge( CvSubdiv2DEdge edge, int rotate )
02979 {
02980     return  (edge & ~3) + ((edge + rotate) & 3);
02981 }
02982 
02983 CV_INLINE  CvSubdiv2DEdge  cvSubdiv2DSymEdge( CvSubdiv2DEdge edge )
02984 {
02985     return edge ^ 2;
02986 }
02987 
02988 CV_INLINE  CvSubdiv2DEdge  cvSubdiv2DGetEdge( CvSubdiv2DEdge edge, CvNextEdgeType type )
02989 {
02990     CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3);
02991     edge = e->next[(edge + (int)type) & 3];
02992     return  (edge & ~3) + ((edge + ((int)type >> 4)) & 3);
02993 }
02994 
02995 
02996 CV_INLINE  CvSubdiv2DPoint*  cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge )
02997 {
02998     CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3);
02999     return (CvSubdiv2DPoint*)e->pt[edge & 3];
03000 }
03001 
03002 
03003 CV_INLINE  CvSubdiv2DPoint*  cvSubdiv2DEdgeDst( CvSubdiv2DEdge edge )
03004 {
03005     CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3);
03006     return (CvSubdiv2DPoint*)e->pt[(edge + 2) & 3];
03007 }
03008 
03009 /****************************************************************************************\
03010 *                           Additional operations on Subdivisions                        *
03011 \****************************************************************************************/
03012 
03013 // paints voronoi diagram: just demo function
03014 CVAPI(void)  icvDrawMosaic( CvSubdiv2D* subdiv, IplImage* src, IplImage* dst );
03015 
03016 // checks planar subdivision for correctness. It is not an absolute check,
03017 // but it verifies some relations between quad-edges
03018 CVAPI(int)   icvSubdiv2DCheck( CvSubdiv2D* subdiv );
03019 
03020 // returns squared distance between two 2D points with floating-point coordinates.
03021 CV_INLINE double icvSqDist2D32f( CvPoint2D32f pt1, CvPoint2D32f pt2 )
03022 {
03023     double dx = pt1.x - pt2.x;
03024     double dy = pt1.y - pt2.y;
03025 
03026     return dx*dx + dy*dy;
03027 }
03028 
03029 
03030 
03031 
03032 CV_INLINE  double  cvTriangleArea( CvPoint2D32f a, CvPoint2D32f b, CvPoint2D32f c )
03033 {
03034     return ((double)b.x - a.x) * ((double)c.y - a.y) - ((double)b.y - a.y) * ((double)c.x - a.x);
03035 }
03036 
03037 
03038 /* Constructs kd-tree from set of feature descriptors */
03039 CVAPI(struct CvFeatureTree*) cvCreateKDTree(CvMat* desc);
03040 
03041 /* Constructs spill-tree from set of feature descriptors */
03042 CVAPI(struct CvFeatureTree*) cvCreateSpillTree( const CvMat* raw_data,
03043                                                const int naive CV_DEFAULT(50),
03044                                                const double rho CV_DEFAULT(.7),
03045                                                const double tau CV_DEFAULT(.1) );
03046 
03047 /* Release feature tree */
03048 CVAPI(void) cvReleaseFeatureTree(struct CvFeatureTree* tr);
03049 
03050 /* Searches feature tree for k nearest neighbors of given reference points,
03051  searching (in case of kd-tree/bbf) at most emax leaves. */
03052 CVAPI(void) cvFindFeatures(struct CvFeatureTree* tr, const CvMat* query_points,
03053                            CvMat* indices, CvMat* dist, int k, int emax CV_DEFAULT(20));
03054 
03055 /* Search feature tree for all points that are inlier to given rect region.
03056  Only implemented for kd trees */
03057 CVAPI(int) cvFindFeaturesBoxed(struct CvFeatureTree* tr,
03058                                CvMat* bounds_min, CvMat* bounds_max,
03059                                CvMat* out_indices);
03060 
03061 
03062 /* Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of
03063  given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. */
03064 CVAPI(struct CvLSH*) cvCreateLSH(struct CvLSHOperations* ops, int d,
03065                                  int L CV_DEFAULT(10), int k CV_DEFAULT(10),
03066                                  int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4),
03067                                  int64 seed CV_DEFAULT(-1));
03068 
03069 /* Construct in-memory LSH table, with n bins. */
03070 CVAPI(struct CvLSH*) cvCreateMemoryLSH(int d, int n, int L CV_DEFAULT(10), int k CV_DEFAULT(10),
03071                                        int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4),
03072                                        int64 seed CV_DEFAULT(-1));
03073 
03074 /* Free the given LSH structure. */
03075 CVAPI(void) cvReleaseLSH(struct CvLSH** lsh);
03076 
03077 /* Return the number of vectors in the LSH. */
03078 CVAPI(unsigned int) LSHSize(struct CvLSH* lsh);
03079 
03080 /* Add vectors to the LSH structure, optionally returning indices. */
03081 CVAPI(void) cvLSHAdd(struct CvLSH* lsh, const CvMat* data, CvMat* indices CV_DEFAULT(0));
03082 
03083 /* Remove vectors from LSH, as addressed by given indices. */
03084 CVAPI(void) cvLSHRemove(struct CvLSH* lsh, const CvMat* indices);
03085 
03086 /* Query the LSH n times for at most k nearest points; data is n x d,
03087  indices and dist are n x k. At most emax stored points will be accessed. */
03088 CVAPI(void) cvLSHQuery(struct CvLSH* lsh, const CvMat* query_points,
03089                        CvMat* indices, CvMat* dist, int k, int emax);
03090 
03091 /* Kolmogorov-Zabin stereo-correspondence algorithm (a.k.a. KZ1) */
03092 #define CV_STEREO_GC_OCCLUDED  SHRT_MAX
03093 
03094 typedef struct CvStereoGCState
03095 {
03096     int Ithreshold;
03097     int interactionRadius;
03098     float K, lambda, lambda1, lambda2;
03099     int occlusionCost;
03100     int minDisparity;
03101     int numberOfDisparities;
03102     int maxIters;
03103 
03104     CvMat* left;
03105     CvMat* right;
03106     CvMat* dispLeft;
03107     CvMat* dispRight;
03108     CvMat* ptrLeft;
03109     CvMat* ptrRight;
03110     CvMat* vtxBuf;
03111     CvMat* edgeBuf;
03112 } CvStereoGCState;
03113 
03114 CVAPI(CvStereoGCState*) cvCreateStereoGCState( int numberOfDisparities, int maxIters );
03115 CVAPI(void) cvReleaseStereoGCState( CvStereoGCState** state );
03116 
03117 CVAPI(void) cvFindStereoCorrespondenceGC( const CvArr* left, const CvArr* right,
03118                                          CvArr* disparityLeft, CvArr* disparityRight,
03119                                          CvStereoGCState* state,
03120                                          int useDisparityGuess CV_DEFAULT(0) );
03121 
03122 /* Calculates optical flow for 2 images using classical Lucas & Kanade algorithm */
03123 CVAPI(void)  cvCalcOpticalFlowLK( const CvArr* prev, const CvArr* curr,
03124                                  CvSize win_size, CvArr* velx, CvArr* vely );
03125 
03126 /* Calculates optical flow for 2 images using block matching algorithm */
03127 CVAPI(void)  cvCalcOpticalFlowBM( const CvArr* prev, const CvArr* curr,
03128                                  CvSize block_size, CvSize shift_size,
03129                                  CvSize max_range, int use_previous,
03130                                  CvArr* velx, CvArr* vely );
03131 
03132 /* Calculates Optical flow for 2 images using Horn & Schunck algorithm */
03133 CVAPI(void)  cvCalcOpticalFlowHS( const CvArr* prev, const CvArr* curr,
03134                                  int use_previous, CvArr* velx, CvArr* vely,
03135                                  double lambda, CvTermCriteria criteria );
03136 
03137 
03138 /****************************************************************************************\
03139 *                           Background/foreground segmentation                           *
03140 \****************************************************************************************/
03141 
03142 /* We discriminate between foreground and background pixels
03143  * by building and maintaining a model of the background.
03144  * Any pixel which does not fit this model is then deemed
03145  * to be foreground.
03146  *
03147  * At present we support two core background models,
03148  * one of which has two variations:
03149  *
03150  *  o CV_BG_MODEL_FGD: latest and greatest algorithm, described in
03151  *
03152  *   Foreground Object Detection from Videos Containing Complex Background.
03153  *   Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian.
03154  *   ACM MM2003 9p
03155  *
03156  *  o CV_BG_MODEL_FGD_SIMPLE:
03157  *       A code comment describes this as a simplified version of the above,
03158  *       but the code is in fact currently identical
03159  *
03160  *  o CV_BG_MODEL_MOG: "Mixture of Gaussians", older algorithm, described in
03161  *
03162  *       Moving target classification and tracking from real-time video.
03163  *       A Lipton, H Fujijoshi, R Patil
03164  *       Proceedings IEEE Workshop on Application of Computer Vision pp 8-14 1998
03165  *
03166  *       Learning patterns of activity using real-time tracking
03167  *       C Stauffer and W Grimson  August 2000
03168  *       IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8):747-757
03169  */
03170 
03171 
03172 #define CV_BG_MODEL_FGD     0
03173 #define CV_BG_MODEL_MOG     1           /* "Mixture of Gaussians".  */
03174 #define CV_BG_MODEL_FGD_SIMPLE  2
03175 
03176 struct CvBGStatModel;
03177 
03178 typedef void (CV_CDECL * CvReleaseBGStatModel)( struct CvBGStatModel** bg_model );
03179 typedef int (CV_CDECL * CvUpdateBGStatModel)( IplImage* curr_frame, struct CvBGStatModel* bg_model,
03180                                              double learningRate );
03181 
03182 #define CV_BG_STAT_MODEL_FIELDS()                                               \
03183 int             type; /*type of BG model*/                                      \
03184 CvReleaseBGStatModel release;                                                   \
03185 CvUpdateBGStatModel update;                                                     \
03186 IplImage*       background;   /*8UC3 reference background image*/               \
03187 IplImage*       foreground;   /*8UC1 foreground image*/                         \
03188 IplImage**      layers;       /*8UC3 reference background image, can be null */ \
03189 int             layer_count;  /* can be zero */                                 \
03190 CvMemStorage*   storage;      /*storage for foreground_regions*/                \
03191 CvSeq*          foreground_regions /*foreground object contours*/
03192 
03193 typedef struct CvBGStatModel
03194 {
03195     CV_BG_STAT_MODEL_FIELDS();
03196 } CvBGStatModel;
03197 
03198 //
03199 
03200 // Releases memory used by BGStatModel
03201 CVAPI(void) cvReleaseBGStatModel( CvBGStatModel** bg_model );
03202 
03203 // Updates statistical model and returns number of found foreground regions
03204 CVAPI(int) cvUpdateBGStatModel( IplImage* current_frame, CvBGStatModel*  bg_model,
03205                                double learningRate CV_DEFAULT(-1));
03206 
03207 // Performs FG post-processing using segmentation
03208 // (all pixels of a region will be classified as foreground if majority of pixels of the region are FG).
03209 // parameters:
03210 //      segments - pointer to result of segmentation (for example MeanShiftSegmentation)
03211 //      bg_model - pointer to CvBGStatModel structure
03212 CVAPI(void) cvRefineForegroundMaskBySegm( CvSeq* segments, CvBGStatModel*  bg_model );
03213 
03214 /* Common use change detection function */
03215 CVAPI(int)  cvChangeDetection( IplImage*  prev_frame,
03216                               IplImage*  curr_frame,
03217                               IplImage*  change_mask );
03218 
03219 /*
03220  Interface of ACM MM2003 algorithm
03221  */
03222 
03223 /* Default parameters of foreground detection algorithm: */
03224 #define  CV_BGFG_FGD_LC              128
03225 #define  CV_BGFG_FGD_N1C             15
03226 #define  CV_BGFG_FGD_N2C             25
03227 
03228 #define  CV_BGFG_FGD_LCC             64
03229 #define  CV_BGFG_FGD_N1CC            25
03230 #define  CV_BGFG_FGD_N2CC            40
03231 
03232 /* Background reference image update parameter: */
03233 #define  CV_BGFG_FGD_ALPHA_1         0.1f
03234 
03235 /* stat model update parameter
03236  * 0.002f ~ 1K frame(~45sec), 0.005 ~ 18sec (if 25fps and absolutely static BG)
03237  */
03238 #define  CV_BGFG_FGD_ALPHA_2         0.005f
03239 
03240 /* start value for alpha parameter (to fast initiate statistic model) */
03241 #define  CV_BGFG_FGD_ALPHA_3         0.1f
03242 
03243 #define  CV_BGFG_FGD_DELTA           2
03244 
03245 #define  CV_BGFG_FGD_T               0.9f
03246 
03247 #define  CV_BGFG_FGD_MINAREA         15.f
03248 
03249 #define  CV_BGFG_FGD_BG_UPDATE_TRESH 0.5f
03250 
03251 /* See the above-referenced Li/Huang/Gu/Tian paper
03252  * for a full description of these background-model
03253  * tuning parameters.
03254  *
03255  * Nomenclature:  'c'  == "color", a three-component red/green/blue vector.
03256  *                         We use histograms of these to model the range of
03257  *                         colors we've seen at a given background pixel.
03258  *
03259  *                'cc' == "color co-occurrence", a six-component vector giving
03260  *                         RGB color for both this frame and preceding frame.
03261  *                             We use histograms of these to model the range of
03262  *                         color CHANGES we've seen at a given background pixel.
03263  */
03264 typedef struct CvFGDStatModelParams
03265 {
03266     int    Lc;          /* Quantized levels per 'color' component. Power of two, typically 32, 64 or 128.               */
03267     int    N1c;         /* Number of color vectors used to model normal background color variation at a given pixel.            */
03268     int    N2c;         /* Number of color vectors retained at given pixel.  Must be > N1c, typically ~ 5/3 of N1c.         */
03269     /* Used to allow the first N1c vectors to adapt over time to changing background.               */
03270 
03271     int    Lcc;         /* Quantized levels per 'color co-occurrence' component.  Power of two, typically 16, 32 or 64.         */
03272     int    N1cc;        /* Number of color co-occurrence vectors used to model normal background color variation at a given pixel.  */
03273     int    N2cc;        /* Number of color co-occurrence vectors retained at given pixel.  Must be > N1cc, typically ~ 5/3 of N1cc. */
03274     /* Used to allow the first N1cc vectors to adapt over time to changing background.              */
03275 
03276     int    is_obj_without_holes;/* If TRUE we ignore holes within foreground blobs. Defaults to TRUE.                       */
03277     int    perform_morphing;    /* Number of erode-dilate-erode foreground-blob cleanup iterations.                     */
03278     /* These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1.            */
03279 
03280     float  alpha1;      /* How quickly we forget old background pixel values seen.  Typically set to 0.1                */
03281     float  alpha2;      /* "Controls speed of feature learning". Depends on T. Typical value circa 0.005.               */
03282     float  alpha3;      /* Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1.             */
03283 
03284     float  delta;       /* Affects color and color co-occurrence quantization, typically set to 2.                  */
03285     float  T;           /* "A percentage value which determines when new features can be recognized as new background." (Typically 0.9).*/
03286     float  minArea;     /* Discard foreground blobs whose bounding box is smaller than this threshold.                  */
03287 } CvFGDStatModelParams;
03288 
03289 typedef struct CvBGPixelCStatTable
03290 {
03291     float          Pv, Pvb;
03292     uchar          v[3];
03293 } CvBGPixelCStatTable;
03294 
03295 typedef struct CvBGPixelCCStatTable
03296 {
03297     float          Pv, Pvb;
03298     uchar          v[6];
03299 } CvBGPixelCCStatTable;
03300 
03301 typedef struct CvBGPixelStat
03302 {
03303     float                 Pbc;
03304     float                 Pbcc;
03305     CvBGPixelCStatTable*  ctable;
03306     CvBGPixelCCStatTable* cctable;
03307     uchar                 is_trained_st_model;
03308     uchar                 is_trained_dyn_model;
03309 } CvBGPixelStat;
03310 
03311 
03312 typedef struct CvFGDStatModel
03313 {
03314     CV_BG_STAT_MODEL_FIELDS();
03315     CvBGPixelStat*         pixel_stat;
03316     IplImage*              Ftd;
03317     IplImage*              Fbd;
03318     IplImage*              prev_frame;
03319     CvFGDStatModelParams   params;
03320 } CvFGDStatModel;
03321 
03322 /* Creates FGD model */
03323 CVAPI(CvBGStatModel*) cvCreateFGDStatModel( IplImage* first_frame,
03324                                            CvFGDStatModelParams* parameters CV_DEFAULT(NULL));
03325 
03326 /*
03327  Interface of Gaussian mixture algorithm
03328 
03329  "An improved adaptive background mixture model for real-time tracking with shadow detection"
03330  P. KadewTraKuPong and R. Bowden,
03331  Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."
03332  http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
03333  */
03334 
03335 /* Note:  "MOG" == "Mixture Of Gaussians": */
03336 
03337 #define CV_BGFG_MOG_MAX_NGAUSSIANS 500
03338 
03339 /* default parameters of gaussian background detection algorithm */
03340 #define CV_BGFG_MOG_BACKGROUND_THRESHOLD     0.7     /* threshold sum of weights for background test */
03341 #define CV_BGFG_MOG_STD_THRESHOLD            2.5     /* lambda=2.5 is 99% */
03342 #define CV_BGFG_MOG_WINDOW_SIZE              200     /* Learning rate; alpha = 1/CV_GBG_WINDOW_SIZE */
03343 #define CV_BGFG_MOG_NGAUSSIANS               5       /* = K = number of Gaussians in mixture */
03344 #define CV_BGFG_MOG_WEIGHT_INIT              0.05
03345 #define CV_BGFG_MOG_SIGMA_INIT               30
03346 #define CV_BGFG_MOG_MINAREA                  15.f
03347 
03348 
03349 #define CV_BGFG_MOG_NCOLORS                  3
03350 
03351 typedef struct CvGaussBGStatModelParams
03352 {
03353     int     win_size;               /* = 1/alpha */
03354     int     n_gauss;
03355     double  bg_threshold, std_threshold, minArea;
03356     double  weight_init, variance_init;
03357 }CvGaussBGStatModelParams;
03358 
03359 typedef struct CvGaussBGValues
03360 {
03361     int         match_sum;
03362     double      weight;
03363     double      variance[CV_BGFG_MOG_NCOLORS];
03364     double      mean[CV_BGFG_MOG_NCOLORS];
03365 } CvGaussBGValues;
03366 
03367 typedef struct CvGaussBGPoint
03368 {
03369     CvGaussBGValues* g_values;
03370 } CvGaussBGPoint;
03371 
03372 
03373 typedef struct CvGaussBGModel
03374 {
03375     CV_BG_STAT_MODEL_FIELDS();
03376     CvGaussBGStatModelParams   params;
03377     CvGaussBGPoint*            g_point;
03378     int                        countFrames;
03379     void*                      mog;
03380 } CvGaussBGModel;
03381 
03382 
03383 /* Creates Gaussian mixture background model */
03384 CVAPI(CvBGStatModel*) cvCreateGaussianBGModel( IplImage* first_frame,
03385                                               CvGaussBGStatModelParams* parameters CV_DEFAULT(NULL));
03386 
03387 
03388 typedef struct CvBGCodeBookElem
03389 {
03390     struct CvBGCodeBookElem* next;
03391     int tLastUpdate;
03392     int stale;
03393     uchar boxMin[3];
03394     uchar boxMax[3];
03395     uchar learnMin[3];
03396     uchar learnMax[3];
03397 } CvBGCodeBookElem;
03398 
03399 typedef struct CvBGCodeBookModel
03400 {
03401     CvSize size;
03402     int t;
03403     uchar cbBounds[3];
03404     uchar modMin[3];
03405     uchar modMax[3];
03406     CvBGCodeBookElem** cbmap;
03407     CvMemStorage* storage;
03408     CvBGCodeBookElem* freeList;
03409 } CvBGCodeBookModel;
03410 
03411 CVAPI(CvBGCodeBookModel*) cvCreateBGCodeBookModel( void );
03412 CVAPI(void) cvReleaseBGCodeBookModel( CvBGCodeBookModel** model );
03413 
03414 CVAPI(void) cvBGCodeBookUpdate( CvBGCodeBookModel* model, const CvArr* image,
03415                                CvRect roi CV_DEFAULT(cvRect(0,0,0,0)),
03416                                const CvArr* mask CV_DEFAULT(0) );
03417 
03418 CVAPI(int) cvBGCodeBookDiff( const CvBGCodeBookModel* model, const CvArr* image,
03419                             CvArr* fgmask, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)) );
03420 
03421 CVAPI(void) cvBGCodeBookClearStale( CvBGCodeBookModel* model, int staleThresh,
03422                                    CvRect roi CV_DEFAULT(cvRect(0,0,0,0)),
03423                                    const CvArr* mask CV_DEFAULT(0) );
03424 
03425 CVAPI(CvSeq*) cvSegmentFGMask( CvArr *fgmask, int poly1Hull0 CV_DEFAULT(1),
03426                               float perimScale CV_DEFAULT(4.f),
03427                               CvMemStorage* storage CV_DEFAULT(0),
03428                               CvPoint offset CV_DEFAULT(cvPoint(0,0)));
03429 
03430 #ifdef __cplusplus
03431 }
03432 #endif
03433 
03434 #endif
03435 
03436 /* End of file. */