]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cv_motion_tracking.tex
Fixed ~100 argument name mismatches
[opencv.git] / opencv / doc / cv_motion_tracking.tex
1 \section{Motion Analysis and Object Tracking}
2
3 \ifCPy
4
5 \cvCPyFunc{Acc}
6 Adds a frame to an accumulator.
7
8 \cvdefC{
9 void cvAcc( \par const CvArr* image,\par CvArr* sum,\par const CvArr* mask=NULL );
10 }
11 \cvdefPy{Acc(image,sum,mask=NULL)-> None}
12
13 \begin{description}
14 \cvarg{image}{Input image, 1- or 3-channel, 8-bit or 32-bit floating point. (each channel of multi-channel image is processed independently)}
15 \cvarg{sum}{Accumulator with the same number of channels as input image, 32-bit or 64-bit floating-point}
16 \cvarg{mask}{Optional operation mask}
17 \end{description}
18
19 The function adds the whole image \texttt{image} or its selected region to the accumulator \texttt{sum}:
20
21 \[ \texttt{sum}(x,y) \leftarrow \texttt{sum}(x,y) + \texttt{image}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
22
23 \cvCPyFunc{CalcGlobalOrientation}
24 Calculates the global motion orientation of some selected region.
25
26 \cvdefC{
27 double cvCalcGlobalOrientation( \par const CvArr* orientation,\par const CvArr* mask,\par const CvArr* mhi,\par double timestamp,\par double duration );
28 }\cvdefPy{CalcGlobalOrientation(orientation,mask,mhi,timestamp,duration)-> float}
29
30 \begin{description}
31 \cvarg{orientation}{Motion gradient orientation image; calculated by the function \cvCPyCross{CalcMotionGradient}}
32 \cvarg{mask}{Mask image. It may be a conjunction of a valid gradient mask, obtained with \cvCPyCross{CalcMotionGradient} and the mask of the region, whose direction needs to be calculated}
33 \cvarg{mhi}{Motion history image}
34 \cvarg{timestamp}{Current time in milliseconds or other units, it is better to store time passed to \cvCPyCross{UpdateMotionHistory} before and reuse it here, because running \cvCPyCross{UpdateMotionHistory} and \cvCPyCross{CalcMotionGradient} on large images may take some time}
35 \cvarg{duration}{Maximal duration of motion track in milliseconds, the same as \cvCPyCross{UpdateMotionHistory}}
36 \end{description}
37
38 The function calculates the general
39 motion direction in the selected region and returns the angle between
40 0 degrees  and 360 degrees . At first the function builds the orientation histogram
41 and finds the basic orientation as a coordinate of the histogram
42 maximum. After that the function calculates the shift relative to the
43 basic orientation as a weighted sum of all of the orientation vectors: the more
44 recent the motion, the greater the weight. The resultant angle is
45 a circular sum of the basic orientation and the shift.
46
47 \cvCPyFunc{CalcMotionGradient}
48 Calculates the gradient orientation of a motion history image.
49
50 \cvdefC{
51 void cvCalcMotionGradient( \par const CvArr* mhi,\par CvArr* mask,\par CvArr* orientation,\par double delta1,\par double delta2,\par int apertureSize=3 );
52 }\cvdefPy{CalcMotionGradient(mhi,mask,orientation,delta1,delta2,apertureSize=3)-> None}
53
54 \begin{description}
55 \cvarg{mhi}{Motion history image}
56 \cvarg{mask}{Mask image; marks pixels where the motion gradient data is correct; output parameter}
57 \cvarg{orientation}{Motion gradient orientation image; contains angles from 0 to ~360 degrees }
58 \cvarg{delta1}{See below}
59 \cvarg{delta2}{See below}
60 \cvarg{apertureSize}{Aperture size of derivative operators used by the function: CV\_SCHARR, 1, 3, 5 or 7 (see \cvCPyCross{Sobel})}
61 \end{description}
62
63 The function calculates the derivatives $Dx$ and $Dy$ of \texttt{mhi} and then calculates gradient orientation as:
64
65 \[
66 \texttt{orientation}(x,y)=\arctan{\frac{Dy(x,y)}{Dx(x,y)}}
67 \]
68
69 where both $Dx(x,y)$ and $Dy(x,y)$ signs are taken into account (as in the \cvCPyCross{CartToPolar} function). After that \texttt{mask} is filled to indicate where the orientation is valid (see the \texttt{delta1} and \texttt{delta2} description).
70
71 The function finds the minimum ($m(x,y)$) and maximum ($M(x,y)$) mhi values over each pixel $(x,y)$ neighborhood and assumes the gradient is valid only if
72 \[
73 \min(\texttt{delta1} , \texttt{delta2} ) \le M(x,y)-m(x,y) \le \max(\texttt{delta1} ,\texttt{delta2} ).
74 \]}
75
76 \cvCPyFunc{CalcOpticalFlowBM}
77 Calculates the optical flow for two images by using the block matching method.
78
79 \cvdefC{
80 void cvCalcOpticalFlowBM( \par const CvArr* prev,\par const CvArr* curr,\par CvSize blockSize,\par CvSize shiftSize,\par CvSize max\_range,\par int usePrevious,\par CvArr* velx,\par CvArr* vely );
81 }\cvdefPy{CalcOpticalFlowBM(prev,curr,blockSize,shiftSize,max\_range,usePrevious,velx,vely)-> None}
82
83 \begin{description}
84 \cvarg{prev}{First image, 8-bit, single-channel}
85 \cvarg{curr}{Second image, 8-bit, single-channel}
86 \cvarg{blockSize}{Size of basic blocks that are compared}
87 \cvarg{shiftSize}{Block coordinate increments}
88 \cvarg{max\_range}{Size of the scanned neighborhood in pixels around the block}
89 \cvarg{usePrevious}{Uses the previous (input) velocity field}
90 \cvarg{velx}{Horizontal component of the optical flow of
91 \[
92 \left\lfloor \frac{\texttt{prev->width} - \texttt{blockSize.width}}{\texttt{shiftSize.width}} \right\rfloor
93 \times
94 \left\lfloor \frac{\texttt{prev->height} - \texttt{blockSize.height}}{\texttt{shiftSize.height}} \right\rfloor
95 \]
96 size, 32-bit floating-point, single-channel}
97 \cvarg{vely}{Vertical component of the optical flow of the same size \texttt{velx}, 32-bit floating-point, single-channel}
98 \end{description}
99
100 The function calculates the optical
101 flow for overlapped blocks $\texttt{blockSize.width} \times \texttt{blockSize.height}$ pixels each, thus the velocity
102 fields are smaller than the original images. For every block in \texttt{prev} the functions tries to find a similar block in
103 \texttt{curr} in some neighborhood of the original block or shifted by (velx(x0,y0),vely(x0,y0)) block as has been calculated by previous
104 function call (if \texttt{usePrevious=1})
105
106 \cvCPyFunc{CalcOpticalFlowHS}
107 Calculates the optical flow for two images.
108
109 \cvdefC{
110 void cvCalcOpticalFlowHS( \par const CvArr* prev,\par const CvArr* curr,\par int usePrevious,\par CvArr* velx,\par CvArr* vely,\par double lambda,\par CvTermCriteria criteria );
111 }\cvdefPy{CalcOpticalFlowHS(prev,curr,usePrevious,velx,vely,lambda,criteria)-> None}
112
113 \begin{description}
114 \cvarg{prev}{First image, 8-bit, single-channel}
115 \cvarg{curr}{Second image, 8-bit, single-channel}
116 \cvarg{usePrevious}{Uses the previous (input) velocity field}
117 \cvarg{velx}{Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel}
118 \cvarg{vely}{Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel}
119 \cvarg{lambda}{Lagrangian multiplier}
120 \cvarg{criteria}{Criteria of termination of velocity computing}
121 \end{description}
122
123 The function computes the flow for every pixel of the first input image using the Horn and Schunck algorithm
124 \cvCPyCross{Horn81}.
125
126 \cvCPyFunc{CalcOpticalFlowLK}
127 Calculates the optical flow for two images.
128
129 \cvdefC{
130 void cvCalcOpticalFlowLK( \par const CvArr* prev,\par const CvArr* curr,\par CvSize winSize,\par CvArr* velx,\par CvArr* vely );
131 }\cvdefPy{CalcOpticalFlowLK(prev,curr,winSize,velx,vely)-> None}
132 \begin{description}
133
134 \cvarg{prev}{First image, 8-bit, single-channel}
135 \cvarg{curr}{Second image, 8-bit, single-channel}
136 \cvarg{winSize}{Size of the averaging window used for grouping pixels}
137 \cvarg{velx}{Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel}
138 \cvarg{vely}{Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel}
139 \end{description}
140
141 The function computes the flow for every pixel of the first input image using the Lucas and Kanade algorithm
142 \cvCPyCross{Lucas81}.
143
144 \cvCPyFunc{CalcOpticalFlowPyrLK}
145 Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids.
146
147 \cvdefC{
148 void cvCalcOpticalFlowPyrLK( \par const CvArr* prev,\par const CvArr* curr,\par CvArr* prevPyr,\par CvArr* currPyr,\par const CvPoint2D32f* prevFeatures,\par CvPoint2D32f* currFeatures,\par int count,\par CvSize winSize,\par int level,\par char* status,\par float* track\_error,\par CvTermCriteria criteria,\par int flags );
149 }
150 \cvdefPy{
151 CalcOpticalFlowPyrLK(  prev, curr, prevPyr, currPyr, prevFeatures, winSize, level, criteria, flags, guesses = None) -> (currFeatures, status, track\_error)
152 }
153
154 \begin{description}
155 \cvarg{prev}{First frame, at time \texttt{t}}
156 \cvarg{curr}{Second frame, at time \texttt{t + dt} }
157 \cvarg{prevPyr}{Buffer for the pyramid for the first frame. If the pointer is not \texttt{NULL} , the buffer must have a sufficient size to store the pyramid from level \texttt{1} to level \texttt{level} ; the total size of \texttt{(image\_width+8)*image\_height/3} bytes is sufficient}
158 \cvarg{currPyr}{Similar to \texttt{prevPyr}, used for the second frame}
159 \cvarg{prevFeatures}{Array of points for which the flow needs to be found}
160 \cvarg{currFeatures}{Array of 2D points containing the calculated new positions of the input features in the second image}
161 \ifC
162 \cvarg{count}{Number of feature points}
163 \fi
164 \cvarg{winSize}{Size of the search window of each pyramid level}
165 \cvarg{level}{Maximal pyramid level number. If \texttt{0} , pyramids are not used (single level), if \texttt{1} , two levels are used, etc}
166 \cvarg{status}{Array. Every element of the array is set to \texttt{1} if the flow for the corresponding feature has been found, \texttt{0} otherwise}
167 \cvarg{track\_error}{Array of double numbers containing the difference between patches around the original and moved points. Optional parameter; can be \texttt{NULL }}
168 \cvarg{criteria}{Specifies when the iteration process of finding the flow for each point on each pyramid level should be stopped}
169 \cvarg{flags}{Miscellaneous flags:
170 \begin{description}
171   \cvarg{CV\_LKFLOWPyr\_A\_READY}{pyramid for the first frame is precalculated before the call}
172   \cvarg{CV\_LKFLOWPyr\_B\_READY}{ pyramid for the second frame is precalculated before the call}
173   \cvC{\cvarg{CV\_LKFLOW\_INITIAL\_GUESSES}{array B contains initial coordinates of features before the function call}}
174 \end{description}}
175 \cvPy{\cvarg{guesses}{optional array of estimated coordinates of features in second frame, with same length as \texttt{prevFeatures}}}
176 \end{description}
177
178 The function implements the sparse iterative version of the Lucas-Kanade optical flow in pyramids
179 \cvCPyCross{Bouguet00}
180 . It calculates the coordinates of the feature points on the current video
181 frame given their coordinates on the previous frame. The function finds
182 the coordinates with sub-pixel accuracy.
183
184 Both parameters \texttt{prevPyr} and \texttt{currPyr} comply with the
185 following rules: if the image pointer is 0, the function allocates the
186 buffer internally, calculates the pyramid, and releases the buffer after
187 processing. Otherwise, the function calculates the pyramid and stores
188 it in the buffer unless the flag \texttt{CV\_LKFLOWPyr\_A[B]\_READY}
189 is set. The image should be large enough to fit the Gaussian pyramid
190 data. After the function call both pyramids are calculated and the
191 readiness flag for the corresponding image can be set in the next call
192 (i.e., typically, for all the image pairs except the very first one
193 \texttt{CV\_LKFLOWPyr\_A\_READY} is set).
194
195
196 \cvCPyFunc{CamShift}
197 Finds the object center, size, and orientation.
198
199 \cvdefC{
200 int cvCamShift( \par const CvArr* prob\_image,\par CvRect window,\par CvTermCriteria criteria,\par CvConnectedComp* comp,\par CvBox2D* box=NULL );
201 }\cvdefPy{CamShift(prob\_image,window,criteria,box=NULL)-> comp}
202
203 \begin{description}
204 \cvarg{prob\_image}{Back projection of object histogram (see \cvCPyCross{CalcBackProject})}
205 \cvarg{window}{Initial search window}
206 \cvarg{criteria}{Criteria applied to determine when the window search should be finished}
207 \cvarg{comp}{Resultant structure that contains the converged search window coordinates (\texttt{comp->rect} field) and the sum of all of the pixels inside the window (\texttt{comp->area} field)}
208 \cvarg{box}{Circumscribed box for the object. If not \texttt{NULL}, it contains object size and orientation}
209 \end{description}
210
211 The function implements the CAMSHIFT object tracking algrorithm
212 \cvCPyCross{Bradski98}.
213 First, it finds an object center using \cvCPyCross{MeanShift} and, after that, calculates the object size and orientation. The function returns number of iterations made within \cvCPyCross{MeanShift}.
214
215 The \cvCPyCross{CvCamShiftTracker} class declared in cv.hpp implements the color object tracker that uses the function.
216
217 \ifC % {
218 \subsection{CvConDensation}
219 ConDenstation state.
220
221 \begin{lstlisting}
222     typedef struct CvConDensation
223     {
224         int MP;     //Dimension of measurement vector
225         int DP;     // Dimension of state vector
226         float* DynamMatr;       // Matrix of the linear Dynamics system
227         float* State;           // Vector of State
228         int SamplesNum;         // Number of the Samples
229         float** flSamples;      // array of the Sample Vectors
230         float** flNewSamples;   // temporary array of the Sample Vectors
231         float* flConfidence;    // Confidence for each Sample
232         float* flCumulative;    // Cumulative confidence
233         float* Temp;            // Temporary vector
234         float* RandomSample;    // RandomVector to update sample set
235         CvRandState* RandS;     // Array of structures to generate random vectors
236     } CvConDensation;
237
238 \end{lstlisting}
239 The structure \texttt{CvConDensation} stores the CONditional DENSity propagATION tracker state. The information about the algorithm can be found at \url{http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/ISARD1/condensation.html}.
240
241 \cvCPyFunc{CreateConDensation}
242 Allocates the ConDensation filter structure.
243
244 \cvdefC{
245 CvConDensation* cvCreateConDensation( \par int dynam\_params,\par int measure\_params,\par int sample\_count );
246 }
247
248 \begin{description}
249 \cvarg{dynam\_params}{Dimension of the state vector}
250 \cvarg{measure\_params}{Dimension of the measurement vector}
251 \cvarg{sample\_count}{Number of samples}
252 \end{description}
253
254 The function creates a \texttt{CvConDensation} structure and returns a pointer to the structure.
255
256 \cvCPyFunc{ConDensInitSampleSet}
257 Initializes the sample set for the ConDensation algorithm.
258
259 \cvdefC{
260 void cvConDensInitSampleSet( CvConDensation* condens, \par CvMat* lower\_bound, \par CvMat* upper\_bound );
261 }
262
263 \begin{description}
264 \cvarg{condens}{Pointer to a structure to be initialized}
265 \cvarg{lower\_bound}{Vector of the lower boundary for each dimension}
266 \cvarg{upper\_bound}{Vector of the upper boundary for each dimension}
267 \end{description}
268
269 The function fills the samples arrays in the structure \cvCPyCross{CvConDensation} with values within the specified ranges.
270 \fi
271
272 \cvfunc{CvKalman}\label{CvKalman}
273 Kalman filter state.
274
275 \begin{lstlisting}
276 typedef struct CvKalman
277 {
278     int MP;                     /* number of measurement vector dimensions */
279     int DP;                     /* number of state vector dimensions */
280     int CP;                     /* number of control vector dimensions */
281
282     /* backward compatibility fields */
283 #if 1
284     float* PosterState;         /* =state_pre->data.fl */
285     float* PriorState;          /* =state_post->data.fl */
286     float* DynamMatr;           /* =transition_matrix->data.fl */
287     float* MeasurementMatr;     /* =measurement_matrix->data.fl */
288     float* MNCovariance;        /* =measurement_noise_cov->data.fl */
289     float* PNCovariance;        /* =process_noise_cov->data.fl */
290     float* KalmGainMatr;        /* =gain->data.fl */
291     float* PriorErrorCovariance;/* =error_cov_pre->data.fl */
292     float* PosterErrorCovariance;/* =error_cov_post->data.fl */
293     float* Temp1;               /* temp1->data.fl */
294     float* Temp2;               /* temp2->data.fl */
295 #endif
296
297     CvMat* state_pre;           /* predicted state (x'(k)):
298                                     x(k)=A*x(k-1)+B*u(k) */
299     CvMat* state_post;          /* corrected state (x(k)):
300                                     x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) */
301     CvMat* transition_matrix;   /* state transition matrix (A) */
302     CvMat* control_matrix;      /* control matrix (B)
303                                    (it is not used if there is no control)*/
304     CvMat* measurement_matrix;  /* measurement matrix (H) */
305     CvMat* process_noise_cov;   /* process noise covariance matrix (Q) */
306     CvMat* measurement_noise_cov; /* measurement noise covariance matrix (R) */
307     CvMat* error_cov_pre;       /* priori error estimate covariance matrix (P'(k)):
308                                     P'(k)=A*P(k-1)*At + Q*/
309     CvMat* gain;                /* Kalman gain matrix (K(k)):
310                                     K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)*/
311     CvMat* error_cov_post;      /* posteriori error estimate covariance matrix (P(k)):
312                                     P(k)=(I-K(k)*H)*P'(k) */
313     CvMat* temp1;               /* temporary matrices */
314     CvMat* temp2;
315     CvMat* temp3;
316     CvMat* temp4;
317     CvMat* temp5;
318 }
319 CvKalman;
320 \end{lstlisting}
321
322 The structure \texttt{CvKalman} is used to keep the Kalman filter
323 state. It is created by the \cvCPyCross{CreateKalman} function, updated
324 by the \cvCPyCross{KalmanPredict} and \cvCPyCross{KalmanCorrect} functions
325 and released by the \cvCPyCross{ReleaseKalman} function. Normally, the
326 structure is used for the standard Kalman filter (notation and the
327 formulas below are borrowed from the excellent Kalman tutorial
328 \cite{Welch95})
329
330 \[
331 \begin{array}{l}
332 x_k=A \cdot x_{k-1}+B \cdot u_k+w_k\\
333 z_k=H \cdot x_k+v_k
334 \end{array}
335 \]
336
337 where:
338
339 \[
340 \begin{array}{l l}
341 x_k\;(x_{k-1})& \text{state of the system at the moment \emph{k} (\emph{k-1})}\\
342 z_k & \text{measurement of the system state at the moment \emph{k}}\\
343 u_k & \text{external control applied at the moment \emph{k}}
344 \end{array}
345 \]
346
347 $w_k$ and $v_k$ are normally-distributed process and measurement noise, respectively:
348
349 \[
350 \begin{array}{l}
351 p(w) \sim N(0,Q)\\
352 p(v) \sim N(0,R)
353 \end{array}
354 \]
355
356 that is,
357
358 $Q$ process noise covariance matrix, constant or variable,
359
360 $R$ measurement noise covariance matrix, constant or variable
361
362 In the case of the standard Kalman filter, all of the matrices: A, B, H, Q and R are initialized once after the \cvCPyCross{CvKalman} structure is allocated via \cvCPyCross{CreateKalman}. However, the same structure and the same functions may be used to simulate the extended Kalman filter by linearizing the extended Kalman filter equation in the current system state neighborhood, in this case A, B, H (and, probably, Q and R) should be updated on every step.
363
364 \cvCPyFunc{CreateKalman}
365 Allocates the Kalman filter structure.
366
367 \cvdefC{
368 CvKalman* cvCreateKalman( \par int dynam\_params,\par int measure\_params,\par int control\_params=0 );
369 }
370
371 \cvdefPy{
372 CreateKalman(dynam\_params, measure\_params, control\_params=0) -> CvKalman
373 }
374
375 \begin{description}
376 \cvarg{dynam\_params}{dimensionality of the state vector}
377 \cvarg{measure\_params}{dimensionality of the measurement vector}
378 \cvarg{control\_params}{dimensionality of the control vector}
379 \end{description}
380
381 The function allocates \cvCPyCross{CvKalman} and all its matrices and initializes them somehow.
382
383
384 \cvCPyFunc{KalmanCorrect}
385 Adjusts the model state.
386
387 \cvdefC{
388 const CvMat* cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement );
389 }
390 \cvdefPy{
391 KalmanCorrect(kalman, measurement) -> cvmat
392 }
393
394 \begin{lstlisting}
395 #define cvKalmanUpdateByMeasurement cvKalmanCorrect
396 \end{lstlisting}
397
398 \begin{description}
399 \ifC
400 \cvarg{kalman}{Pointer to the structure to be updated}
401 \else
402 \cvarg{kalman}{Kalman filter object returned by \cvCPyCross{CreateKalman}}
403 \fi
404 \cvarg{measurement}{CvMat containing the measurement vector}
405 \end{description}
406
407 The function adjusts the stochastic model state on the basis of the given measurement of the model state:
408
409 \[
410 \begin{array}{l}
411 K_k=P'_k \cdot H^T \cdot (H \cdot P'_k \cdot H^T+R)^{-1}\\
412 x_k=x'_k+K_k \cdot (z_k-H \cdot x'_k)\\
413 P_k=(I-K_k \cdot H) \cdot P'_k
414 \end{array}
415 \]
416
417 where
418
419 \begin{tabular}{l p{4 in}}
420 $z_k$ & given measurement (\texttt{mesurement} parameter)\\
421 $K_k$ & Kalman "gain" matrix.
422 \end{tabular}
423
424 The function stores the adjusted state at \texttt{kalman->state\_post} and returns it on output.
425
426 \ifC
427 Example. Using Kalman filter to track a rotating point
428 \begin{lstlisting}
429 #include "cv.h"
430 #include "highgui.h"
431 #include <math.h>
432
433 int main(int argc, char** argv)
434 {
435     /* A matrix data */
436     const float A[] = { 1, 1, 0, 1 };
437
438     IplImage* img = cvCreateImage( cvSize(500,500), 8, 3 );
439     CvKalman* kalman = cvCreateKalman( 2, 1, 0 );
440     /* state is (phi, delta_phi) - angle and angle increment */
441     CvMat* state = cvCreateMat( 2, 1, CV_32FC1 );
442     CvMat* process_noise = cvCreateMat( 2, 1, CV_32FC1 );
443     /* only phi (angle) is measured */
444     CvMat* measurement = cvCreateMat( 1, 1, CV_32FC1 );
445     CvRandState rng;
446     int code = -1;
447
448     cvRandInit( &rng, 0, 1, -1, CV_RAND_UNI );
449
450     cvZero( measurement );
451     cvNamedWindow( "Kalman", 1 );
452
453     for(;;)
454     {
455         cvRandSetRange( &rng, 0, 0.1, 0 );
456         rng.disttype = CV_RAND_NORMAL;
457
458         cvRand( &rng, state );
459
460         memcpy( kalman->transition_matrix->data.fl, A, sizeof(A));
461         cvSetIdentity( kalman->measurement_matrix, cvRealScalar(1) );
462         cvSetIdentity( kalman->process_noise_cov, cvRealScalar(1e-5) );
463         cvSetIdentity( kalman->measurement_noise_cov, cvRealScalar(1e-1) );
464         cvSetIdentity( kalman->error_cov_post, cvRealScalar(1));
465         /* choose random initial state */
466         cvRand( &rng, kalman->state_post );
467
468         rng.disttype = CV_RAND_NORMAL;
469
470         for(;;)
471         {
472             #define calc_point(angle)                                      \
473                 cvPoint( cvRound(img->width/2 + img->width/3*cos(angle)),  \
474                          cvRound(img->height/2 - img->width/3*sin(angle)))
475
476             float state_angle = state->data.fl[0];
477             CvPoint state_pt = calc_point(state_angle);
478
479             /* predict point position */
480             const CvMat* prediction = cvKalmanPredict( kalman, 0 );
481             float predict_angle = prediction->data.fl[0];
482             CvPoint predict_pt = calc_point(predict_angle);
483             float measurement_angle;
484             CvPoint measurement_pt;
485
486             cvRandSetRange( &rng,
487                             0,
488                             sqrt(kalman->measurement_noise_cov->data.fl[0]),
489                             0 );
490             cvRand( &rng, measurement );
491
492             /* generate measurement */
493             cvMatMulAdd( kalman->measurement_matrix, state, measurement, measurement );
494
495             measurement_angle = measurement->data.fl[0];
496             measurement_pt = calc_point(measurement_angle);
497
498             /* plot points */
499             #define draw_cross( center, color, d )                        \
500                 cvLine( img, cvPoint( center.x - d, center.y - d ),       \
501                              cvPoint( center.x + d, center.y + d ),       \
502                              color, 1, 0 );                               \
503                 cvLine( img, cvPoint( center.x + d, center.y - d ),       \
504                              cvPoint( center.x - d, center.y + d ),       \
505                              color, 1, 0 )
506
507             cvZero( img );
508             draw_cross( state_pt, CV_RGB(255,255,255), 3 );
509             draw_cross( measurement_pt, CV_RGB(255,0,0), 3 );
510             draw_cross( predict_pt, CV_RGB(0,255,0), 3 );
511             cvLine( img, state_pt, predict_pt, CV_RGB(255,255,0), 3, 0 );
512
513             /* adjust Kalman filter state */
514             cvKalmanCorrect( kalman, measurement );
515
516             cvRandSetRange( &rng,
517                             0,
518                             sqrt(kalman->process_noise_cov->data.fl[0]),
519                             0 );
520             cvRand( &rng, process_noise );
521             cvMatMulAdd( kalman->transition_matrix,
522                          state,
523                          process_noise,
524                          state );
525
526             cvShowImage( "Kalman", img );
527             code = cvWaitKey( 100 );
528
529             if( code > 0 ) /* break current simulation by pressing a key */
530                 break;
531         }
532         if( code == 27 ) /* exit by ESCAPE */
533             break;
534     }
535
536     return 0;
537 }
538 \end{lstlisting}
539 \fi
540
541 \cvCPyFunc{KalmanPredict}
542 Estimates the subsequent model state.
543
544 \cvdefC{
545 const CvMat* cvKalmanPredict( \par CvKalman* kalman, \par const CvMat* control=NULL );
546 }
547 \cvdefPy{
548 KalmanPredict(kalman, control=None) -> cvmat
549 }
550 \begin{lstlisting}
551 #define cvKalmanUpdateByTime cvKalmanPredict
552 \end{lstlisting}
553
554 \begin{description}
555 \ifC
556 \cvarg{kalman}{Kalman filter state}
557 \else
558 \cvarg{kalman}{Kalman filter object returned by \cvCPyCross{CreateKalman}}
559 \fi
560 \cvarg{control}{Control vector $u_k$, should be NULL iff there is no external control (\texttt{control\_params} =0)}
561 \end{description}
562
563 The function estimates the subsequent stochastic model state by its current state and stores it at \texttt{kalman->state\_pre}:
564
565 \[
566 \begin{array}{l}
567 x'_k=A \cdot x_{k-1}+B \cdot u_k\\
568 P'_k=A \cdot P_{k-1}+A^T + Q
569 \end{array}
570 \]
571
572 where
573
574 \begin{tabular}{l p{5 in}}
575 $x'_k$ & is predicted state \texttt{kalman->state\_pre},\\
576 $x_{k-1}$ & is corrected state on the previous step \texttt{kalman->state\_post}
577                 (should be initialized somehow in the beginning, zero vector by default),\\
578 $u_k$ & is external control (\texttt{control} parameter),\\
579 $P'_k$ & is priori error covariance matrix \texttt{kalman->error\_cov\_pre}\\
580 $P_{k-1}$ & is posteriori error covariance matrix on the previous step \texttt{kalman->error\_cov\_post}
581                 (should be initialized somehow in the beginning, identity matrix by default),
582 \end{tabular}
583
584 The function returns the estimated state.
585
586 \cvCPyFunc{MeanShift}
587 Finds the object center on back projection.
588
589 \cvdefC{
590 int cvMeanShift( \par const CvArr* prob\_image,\par CvRect window,\par CvTermCriteria criteria,\par CvConnectedComp* comp );
591 }\cvdefPy{MeanShift(prob\_image,window,criteria)-> comp}
592
593 \begin{description}
594 \cvarg{prob\_image}{Back projection of the object histogram (see \cvCPyCross{CalcBackProject})}
595 \cvarg{window}{Initial search window}
596 \cvarg{criteria}{Criteria applied to determine when the window search should be finished}
597 \cvarg{comp}{Resultant structure that contains the converged search window coordinates (\texttt{comp->rect} field) and the sum of all of the pixels inside the window (\texttt{comp->area} field)}
598 \end{description}
599
600 The function iterates to find the object center
601 given its back projection and initial position of search window. The
602 iterations are made until the search window center moves by less than
603 the given value and/or until the function has done the maximum number
604 of iterations. The function returns the number of iterations made.
605
606 \cvCPyFunc{MultiplyAcc}
607 Adds the product of two input images to the accumulator.
608
609 \cvdefC{
610 void cvMultiplyAcc( \par const CvArr* image1,\par const CvArr* image2,\par CvArr* acc,\par const CvArr* mask=NULL );
611 }
612 \cvdefPy{MultiplyAcc(image1,image2,acc,mask=NULL)-> None}
613
614 \begin{description}
615 \cvarg{image1}{First input image, 1- or 3-channel, 8-bit or 32-bit floating point (each channel of multi-channel image is processed independently)}
616 \cvarg{image2}{Second input image, the same format as the first one}
617 \cvarg{acc}{Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point}
618 \cvarg{mask}{Optional operation mask}
619 \end{description}
620
621 The function adds the product of 2 images or their selected regions to the accumulator \texttt{acc}:
622
623 \[ \texttt{acc}(x,y) \leftarrow \texttt{acc}(x,y) + \texttt{image1}(x,y) \cdot \texttt{image2}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
624
625 \ifC % {
626 \cvCPyFunc{ReleaseConDensation}
627 Deallocates the ConDensation filter structure.
628
629 \cvdefC{
630 void cvReleaseConDensation( CvConDensation** condens );
631
632 }
633 \begin{description}
634 \cvarg{condens}{Pointer to the pointer to the structure to be released}
635 \end{description}
636
637 The function releases the structure \cvCPyCross{CvConDensation}) and frees all memory previously allocated for the structure.
638
639 \fi % }
640
641 \ifC % {
642
643 \cvCPyFunc{ReleaseKalman}
644 Deallocates the Kalman filter structure.
645
646 \cvdefC{
647 void cvReleaseKalman( \par CvKalman** kalman );
648 }
649
650 \begin{description}
651 \cvarg{kalman}{double pointer to the Kalman filter structure}
652 \end{description}
653
654 The function releases the structure \cvCPyCross{CvKalman} and all of the underlying matrices.
655
656 \fi % }
657
658 \cvCPyFunc{RunningAvg}
659 Updates the running average.
660
661 \cvdefC{
662 void cvRunningAvg( \par const CvArr* image,\par CvArr* acc,\par double alpha,\par const CvArr* mask=NULL );
663 }
664 \cvdefPy{RunningAvg(image,acc,alpha,mask=NULL)-> None}
665
666 \begin{description}
667 \cvarg{image}{Input image, 1- or 3-channel, 8-bit or 32-bit floating point (each channel of multi-channel image is processed independently)}
668 \cvarg{acc}{Accumulator with the same number of channels as input image, 32-bit or 64-bit floating-point}
669 \cvarg{alpha}{Weight of input image}
670 \cvarg{mask}{Optional operation mask}
671 \end{description}
672
673 The function calculates the weighted sum of the input image
674 \texttt{image} and the accumulator \texttt{acc} so that \texttt{acc}
675 becomes a running average of frame sequence:
676
677 \[ \texttt{acc}(x,y) \leftarrow (1-\alpha) \cdot \texttt{acc}(x,y) + \alpha \cdot \texttt{image}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
678
679 where $\alpha$ (\texttt{alpha}) regulates the update speed (how fast the accumulator forgets about previous frames).
680
681
682 \cvCPyFunc{SegmentMotion}
683 Segments a whole motion into separate moving parts.
684
685 \cvdefC{
686 CvSeq* cvSegmentMotion( \par const CvArr* mhi,\par CvArr* seg\_mask,\par CvMemStorage* storage,\par double timestamp,\par double seg\_thresh );
687 }\cvdefPy{SegmentMotion(mhi,seg\_mask,storage,timestamp,seg\_thresh)-> None}
688
689 \begin{description}
690 \cvarg{mhi}{Motion history image}
691 \cvarg{seg\_mask}{Image where the mask found should be stored, single-channel, 32-bit floating-point}
692 \cvarg{storage}{Memory storage that will contain a sequence of motion connected components}
693 \cvarg{timestamp}{Current time in milliseconds or other units}
694 \cvarg{seg\_thresh}{Segmentation threshold; recommended to be equal to the interval between motion history "steps" or greater}
695 \end{description}
696
697 The function finds all of the motion segments and
698 marks them in \texttt{seg\_mask} with individual values (1,2,...). It
699 also returns a sequence of \cvCPyCross{CvConnectedComp}
700 structures, one for each motion component. After that the
701 motion direction for every component can be calculated with
702 \cvCPyCross{CalcGlobalOrientation} using the extracted mask of the particular
703 component \cvCPyCross{Cmp}.
704
705 \cvCPyFunc{SnakeImage}
706 Changes the contour position to minimize its energy.
707
708 \cvdefC{
709 void cvSnakeImage( \par const IplImage* image,\par CvPoint* points,\par int length,\par float* alpha,\par float* beta,\par float* gamma,\par int coeff\_usage,\par CvSize win,\par CvTermCriteria criteria,\par int calc\_gradient=1 );
710 }\cvdefPy{SnakeImage(image,points,alpha,beta,gamma,coeff\_usage,win,criteria,calc\_gradient=1)-> None}
711
712 \begin{description}
713 \cvarg{image}{The source image or external energy field}
714 \cvarg{points}{Contour points (snake)}
715 \ifC
716 \cvarg{length}{Number of points in the contour}
717 \fi
718 \cvarg{alpha}{Weight[s] of continuity energy, single float or array of \texttt{length} floats, one for each contour point}
719 \cvarg{beta}{Weight[s] of curvature energy, similar to \texttt{alpha}}
720 \cvarg{gamma}{Weight[s] of image energy, similar to \texttt{alpha}}
721 \cvarg{coeff\_usage}{Different uses of the previous three parameters:
722 \begin{description}
723   \cvarg{CV\_VALUE}{indicates that each of \texttt{alpha, beta, gamma} is a pointer to a single value to be used for all points;}
724   \cvarg{CV\_ARRAY}{indicates that each of \texttt{alpha, beta, gamma} is a pointer to an array of coefficients different for all the points of the snake. All the arrays must have the size equal to the contour size.}
725 \end{description}}
726 \cvarg{win}{Size of neighborhood of every point used to search the minimum, both \texttt{win.width} and \texttt{win.height} must be odd}
727 \cvarg{criteria}{Termination criteria}
728 \cvarg{calc\_gradient}{Gradient flag; if not 0, the function calculates the gradient magnitude for every image pixel and consideres it as the energy field, otherwise the input image itself is considered}
729 \end{description}
730
731 The function updates the snake in order to minimize its
732 total energy that is a sum of internal energy that depends on the contour
733 shape (the smoother contour is, the smaller internal energy is) and
734 external energy that depends on the energy field and reaches minimum at
735 the local energy extremums that correspond to the image edges in the case
736 of using an image gradient.
737
738 The parameter \texttt{criteria.epsilon} is used to define the minimal
739 number of points that must be moved during any iteration to keep the
740 iteration process running.
741
742 If at some iteration the number of moved points is less
743 than \texttt{criteria.epsilon} or the function performed
744 \texttt{criteria.max\_iter} iterations, the function terminates.
745
746 \cvCPyFunc{SquareAcc}
747 Adds the square of the source image to the accumulator.
748
749 \cvdefC{
750 void cvSquareAcc( \par const CvArr* image,\par CvArr* sqsum,\par const CvArr* mask=NULL );
751 }\cvdefPy{SquareAcc(image,sqsum,mask=NULL)-> None}
752
753 \begin{description}
754 \cvarg{image}{Input image, 1- or 3-channel, 8-bit or 32-bit floating point (each channel of multi-channel image is processed independently)}
755 \cvarg{sqsum}{Accumulator with the same number of channels as input image, 32-bit or 64-bit floating-point}
756 \cvarg{mask}{Optional operation mask}
757 \end{description}
758
759 The function adds the input image \texttt{image} or its selected region, raised to power 2, to the accumulator \texttt{sqsum}:
760
761 \[ \texttt{sqsum}(x,y) \leftarrow \texttt{sqsum}(x,y) + \texttt{image}(x,y)^2 \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
762
763 \cvCPyFunc{UpdateMotionHistory}
764 Updates the motion history image by a moving silhouette.
765
766 \cvdefC{
767 void cvUpdateMotionHistory( \par const CvArr* silhouette,\par CvArr* mhi,\par double timestamp,\par double duration );
768 }\cvdefPy{UpdateMotionHistory(silhouette,mhi,timestamp,duration)-> None}
769
770 \begin{description}
771 \cvarg{silhouette}{Silhouette mask that has non-zero pixels where the motion occurs}
772 \cvarg{mhi}{Motion history image, that is updated by the function (single-channel, 32-bit floating-point)}
773 \cvarg{timestamp}{Current time in milliseconds or other units}
774 \cvarg{duration}{Maximal duration of the motion track in the same units as \texttt{timestamp}}
775 \end{description}
776
777 The function updates the motion history image as following:
778
779 \[
780 \texttt{mhi}(x,y)=\forkthree
781 {\texttt{timestamp}}{if $\texttt{silhouette}(x,y) \ne 0$}
782 {0}{if $\texttt{silhouette}(x,y) = 0$ and $\texttt{mhi} < (\texttt{timestamp} - \texttt{duration})$}
783 {\texttt{mhi}(x,y)}{otherwise}
784 \]
785 That is, MHI pixels where motion occurs are set to the current timestamp, while the pixels where motion happened far ago are cleared.
786
787 \fi
788
789 \ifCpp
790
791 \cvCppFunc{accumulate}
792 Adds image to the accumulator.
793
794 \cvdefCpp{void accumulate( const Mat\& src, Mat\& dst, const Mat\& mask=Mat() );}
795 \begin{description}
796 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
797 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
798 \cvarg{mask}{Optional operation mask}
799 \end{description}
800
801 The function adds \texttt{src}, or some of its elements, to \texttt{dst}:
802
803 \[ \texttt{dst}(x,y) \leftarrow \texttt{dst}(x,y) + \texttt{src}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
804
805 The function supports multi-channel images; each channel is processed independently.
806
807 The functions \texttt{accumulate*} can be used, for example, to collect statistic of background of a scene, viewed by a still camera, for the further foreground-background segmentation.
808
809 See also: \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateWeighted}
810
811 \cvCppFunc{accumulateSquare}
812 Adds the square of the source image to the accumulator.
813
814 \cvdefCpp{void accumulateSquare( const Mat\& src, Mat\& dst, \par const Mat\& mask=Mat() );}
815 \begin{description}
816 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
817 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
818 \cvarg{mask}{Optional operation mask}
819 \end{description}
820
821 The function adds the input image \texttt{src} or its selected region, raised to power 2, to the accumulator \texttt{dst}:
822
823 \[ \texttt{dst}(x,y) \leftarrow \texttt{dst}(x,y) + \texttt{src}(x,y)^2 \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
824
825 The function supports multi-channel images; each channel is processed independently.
826
827 See also: \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateWeighted}
828
829 \cvCppFunc{accumulateProduct}
830 Adds the per-element product of two input images to the accumulator.
831
832 \cvdefCpp{void accumulateProduct( const Mat\& src1, const Mat\& src2,\par
833                         Mat\& dst, const Mat\& mask=Mat() );}
834 \begin{description}
835 \cvarg{src1}{The first input image, 1- or 3-channel, 8-bit or 32-bit floating point}
836 \cvarg{src2}{The second input image of the same type and the same size as \texttt{src1}}
837 \cvarg{dst}{Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point}
838 \cvarg{mask}{Optional operation mask}
839 \end{description}
840
841 The function adds the product of 2 images or their selected regions to the accumulator \texttt{dst}:
842
843 \[ \texttt{dst}(x,y) \leftarrow \texttt{dst}(x,y) + \texttt{src1}(x,y) \cdot \texttt{src2}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
844
845 The function supports multi-channel images; each channel is processed independently.
846
847 See also: \cvCppCross{accumulate}, \cvCppCross{accumulateSquare}, \cvCppCross{accumulateWeighted}
848
849 \cvCppFunc{accumulateWeighted}
850 Updates the running average.
851
852 \cvdefCpp{void accumulateWeighted( const Mat\& src, Mat\& dst,\par
853                          double alpha, const Mat\& mask=Mat() );}
854 \begin{description}
855 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
856 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
857 \cvarg{alpha}{Weight of the input image}
858 \cvarg{mask}{Optional operation mask}
859 \end{description}
860
861 The function calculates the weighted sum of the input image
862 \texttt{src} and the accumulator \texttt{dst} so that \texttt{dst}
863 becomes a running average of frame sequence:
864
865 \[ \texttt{dst}(x,y) \leftarrow (1-\texttt{alpha}) \cdot \texttt{dst}(x,y) + \texttt{alpha} \cdot \texttt{src}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
866
867 that is, \texttt{alpha} regulates the update speed (how fast the accumulator "forgets" about earlier images).
868 The function supports multi-channel images; each channel is processed independently.
869
870 See also: \cvCppCross{accumulate}, \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}
871
872 \cvCppFunc{calcOpticalFlowPyrLK}
873 Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids
874
875 \cvdefCpp{void calcOpticalFlowPyrLK( const Mat\& prevImg, const Mat\& nextImg,\par
876         const vector<Point2f>\& prevPts, vector<Point2f>\& nextPts,\par
877         vector<uchar>\& status, vector<float>\& err, \par
878         Size winSize=Size(15,15), int maxLevel=3,\par
879         TermCriteria criteria=TermCriteria(\par
880             TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01),\par
881         double derivLambda=0.5, int flags=0 );}
882 \begin{description}
883 \cvarg{prevImg}{The first 8-bit single-channel or 3-channel input image}
884 \cvarg{nextImg}{The second input image of the same size and the same type as \texttt{prevImg}}
885 \cvarg{prevPts}{Vector of points for which the flow needs to be found}
886 \cvarg{nextPts}{The output vector of points containing the calculated new positions of the input features in the second image}
887 \cvarg{status}{The output status vector. Each element of the vector is set to 1 if the flow for the corresponding features has been found, 0 otherwise}
888 \cvarg{err}{The output vector that will contain the difference between patches around the original and moved points}
889 \cvarg{winSize}{Size of the search window at each pyramid level}
890 \cvarg{maxLevel}{0-based maximal pyramid level number. If 0, pyramids are not used (single level), if 1, two levels are used etc.}
891 \cvarg{criteria}{Specifies the termination criteria of the iterative search algorithm (after the specified maximum number of iterations \texttt{criteria.maxCount} or when the search window moves by less than \texttt{criteria.epsilon}}
892 \cvarg{derivLambda}{The relative weight of the spatial image derivatives impact to the optical flow estimation. If \texttt{derivLambda=0}, only the image intensity is used, if \texttt{derivLambda=1}, only derivatives are used. Any other values between 0 and 1 means that both derivatives and the image intensity are used (in the corresponding proportions).}
893 \cvarg{flags}{The operation flags:
894 \begin{description}
895   \cvarg{OPTFLOW\_USE\_INITIAL\_FLOW}{use initial estimations stored in \texttt{nextPts}. If the flag is not set, then initially $\texttt{nextPts}\leftarrow\texttt{prevPts}$}
896 \end{description}}
897 \end{description}
898
899 The function implements the sparse iterative version of the Lucas-Kanade optical flow in pyramids, see \cite{Bouguet00}.
900
901 \cvCppFunc{calcOpticalFlowFarneback}
902 Computes dense optical flow using Gunnar Farneback's algorithm
903
904 \cvdefCpp{void calcOpticalFlowFarneback( const Mat\& prevImg, const Mat\& nextImg,\par
905                                Mat\& flow, double pyrScale, int levels, int winsize,\par
906                                int iterations, int polyN, double polySigma, int flags );}
907 \begin{description}
908 \cvarg{prevImg}{The first 8-bit single-channel input image}
909 \cvarg{nextImg}{The second input image of the same size and the same type as \texttt{prevImg}}
910 \cvarg{flow}{The computed flow image; will have the same size as \texttt{prevImg} and type \texttt{CV\_32FC2}}
911 \cvarg{pyrScale}{Specifies the image scale (<1) to build the pyramids for each image. \texttt{pyrScale=0.5} means the classical pyramid, where each next layer is twice smaller than the previous}
912 \cvarg{levels}{The number of pyramid layers, including the initial image. \texttt{levels=1} means that no extra layers are created and only the original images are used}
913 \cvarg{winsize}{The averaging window size; The larger values increase the algorithm robustness to image noise and give more chances for fast motion detection, but yield more blurred motion field}
914 \cvarg{iterations}{The number of iterations the algorithm does at each pyramid level}
915 \cvarg{polyN}{Size of the pixel neighborhood used to find polynomial expansion in each pixel. The larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred  motion field. Typically, \texttt{polyN}=5 or 7}
916 \cvarg{polySigma}{Standard deviation of the Gaussian that is used to smooth derivatives that are used as a basis for the polynomial expansion. For \texttt{polyN=5} you can set \texttt{polySigma=1.1}, for \texttt{polyN=7} a good value would be \texttt{polySigma=1.5}}
917 \cvarg{flags}{The operation flags; can be a combination of the following:
918 \begin{description}
919     \cvarg{OPTFLOW\_USE\_INITIAL\_FLOW}{Use the input \texttt{flow} as the initial flow approximation}
920     \cvarg{OPTFLOW\_FARNEBACK\_GAUSSIAN}{Use a Gaussian $\texttt{winsize}\times\texttt{winsize}$ filter instead of box filter of the same size for optical flow estimation. Usually, this option gives more accurate flow than with a box filter, at the cost of lower speed (and normally \texttt{winsize} for a Gaussian window should be set to a larger value to achieve the same level of robustness)}
921 \end{description}}
922 \end{description}
923
924 The function finds optical flow for each \texttt{prevImg} pixel using the alorithm so that
925
926 \[\texttt{prevImg}(x,y) \sim \texttt{nextImg}(\texttt{flow}(x,y)[0], \texttt{flow}(x,y)[1])\]
927
928
929 \cvCppFunc{updateMotionHistory}
930 Updates the motion history image by a moving silhouette.
931
932 \cvdefCpp{void updateMotionHistory( const Mat\& silhouette, Mat\& mhi,\par
933                           double timestamp, double duration );}
934 \begin{description}
935 \cvarg{silhouette}{Silhouette mask that has non-zero pixels where the motion occurs}
936 \cvarg{mhi}{Motion history image, that is updated by the function (single-channel, 32-bit floating-point)}
937 \cvarg{timestamp}{Current time in milliseconds or other units}
938 \cvarg{duration}{Maximal duration of the motion track in the same units as \texttt{timestamp}}
939 \end{description}
940
941 The function updates the motion history image as following:
942
943 \[
944 \texttt{mhi}(x,y)=\forkthree
945 {\texttt{timestamp}}{if $\texttt{silhouette}(x,y) \ne 0$}
946 {0}{if $\texttt{silhouette}(x,y) = 0$ and $\texttt{mhi} < (\texttt{timestamp} - \texttt{duration})$}
947 {\texttt{mhi}(x,y)}{otherwise}
948 \]
949 That is, MHI pixels where motion occurs are set to the current \texttt{timestamp}, while the pixels where motion happened last time a long time ago are cleared.
950
951 The function, together with \cvCppCross{calcMotionGradient} and \cvCppCross{calcGlobalOrientation}, implements the motion templates technique, described in \cite{Davis97} and \cite{Bradski00}.
952 See also the OpenCV sample \texttt{motempl.c} that demonstrates the use of all the motion template functions.
953
954 \cvCppFunc{calcMotionGradient}
955 Calculates the gradient orientation of a motion history image.
956
957 \cvdefCpp{void calcMotionGradient( const Mat\& mhi, Mat\& mask,\par
958                          Mat\& orientation,\par
959                          double delta1, double delta2,\par
960                          int apertureSize=3 );}
961 \begin{description}
962 \cvarg{mhi}{Motion history single-channel floating-point image}
963 \cvarg{mask}{The output mask image; will have the type \texttt{CV\_8UC1} and the same size as \texttt{mhi}. Its non-zero elements will mark pixels where the motion gradient data is correct}
964 \cvarg{orientation}{The output motion gradient orientation image; will have the same type and the same size as \texttt{mhi}. Each pixel of it will the motion orientation in degrees, from 0 to 360.}
965 \cvarg{delta1, delta2}{The minimal and maximal allowed difference between \texttt{mhi} values within a pixel neighorhood. That is, the function finds the minimum ($m(x,y)$) and maximum ($M(x,y)$) \texttt{mhi} values over $3 \times 3$ neighborhood of each pixel and marks the motion orientation at $(x, y)$ as valid only if
966 \[
967 \min(\texttt{delta1} , \texttt{delta2} ) \le M(x,y)-m(x,y) \le \max(\texttt{delta1} ,\texttt{delta2}).
968 \]}
969 \cvarg{apertureSize}{The aperture size of \cvCppCross{Sobel} operator}
970 \end{description}
971
972 The function calculates the gradient orientation at each pixel $(x, y)$ as:
973
974 \[
975 \texttt{orientation}(x,y)=\arctan{\frac{d\texttt{mhi}/dy}{d\texttt{mhi}/dx}}
976 \]
977
978 (in fact, \cvCppCross{fastArctan} and \cvCppCross{phase} are used, so that the computed angle is measured in degrees and covers the full range 0..360). Also, the \texttt{mask} is filled to indicate pixels where the computed angle is valid.
979
980 \cvCppFunc{calcGlobalOrientation}
981 Calculates the global motion orientation in some selected region.
982
983 \cvdefCpp{double calcGlobalOrientation( const Mat\& orientation, const Mat\& mask,\par
984                               const Mat\& mhi, double timestamp,\par
985                               double duration );}
986 \begin{description}
987 \cvarg{orientation}{Motion gradient orientation image, calculated by the function \cvCppCross{calcMotionGradient}}
988 \cvarg{mask}{Mask image. It may be a conjunction of a valid gradient mask, also calculated by \cvCppCross{calcMotionGradient}, and the mask of the region, whose direction needs to be calculated}
989 \cvarg{mhi}{The motion history image, calculated by \cvCppCross{updateMotionHistory}}
990 \cvarg{timestamp}{The timestamp passed to \cvCppCross{updateMotionHistory}}
991 \cvarg{duration}{Maximal duration of motion track in milliseconds, passed to \cvCppCross{updateMotionHistory}}
992 \end{description}
993
994 The function calculates the average
995 motion direction in the selected region and returns the angle between
996 0 degrees  and 360 degrees. The average direction is computed from
997 the weighted orientation histogram, where a recent motion has larger
998 weight and the motion occurred in the past has smaller weight, as recorded in \texttt{mhi}.
999
1000 \cvCppFunc{CamShift}
1001 Finds the object center, size, and orientation
1002
1003 \cvdefCpp{RotatedRect CamShift( const Mat\& probImage, Rect\& window,\par
1004                       TermCriteria criteria );}
1005 \begin{description}
1006 \cvarg{probImage}{Back projection of the object histogram; see \cvCppCross{calcBackProject}}
1007 \cvarg{window}{Initial search window}
1008 \cvarg{criteria}{Stop criteria for the underlying \cvCppCross{meanShift}}
1009 \end{description}
1010
1011 The function implements the CAMSHIFT object tracking algrorithm
1012 \cvCppCross{Bradski98}.
1013 First, it finds an object center using \cvCppCross{meanShift} and then adjust the window size and finds the optimal rotation. The function returns the rotated rectangle structure that includes the object position, size and the orientation. The next position of the search window can be obtained with \texttt{RotatedRect::boundingRect()}.
1014
1015 See the OpenCV sample \texttt{camshiftdemo.c} that tracks colored objects.
1016
1017 \cvCppFunc{meanShift}
1018 Finds the object on a back projection image.
1019
1020 \cvdefCpp{int meanShift( const Mat\& probImage, Rect\& window,\par
1021                TermCriteria criteria );}
1022 \begin{description}
1023 \cvarg{probImage}{Back projection of the object histogram; see \cvCppCross{calcBackProject}}
1024 \cvarg{window}{Initial search window}
1025 \cvarg{criteria}{The stop criteria for the iterative search algorithm}
1026 \end{description}
1027
1028 The function implements iterative object search algorithm. It takes the object back projection on input and the initial position. The mass center in \texttt{window} of the back projection image is computed and the search window center shifts to the mass center. The procedure is repeated until the specified number of iterations \texttt{criteria.maxCount} is done or until the window center shifts by less than \texttt{criteria.epsilon}. The algorithm is used inside \cvCppCross{CamShift} and, unlike \cvCppCross{CamShift}, the search window size or orientation do not change during the search. You can simply pass the output of \cvCppCross{calcBackProject} to this function, but better results can be obtained if you pre-filter the back projection and remove the noise (e.g. by retrieving connected components with \cvCppCross{findContours}, throwing away contours with small area (\cvCppCross{contourArea}) and rendering the  remaining contours with \cvCppCross{drawContours})
1029
1030
1031 \cvCppFunc{KalmanFilter}
1032 Kalman filter class
1033
1034 \begin{lstlisting}
1035 class KalmanFilter
1036 {
1037 public:
1038     KalmanFilter();newline
1039     KalmanFilter(int dynamParams, int measureParams, int controlParams=0);newline
1040     void init(int dynamParams, int measureParams, int controlParams=0);newline
1041     // predicts statePre from statePost
1042     const Mat& predict(const Mat& control=Mat());newline
1043     // corrects statePre based on the input measurement vector
1044     // and stores the result to statePost. 
1045     const Mat& correct(const Mat& measurement);newline
1046
1047     Mat statePre;           // predicted state (x'(k)):
1048                             //    x(k)=A*x(k-1)+B*u(k)
1049     Mat statePost;          // corrected state (x(k)):
1050                             //    x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
1051     Mat transitionMatrix;   // state transition matrix (A)
1052     Mat controlMatrix;      // control matrix (B)
1053                             //   (it is not used if there is no control)
1054     Mat measurementMatrix;  // measurement matrix (H)
1055     Mat processNoiseCov;    // process noise covariance matrix (Q)
1056     Mat measurementNoiseCov;// measurement noise covariance matrix (R)
1057     Mat errorCovPre;        // priori error estimate covariance matrix (P'(k)):
1058                             //    P'(k)=A*P(k-1)*At + Q)*/
1059     Mat gain;               // Kalman gain matrix (K(k)):
1060                             //    K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
1061     Mat errorCovPost;       // posteriori error estimate covariance matrix (P(k)):
1062                             //    P(k)=(I-K(k)*H)*P'(k)
1063     ...
1064 };
1065 \end{lstlisting}
1066
1067 The class implements standard Kalman filter \url{http://en.wikipedia.org/wiki/Kalman_filter}. However, you can modify \texttt{transitionMatrix}, \texttt{controlMatrix} and \texttt{measurementMatrix} to get the extended Kalman filter functionality. See the OpenCV sample \texttt{kalman.c}
1068
1069 \fi