]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cv_motion_tracking.tex
Many fixes for problems found by latex2sphinx. Turn citations into cite{}.
[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 \cite{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 \cite{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 \cite{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 }
202 \cvdefPy{CamShift(prob\_image,window,criteria)-> (int, comp, box)}
203
204 \begin{description}
205 \cvarg{prob\_image}{Back projection of object histogram (see \cvCPyCross{CalcBackProject})}
206 \cvarg{window}{Initial search window}
207 \cvarg{criteria}{Criteria applied to determine when the window search should be finished}
208 \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)}
209 \ifC % {
210 \cvarg{box}{Circumscribed box for the object. If not \texttt{NULL}, it contains object size and orientation}
211 \else % }{
212 \cvarg{box}{Circumscribed box for the object.}
213 \fi % }
214 \end{description}
215
216 The function implements the CAMSHIFT object tracking algrorithm
217 \cite{Bradski98}.
218 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}.
219
220 The \texttt{CamShiftTracker} class declared in cv.hpp implements the color object tracker that uses the function.
221
222 \ifC % {
223 \subsection{CvConDensation}
224 ConDenstation state.
225
226 \begin{lstlisting}
227     typedef struct CvConDensation
228     {
229         int MP;     //Dimension of measurement vector
230         int DP;     // Dimension of state vector
231         float* DynamMatr;       // Matrix of the linear Dynamics system
232         float* State;           // Vector of State
233         int SamplesNum;         // Number of the Samples
234         float** flSamples;      // array of the Sample Vectors
235         float** flNewSamples;   // temporary array of the Sample Vectors
236         float* flConfidence;    // Confidence for each Sample
237         float* flCumulative;    // Cumulative confidence
238         float* Temp;            // Temporary vector
239         float* RandomSample;    // RandomVector to update sample set
240         CvRandState* RandS;     // Array of structures to generate random vectors
241     } CvConDensation;
242
243 \end{lstlisting}
244 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}.
245
246 \cvCPyFunc{CreateConDensation}
247 Allocates the ConDensation filter structure.
248
249 \cvdefC{
250 CvConDensation* cvCreateConDensation( \par int dynam\_params,\par int measure\_params,\par int sample\_count );
251 }
252
253 \begin{description}
254 \cvarg{dynam\_params}{Dimension of the state vector}
255 \cvarg{measure\_params}{Dimension of the measurement vector}
256 \cvarg{sample\_count}{Number of samples}
257 \end{description}
258
259 The function creates a \texttt{CvConDensation} structure and returns a pointer to the structure.
260
261 \cvCPyFunc{ConDensInitSampleSet}
262 Initializes the sample set for the ConDensation algorithm.
263
264 \cvdefC{
265 void cvConDensInitSampleSet( CvConDensation* condens, \par CvMat* lower\_bound, \par CvMat* upper\_bound );
266 }
267
268 \begin{description}
269 \cvarg{condens}{Pointer to a structure to be initialized}
270 \cvarg{lower\_bound}{Vector of the lower boundary for each dimension}
271 \cvarg{upper\_bound}{Vector of the upper boundary for each dimension}
272 \end{description}
273
274 The function fills the samples arrays in the structure \texttt{condens} with values within the specified ranges.
275 \fi
276
277 \cvclass{CvKalman}\label{CvKalman}
278 Kalman filter state.
279
280 \begin{lstlisting}
281 typedef struct CvKalman
282 {
283     int MP;                     /* number of measurement vector dimensions */
284     int DP;                     /* number of state vector dimensions */
285     int CP;                     /* number of control vector dimensions */
286
287     /* backward compatibility fields */
288 #if 1
289     float* PosterState;         /* =state_pre->data.fl */
290     float* PriorState;          /* =state_post->data.fl */
291     float* DynamMatr;           /* =transition_matrix->data.fl */
292     float* MeasurementMatr;     /* =measurement_matrix->data.fl */
293     float* MNCovariance;        /* =measurement_noise_cov->data.fl */
294     float* PNCovariance;        /* =process_noise_cov->data.fl */
295     float* KalmGainMatr;        /* =gain->data.fl */
296     float* PriorErrorCovariance;/* =error_cov_pre->data.fl */
297     float* PosterErrorCovariance;/* =error_cov_post->data.fl */
298     float* Temp1;               /* temp1->data.fl */
299     float* Temp2;               /* temp2->data.fl */
300 #endif
301
302     CvMat* state_pre;           /* predicted state (x'(k)):
303                                     x(k)=A*x(k-1)+B*u(k) */
304     CvMat* state_post;          /* corrected state (x(k)):
305                                     x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) */
306     CvMat* transition_matrix;   /* state transition matrix (A) */
307     CvMat* control_matrix;      /* control matrix (B)
308                                    (it is not used if there is no control)*/
309     CvMat* measurement_matrix;  /* measurement matrix (H) */
310     CvMat* process_noise_cov;   /* process noise covariance matrix (Q) */
311     CvMat* measurement_noise_cov; /* measurement noise covariance matrix (R) */
312     CvMat* error_cov_pre;       /* priori error estimate covariance matrix (P'(k)):
313                                     P'(k)=A*P(k-1)*At + Q*/
314     CvMat* gain;                /* Kalman gain matrix (K(k)):
315                                     K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)*/
316     CvMat* error_cov_post;      /* posteriori error estimate covariance matrix (P(k)):
317                                     P(k)=(I-K(k)*H)*P'(k) */
318     CvMat* temp1;               /* temporary matrices */
319     CvMat* temp2;
320     CvMat* temp3;
321     CvMat* temp4;
322     CvMat* temp5;
323 }
324 CvKalman;
325 \end{lstlisting}
326
327 The structure \texttt{CvKalman} is used to keep the Kalman filter
328 state. It is created by the \cvCPyCross{CreateKalman} function, updated
329 by the \cvCPyCross{KalmanPredict} and \cvCPyCross{KalmanCorrect} functions
330 and released by the \cvCPyCross{ReleaseKalman} function. Normally, the
331 structure is used for the standard Kalman filter (notation and the
332 formulas below are borrowed from the excellent Kalman tutorial
333 \cite{Welch95})
334
335 \[
336 \begin{array}{l}
337 x_k=A \cdot x_{k-1}+B \cdot u_k+w_k\\
338 z_k=H \cdot x_k+v_k
339 \end{array}
340 \]
341
342 where:
343
344 \[
345 \begin{array}{l l}
346 x_k\;(x_{k-1})& \text{state of the system at the moment \emph{k} (\emph{k-1})}\\
347 z_k & \text{measurement of the system state at the moment \emph{k}}\\
348 u_k & \text{external control applied at the moment \emph{k}}
349 \end{array}
350 \]
351
352 $w_k$ and $v_k$ are normally-distributed process and measurement noise, respectively:
353
354 \[
355 \begin{array}{l}
356 p(w) \sim N(0,Q)\\
357 p(v) \sim N(0,R)
358 \end{array}
359 \]
360
361 that is,
362
363 $Q$ process noise covariance matrix, constant or variable,
364
365 $R$ measurement noise covariance matrix, constant or variable
366
367 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.
368
369 \cvCPyFunc{CreateKalman}
370 Allocates the Kalman filter structure.
371
372 \cvdefC{
373 CvKalman* cvCreateKalman( \par int dynam\_params,\par int measure\_params,\par int control\_params=0 );
374 }
375
376 \cvdefPy{
377 CreateKalman(dynam\_params, measure\_params, control\_params=0) -> CvKalman
378 }
379
380 \begin{description}
381 \cvarg{dynam\_params}{dimensionality of the state vector}
382 \cvarg{measure\_params}{dimensionality of the measurement vector}
383 \cvarg{control\_params}{dimensionality of the control vector}
384 \end{description}
385
386 The function allocates \cvCPyCross{CvKalman} and all its matrices and initializes them somehow.
387
388
389 \cvCPyFunc{KalmanCorrect}
390 Adjusts the model state.
391
392 \cvdefC{
393 const CvMat* cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement );
394 }
395 \cvdefPy{
396 KalmanCorrect(kalman, measurement) -> cvmat
397 }
398
399 \begin{description}
400 \ifC
401 \cvarg{kalman}{Pointer to the structure to be updated}
402 \else
403 \cvarg{kalman}{Kalman filter object returned by \cvCPyCross{CreateKalman}}
404 \fi
405 \cvarg{measurement}{CvMat containing the measurement vector}
406 \end{description}
407
408 \begin{lstlisting}
409 #define cvKalmanUpdateByMeasurement cvKalmanCorrect
410 \end{lstlisting}
411
412 The function adjusts the stochastic model state on the basis of the given measurement of the model state:
413
414 \[
415 \begin{array}{l}
416 K_k=P'_k \cdot H^T \cdot (H \cdot P'_k \cdot H^T+R)^{-1}\\
417 x_k=x'_k+K_k \cdot (z_k-H \cdot x'_k)\\
418 P_k=(I-K_k \cdot H) \cdot P'_k
419 \end{array}
420 \]
421
422 where
423
424 \begin{tabular}{l p{4 in}}
425 \hline
426 $z_k$ & given measurement (\texttt{mesurement} parameter)\\ \hline
427 $K_k$ & Kalman "gain" matrix.\\ \hline
428 \end{tabular}
429
430 The function stores the adjusted state at \texttt{kalman->state\_post} and returns it on output.
431
432 \ifC
433 Example. Using Kalman filter to track a rotating point
434 \begin{lstlisting}
435 #include "cv.h"
436 #include "highgui.h"
437 #include <math.h>
438
439 int main(int argc, char** argv)
440 {
441     /* A matrix data */
442     const float A[] = { 1, 1, 0, 1 };
443
444     IplImage* img = cvCreateImage( cvSize(500,500), 8, 3 );
445     CvKalman* kalman = cvCreateKalman( 2, 1, 0 );
446     /* state is (phi, delta_phi) - angle and angle increment */
447     CvMat* state = cvCreateMat( 2, 1, CV_32FC1 );
448     CvMat* process_noise = cvCreateMat( 2, 1, CV_32FC1 );
449     /* only phi (angle) is measured */
450     CvMat* measurement = cvCreateMat( 1, 1, CV_32FC1 );
451     CvRandState rng;
452     int code = -1;
453
454     cvRandInit( &rng, 0, 1, -1, CV_RAND_UNI );
455
456     cvZero( measurement );
457     cvNamedWindow( "Kalman", 1 );
458
459     for(;;)
460     {
461         cvRandSetRange( &rng, 0, 0.1, 0 );
462         rng.disttype = CV_RAND_NORMAL;
463
464         cvRand( &rng, state );
465
466         memcpy( kalman->transition_matrix->data.fl, A, sizeof(A));
467         cvSetIdentity( kalman->measurement_matrix, cvRealScalar(1) );
468         cvSetIdentity( kalman->process_noise_cov, cvRealScalar(1e-5) );
469         cvSetIdentity( kalman->measurement_noise_cov, cvRealScalar(1e-1) );
470         cvSetIdentity( kalman->error_cov_post, cvRealScalar(1));
471         /* choose random initial state */
472         cvRand( &rng, kalman->state_post );
473
474         rng.disttype = CV_RAND_NORMAL;
475
476         for(;;)
477         {
478             #define calc_point(angle)                                      \
479                 cvPoint( cvRound(img->width/2 + img->width/3*cos(angle)),  \
480                          cvRound(img->height/2 - img->width/3*sin(angle)))
481
482             float state_angle = state->data.fl[0];
483             CvPoint state_pt = calc_point(state_angle);
484
485             /* predict point position */
486             const CvMat* prediction = cvKalmanPredict( kalman, 0 );
487             float predict_angle = prediction->data.fl[0];
488             CvPoint predict_pt = calc_point(predict_angle);
489             float measurement_angle;
490             CvPoint measurement_pt;
491
492             cvRandSetRange( &rng,
493                             0,
494                             sqrt(kalman->measurement_noise_cov->data.fl[0]),
495                             0 );
496             cvRand( &rng, measurement );
497
498             /* generate measurement */
499             cvMatMulAdd( kalman->measurement_matrix, state, measurement, measurement );
500
501             measurement_angle = measurement->data.fl[0];
502             measurement_pt = calc_point(measurement_angle);
503
504             /* plot points */
505             #define draw_cross( center, color, d )                        \
506                 cvLine( img, cvPoint( center.x - d, center.y - d ),       \
507                              cvPoint( center.x + d, center.y + d ),       \
508                              color, 1, 0 );                               \
509                 cvLine( img, cvPoint( center.x + d, center.y - d ),       \
510                              cvPoint( center.x - d, center.y + d ),       \
511                              color, 1, 0 )
512
513             cvZero( img );
514             draw_cross( state_pt, CV_RGB(255,255,255), 3 );
515             draw_cross( measurement_pt, CV_RGB(255,0,0), 3 );
516             draw_cross( predict_pt, CV_RGB(0,255,0), 3 );
517             cvLine( img, state_pt, predict_pt, CV_RGB(255,255,0), 3, 0 );
518
519             /* adjust Kalman filter state */
520             cvKalmanCorrect( kalman, measurement );
521
522             cvRandSetRange( &rng,
523                             0,
524                             sqrt(kalman->process_noise_cov->data.fl[0]),
525                             0 );
526             cvRand( &rng, process_noise );
527             cvMatMulAdd( kalman->transition_matrix,
528                          state,
529                          process_noise,
530                          state );
531
532             cvShowImage( "Kalman", img );
533             code = cvWaitKey( 100 );
534
535             if( code > 0 ) /* break current simulation by pressing a key */
536                 break;
537         }
538         if( code == 27 ) /* exit by ESCAPE */
539             break;
540     }
541
542     return 0;
543 }
544 \end{lstlisting}
545 \fi
546
547 \cvCPyFunc{KalmanPredict}
548 Estimates the subsequent model state.
549
550 \cvdefC{
551 const CvMat* cvKalmanPredict( \par CvKalman* kalman, \par const CvMat* control=NULL );
552 }
553 \cvdefPy{
554 KalmanPredict(kalman, control=None) -> cvmat
555 }
556 \begin{lstlisting}
557 #define cvKalmanUpdateByTime cvKalmanPredict
558 \end{lstlisting}
559
560 \begin{description}
561 \ifC
562 \cvarg{kalman}{Kalman filter state}
563 \else
564 \cvarg{kalman}{Kalman filter object returned by \cvCPyCross{CreateKalman}}
565 \fi
566 \cvarg{control}{Control vector $u_k$, should be NULL iff there is no external control (\texttt{control\_params} =0)}
567 \end{description}
568
569 The function estimates the subsequent stochastic model state by its current state and stores it at \texttt{kalman->state\_pre}:
570
571 \[
572 \begin{array}{l}
573 x'_k=A \cdot x_{k-1}+B \cdot u_k\\
574 P'_k=A \cdot P_{k-1}+A^T + Q
575 \end{array}
576 \]
577
578 where
579
580 \begin{tabular}{l p{5 in}}
581 \hline
582 $x'_k$ & is predicted state \texttt{kalman->state\_pre},\\ \hline
583 $x_{k-1}$ & is corrected state on the previous step \texttt{kalman->state\_post}
584                 (should be initialized somehow in the beginning, zero vector by default),\\ \hline
585 $u_k$ & is external control (\texttt{control} parameter),\\ \hline
586 $P'_k$ & is priori error covariance matrix \texttt{kalman->error\_cov\_pre}\\ \hline
587 $P_{k-1}$ & is posteriori error covariance matrix on the previous step \texttt{kalman->error\_cov\_post}
588                 (should be initialized somehow in the beginning, identity matrix by default),
589 \end{tabular}
590
591 The function returns the estimated state.
592
593 \cvCPyFunc{MeanShift}
594 Finds the object center on back projection.
595
596 \cvdefC{
597 int cvMeanShift( \par const CvArr* prob\_image,\par CvRect window,\par CvTermCriteria criteria,\par CvConnectedComp* comp );
598 }\cvdefPy{MeanShift(prob\_image,window,criteria)-> comp}
599
600 \begin{description}
601 \cvarg{prob\_image}{Back projection of the object histogram (see \cvCPyCross{CalcBackProject})}
602 \cvarg{window}{Initial search window}
603 \cvarg{criteria}{Criteria applied to determine when the window search should be finished}
604 \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)}
605 \end{description}
606
607 The function iterates to find the object center
608 given its back projection and initial position of search window. The
609 iterations are made until the search window center moves by less than
610 the given value and/or until the function has done the maximum number
611 of iterations. The function returns the number of iterations made.
612
613 \cvCPyFunc{MultiplyAcc}
614 Adds the product of two input images to the accumulator.
615
616 \cvdefC{
617 void cvMultiplyAcc( \par const CvArr* image1,\par const CvArr* image2,\par CvArr* acc,\par const CvArr* mask=NULL );
618 }
619 \cvdefPy{MultiplyAcc(image1,image2,acc,mask=NULL)-> None}
620
621 \begin{description}
622 \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)}
623 \cvarg{image2}{Second input image, the same format as the first one}
624 \cvarg{acc}{Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point}
625 \cvarg{mask}{Optional operation mask}
626 \end{description}
627
628 The function adds the product of 2 images or their selected regions to the accumulator \texttt{acc}:
629
630 \[ \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 \]
631
632 \ifC % {
633 \cvCPyFunc{ReleaseConDensation}
634 Deallocates the ConDensation filter structure.
635
636 \cvdefC{
637 void cvReleaseConDensation( CvConDensation** condens );
638
639 }
640 \begin{description}
641 \cvarg{condens}{Pointer to the pointer to the structure to be released}
642 \end{description}
643
644 The function releases the structure \texttt{condens}) and frees all memory previously allocated for the structure.
645
646 \fi % }
647
648 \ifC % {
649
650 \cvCPyFunc{ReleaseKalman}
651 Deallocates the Kalman filter structure.
652
653 \cvdefC{
654 void cvReleaseKalman( \par CvKalman** kalman );
655 }
656
657 \begin{description}
658 \cvarg{kalman}{double pointer to the Kalman filter structure}
659 \end{description}
660
661 The function releases the structure \cvCPyCross{CvKalman} and all of the underlying matrices.
662
663 \fi % }
664
665 \cvCPyFunc{RunningAvg}
666 Updates the running average.
667
668 \cvdefC{
669 void cvRunningAvg( \par const CvArr* image,\par CvArr* acc,\par double alpha,\par const CvArr* mask=NULL );
670 }
671 \cvdefPy{RunningAvg(image,acc,alpha,mask=NULL)-> None}
672
673 \begin{description}
674 \cvarg{image}{Input image, 1- or 3-channel, 8-bit or 32-bit floating point (each channel of multi-channel image is processed independently)}
675 \cvarg{acc}{Accumulator with the same number of channels as input image, 32-bit or 64-bit floating-point}
676 \cvarg{alpha}{Weight of input image}
677 \cvarg{mask}{Optional operation mask}
678 \end{description}
679
680 The function calculates the weighted sum of the input image
681 \texttt{image} and the accumulator \texttt{acc} so that \texttt{acc}
682 becomes a running average of frame sequence:
683
684 \[ \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 \]
685
686 where $\alpha$ regulates the update speed (how fast the accumulator forgets about previous frames).
687
688
689 \cvCPyFunc{SegmentMotion}
690 Segments a whole motion into separate moving parts.
691
692 \cvdefC{
693 CvSeq* cvSegmentMotion( \par const CvArr* mhi,\par CvArr* seg\_mask,\par CvMemStorage* storage,\par double timestamp,\par double seg\_thresh );
694 }\cvdefPy{SegmentMotion(mhi,seg\_mask,storage,timestamp,seg\_thresh)-> None}
695
696 \begin{description}
697 \cvarg{mhi}{Motion history image}
698 \cvarg{seg\_mask}{Image where the mask found should be stored, single-channel, 32-bit floating-point}
699 \cvarg{storage}{Memory storage that will contain a sequence of motion connected components}
700 \cvarg{timestamp}{Current time in milliseconds or other units}
701 \cvarg{seg\_thresh}{Segmentation threshold; recommended to be equal to the interval between motion history "steps" or greater}
702 \end{description}
703
704 The function finds all of the motion segments and
705 marks them in \texttt{seg\_mask} with individual values (1,2,...). It
706 also returns a sequence of \cvCPyCross{CvConnectedComp}
707 structures, one for each motion component. After that the
708 motion direction for every component can be calculated with
709 \cvCPyCross{CalcGlobalOrientation} using the extracted mask of the particular
710 component \cvCPyCross{Cmp}.
711
712 \cvCPyFunc{SnakeImage}
713 Changes the contour position to minimize its energy.
714
715 \cvdefC{
716 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 );
717 }\cvdefPy{SnakeImage(image,points,alpha,beta,gamma,coeff\_usage,win,criteria,calc\_gradient=1)-> None}
718
719 \begin{description}
720 \cvarg{image}{The source image or external energy field}
721 \cvarg{points}{Contour points (snake)}
722 \ifC
723 \cvarg{length}{Number of points in the contour}
724 \fi
725 \cvarg{alpha}{Weight[s] of continuity energy, single float or array of \texttt{length} floats, one for each contour point}
726 \cvarg{beta}{Weight[s] of curvature energy, similar to \texttt{alpha}}
727 \cvarg{gamma}{Weight[s] of image energy, similar to \texttt{alpha}}
728 \cvarg{coeff\_usage}{Different uses of the previous three parameters:
729 \begin{description}
730   \cvarg{CV\_VALUE}{indicates that each of \texttt{alpha, beta, gamma} is a pointer to a single value to be used for all points;}
731   \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.}
732 \end{description}}
733 \cvarg{win}{Size of neighborhood of every point used to search the minimum, both \texttt{win.width} and \texttt{win.height} must be odd}
734 \cvarg{criteria}{Termination criteria}
735 \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}
736 \end{description}
737
738 The function updates the snake in order to minimize its
739 total energy that is a sum of internal energy that depends on the contour
740 shape (the smoother contour is, the smaller internal energy is) and
741 external energy that depends on the energy field and reaches minimum at
742 the local energy extremums that correspond to the image edges in the case
743 of using an image gradient.
744
745 The parameter \texttt{criteria.epsilon} is used to define the minimal
746 number of points that must be moved during any iteration to keep the
747 iteration process running.
748
749 If at some iteration the number of moved points is less
750 than \texttt{criteria.epsilon} or the function performed
751 \texttt{criteria.max\_iter} iterations, the function terminates.
752
753 \cvCPyFunc{SquareAcc}
754 Adds the square of the source image to the accumulator.
755
756 \cvdefC{
757 void cvSquareAcc( \par const CvArr* image,\par CvArr* sqsum,\par const CvArr* mask=NULL );
758 }\cvdefPy{SquareAcc(image,sqsum,mask=NULL)-> None}
759
760 \begin{description}
761 \cvarg{image}{Input image, 1- or 3-channel, 8-bit or 32-bit floating point (each channel of multi-channel image is processed independently)}
762 \cvarg{sqsum}{Accumulator with the same number of channels as input image, 32-bit or 64-bit floating-point}
763 \cvarg{mask}{Optional operation mask}
764 \end{description}
765
766 The function adds the input image \texttt{image} or its selected region, raised to power 2, to the accumulator \texttt{sqsum}:
767
768 \[ \texttt{sqsum}(x,y) \leftarrow \texttt{sqsum}(x,y) + \texttt{image}(x,y)^2 \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
769
770 \cvCPyFunc{UpdateMotionHistory}
771 Updates the motion history image by a moving silhouette.
772
773 \cvdefC{
774 void cvUpdateMotionHistory( \par const CvArr* silhouette,\par CvArr* mhi,\par double timestamp,\par double duration );
775 }\cvdefPy{UpdateMotionHistory(silhouette,mhi,timestamp,duration)-> None}
776
777 \begin{description}
778 \cvarg{silhouette}{Silhouette mask that has non-zero pixels where the motion occurs}
779 \cvarg{mhi}{Motion history image, that is updated by the function (single-channel, 32-bit floating-point)}
780 \cvarg{timestamp}{Current time in milliseconds or other units}
781 \cvarg{duration}{Maximal duration of the motion track in the same units as \texttt{timestamp}}
782 \end{description}
783
784 The function updates the motion history image as following:
785
786 \[
787 \texttt{mhi}(x,y)=\forkthree
788 {\texttt{timestamp}}{if $\texttt{silhouette}(x,y) \ne 0$}
789 {0}{if $\texttt{silhouette}(x,y) = 0$ and $\texttt{mhi} < (\texttt{timestamp} - \texttt{duration})$}
790 {\texttt{mhi}(x,y)}{otherwise}
791 \]
792 That is, MHI pixels where motion occurs are set to the current timestamp, while the pixels where motion happened far ago are cleared.
793
794 \fi
795
796 \ifCpp
797
798 \cvCppFunc{accumulate}
799 Adds image to the accumulator.
800
801 \cvdefCpp{void accumulate( const Mat\& src, Mat\& dst, const Mat\& mask=Mat() );}
802 \begin{description}
803 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
804 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
805 \cvarg{mask}{Optional operation mask}
806 \end{description}
807
808 The function adds \texttt{src}, or some of its elements, to \texttt{dst}:
809
810 \[ \texttt{dst}(x,y) \leftarrow \texttt{dst}(x,y) + \texttt{src}(x,y) \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
811
812 The function supports multi-channel images; each channel is processed independently.
813
814 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.
815
816 See also: \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateWeighted}
817
818 \cvCppFunc{accumulateSquare}
819 Adds the square of the source image to the accumulator.
820
821 \cvdefCpp{void accumulateSquare( const Mat\& src, Mat\& dst, \par const Mat\& mask=Mat() );}
822 \begin{description}
823 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
824 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
825 \cvarg{mask}{Optional operation mask}
826 \end{description}
827
828 The function adds the input image \texttt{src} or its selected region, raised to power 2, to the accumulator \texttt{dst}:
829
830 \[ \texttt{dst}(x,y) \leftarrow \texttt{dst}(x,y) + \texttt{src}(x,y)^2 \quad \text{if} \quad \texttt{mask}(x,y) \ne 0 \]
831
832 The function supports multi-channel images; each channel is processed independently.
833
834 See also: \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateWeighted}
835
836 \cvCppFunc{accumulateProduct}
837 Adds the per-element product of two input images to the accumulator.
838
839 \cvdefCpp{void accumulateProduct( const Mat\& src1, const Mat\& src2,\par
840                         Mat\& dst, const Mat\& mask=Mat() );}
841 \begin{description}
842 \cvarg{src1}{The first input image, 1- or 3-channel, 8-bit or 32-bit floating point}
843 \cvarg{src2}{The second input image of the same type and the same size as \texttt{src1}}
844 \cvarg{dst}{Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point}
845 \cvarg{mask}{Optional operation mask}
846 \end{description}
847
848 The function adds the product of 2 images or their selected regions to the accumulator \texttt{dst}:
849
850 \[ \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 \]
851
852 The function supports multi-channel images; each channel is processed independently.
853
854 See also: \cvCppCross{accumulate}, \cvCppCross{accumulateSquare}, \cvCppCross{accumulateWeighted}
855
856 \cvCppFunc{accumulateWeighted}
857 Updates the running average.
858
859 \cvdefCpp{void accumulateWeighted( const Mat\& src, Mat\& dst,\par
860                          double alpha, const Mat\& mask=Mat() );}
861 \begin{description}
862 \cvarg{src}{The input image, 1- or 3-channel, 8-bit or 32-bit floating point}
863 \cvarg{dst}{The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point}
864 \cvarg{alpha}{Weight of the input image}
865 \cvarg{mask}{Optional operation mask}
866 \end{description}
867
868 The function calculates the weighted sum of the input image
869 \texttt{src} and the accumulator \texttt{dst} so that \texttt{dst}
870 becomes a running average of frame sequence:
871
872 \[ \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 \]
873
874 that is, \texttt{alpha} regulates the update speed (how fast the accumulator "forgets" about earlier images).
875 The function supports multi-channel images; each channel is processed independently.
876
877 See also: \cvCppCross{accumulate}, \cvCppCross{accumulateSquare}, \cvCppCross{accumulateProduct}
878
879 \cvCppFunc{calcOpticalFlowPyrLK}
880 Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids
881
882 \cvdefCpp{void calcOpticalFlowPyrLK( const Mat\& prevImg, const Mat\& nextImg,\par
883         const vector<Point2f>\& prevPts, vector<Point2f>\& nextPts,\par
884         vector<uchar>\& status, vector<float>\& err, \par
885         Size winSize=Size(15,15), int maxLevel=3,\par
886         TermCriteria criteria=TermCriteria(\par
887             TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01),\par
888         double derivLambda=0.5, int flags=0 );}
889 \begin{description}
890 \cvarg{prevImg}{The first 8-bit single-channel or 3-channel input image}
891 \cvarg{nextImg}{The second input image of the same size and the same type as \texttt{prevImg}}
892 \cvarg{prevPts}{Vector of points for which the flow needs to be found}
893 \cvarg{nextPts}{The output vector of points containing the calculated new positions of the input features in the second image}
894 \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}
895 \cvarg{err}{The output vector that will contain the difference between patches around the original and moved points}
896 \cvarg{winSize}{Size of the search window at each pyramid level}
897 \cvarg{maxLevel}{0-based maximal pyramid level number. If 0, pyramids are not used (single level), if 1, two levels are used etc.}
898 \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}}
899 \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).}
900 \cvarg{flags}{The operation flags:
901 \begin{description}
902   \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}$}
903 \end{description}}
904 \end{description}
905
906 The function implements the sparse iterative version of the Lucas-Kanade optical flow in pyramids, see \cite{Bouguet00}.
907
908 \cvCppFunc{calcOpticalFlowFarneback}
909 Computes dense optical flow using Gunnar Farneback's algorithm
910
911 \cvdefCpp{void calcOpticalFlowFarneback( const Mat\& prevImg, const Mat\& nextImg,\par
912                                Mat\& flow, double pyrScale, int levels, int winsize,\par
913                                int iterations, int polyN, double polySigma, int flags );}
914 \begin{description}
915 \cvarg{prevImg}{The first 8-bit single-channel input image}
916 \cvarg{nextImg}{The second input image of the same size and the same type as \texttt{prevImg}}
917 \cvarg{flow}{The computed flow image; will have the same size as \texttt{prevImg} and type \texttt{CV\_32FC2}}
918 \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}
919 \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}
920 \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}
921 \cvarg{iterations}{The number of iterations the algorithm does at each pyramid level}
922 \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}
923 \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}}
924 \cvarg{flags}{The operation flags; can be a combination of the following:
925 \begin{description}
926     \cvarg{OPTFLOW\_USE\_INITIAL\_FLOW}{Use the input \texttt{flow} as the initial flow approximation}
927     \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)}
928 \end{description}}
929 \end{description}
930
931 The function finds optical flow for each \texttt{prevImg} pixel using the alorithm so that
932
933 \[\texttt{prevImg}(x,y) \sim \texttt{nextImg}(\texttt{flow}(x,y)[0], \texttt{flow}(x,y)[1])\]
934
935
936 \cvCppFunc{updateMotionHistory}
937 Updates the motion history image by a moving silhouette.
938
939 \cvdefCpp{void updateMotionHistory( const Mat\& silhouette, Mat\& mhi,\par
940                           double timestamp, double duration );}
941 \begin{description}
942 \cvarg{silhouette}{Silhouette mask that has non-zero pixels where the motion occurs}
943 \cvarg{mhi}{Motion history image, that is updated by the function (single-channel, 32-bit floating-point)}
944 \cvarg{timestamp}{Current time in milliseconds or other units}
945 \cvarg{duration}{Maximal duration of the motion track in the same units as \texttt{timestamp}}
946 \end{description}
947
948 The function updates the motion history image as following:
949
950 \[
951 \texttt{mhi}(x,y)=\forkthree
952 {\texttt{timestamp}}{if $\texttt{silhouette}(x,y) \ne 0$}
953 {0}{if $\texttt{silhouette}(x,y) = 0$ and $\texttt{mhi} < (\texttt{timestamp} - \texttt{duration})$}
954 {\texttt{mhi}(x,y)}{otherwise}
955 \]
956 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.
957
958 The function, together with \cvCppCross{calcMotionGradient} and \cvCppCross{calcGlobalOrientation}, implements the motion templates technique, described in \cite{Davis97} and \cite{Bradski00}.
959 See also the OpenCV sample \texttt{motempl.c} that demonstrates the use of all the motion template functions.
960
961 \cvCppFunc{calcMotionGradient}
962 Calculates the gradient orientation of a motion history image.
963
964 \cvdefCpp{void calcMotionGradient( const Mat\& mhi, Mat\& mask,\par
965                          Mat\& orientation,\par
966                          double delta1, double delta2,\par
967                          int apertureSize=3 );}
968 \begin{description}
969 \cvarg{mhi}{Motion history single-channel floating-point image}
970 \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}
971 \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.}
972 \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
973 \[
974 \min(\texttt{delta1} , \texttt{delta2} ) \le M(x,y)-m(x,y) \le \max(\texttt{delta1} ,\texttt{delta2}).
975 \]}
976 \cvarg{apertureSize}{The aperture size of \cvCppCross{Sobel} operator}
977 \end{description}
978
979 The function calculates the gradient orientation at each pixel $(x, y)$ as:
980
981 \[
982 \texttt{orientation}(x,y)=\arctan{\frac{d\texttt{mhi}/dy}{d\texttt{mhi}/dx}}
983 \]
984
985 (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.
986
987 \cvCppFunc{calcGlobalOrientation}
988 Calculates the global motion orientation in some selected region.
989
990 \cvdefCpp{double calcGlobalOrientation( const Mat\& orientation, const Mat\& mask,\par
991                               const Mat\& mhi, double timestamp,\par
992                               double duration );}
993 \begin{description}
994 \cvarg{orientation}{Motion gradient orientation image, calculated by the function \cvCppCross{calcMotionGradient}}
995 \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}
996 \cvarg{mhi}{The motion history image, calculated by \cvCppCross{updateMotionHistory}}
997 \cvarg{timestamp}{The timestamp passed to \cvCppCross{updateMotionHistory}}
998 \cvarg{duration}{Maximal duration of motion track in milliseconds, passed to \cvCppCross{updateMotionHistory}}
999 \end{description}
1000
1001 The function calculates the average
1002 motion direction in the selected region and returns the angle between
1003 0 degrees  and 360 degrees. The average direction is computed from
1004 the weighted orientation histogram, where a recent motion has larger
1005 weight and the motion occurred in the past has smaller weight, as recorded in \texttt{mhi}.
1006
1007 \cvCppFunc{CamShift}
1008 Finds the object center, size, and orientation
1009
1010 \cvdefCpp{RotatedRect CamShift( const Mat\& probImage, Rect\& window,\par
1011                       TermCriteria criteria );}
1012 \begin{description}
1013 \cvarg{probImage}{Back projection of the object histogram; see \cvCppCross{calcBackProject}}
1014 \cvarg{window}{Initial search window}
1015 \cvarg{criteria}{Stop criteria for the underlying \cvCppCross{meanShift}}
1016 \end{description}
1017
1018 The function implements the CAMSHIFT object tracking algrorithm
1019 \cite{Bradski98}.
1020 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()}.
1021
1022 See the OpenCV sample \texttt{camshiftdemo.c} that tracks colored objects.
1023
1024 \cvCppFunc{meanShift}
1025 Finds the object on a back projection image.
1026
1027 \cvdefCpp{int meanShift( const Mat\& probImage, Rect\& window,\par
1028                TermCriteria criteria );}
1029 \begin{description}
1030 \cvarg{probImage}{Back projection of the object histogram; see \cvCppCross{calcBackProject}}
1031 \cvarg{window}{Initial search window}
1032 \cvarg{criteria}{The stop criteria for the iterative search algorithm}
1033 \end{description}
1034
1035 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})
1036
1037
1038 \cvclass{KalmanFilter}
1039 Kalman filter class
1040
1041 \begin{lstlisting}
1042 class KalmanFilter
1043 {
1044 public:
1045     KalmanFilter();newline
1046     KalmanFilter(int dynamParams, int measureParams, int controlParams=0);newline
1047     void init(int dynamParams, int measureParams, int controlParams=0);newline
1048     // predicts statePre from statePost
1049     const Mat& predict(const Mat& control=Mat());newline
1050     // corrects statePre based on the input measurement vector
1051     // and stores the result to statePost. 
1052     const Mat& correct(const Mat& measurement);newline
1053
1054     Mat statePre;           // predicted state (x'(k)):
1055                             //    x(k)=A*x(k-1)+B*u(k)
1056     Mat statePost;          // corrected state (x(k)):
1057                             //    x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
1058     Mat transitionMatrix;   // state transition matrix (A)
1059     Mat controlMatrix;      // control matrix (B)
1060                             //   (it is not used if there is no control)
1061     Mat measurementMatrix;  // measurement matrix (H)
1062     Mat processNoiseCov;    // process noise covariance matrix (Q)
1063     Mat measurementNoiseCov;// measurement noise covariance matrix (R)
1064     Mat errorCovPre;        // priori error estimate covariance matrix (P'(k)):
1065                             //    P'(k)=A*P(k-1)*At + Q)*/
1066     Mat gain;               // Kalman gain matrix (K(k)):
1067                             //    K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
1068     Mat errorCovPost;       // posteriori error estimate covariance matrix (P(k)):
1069                             //    P(k)=(I-K(k)*H)*P'(k)
1070     ...
1071 };
1072 \end{lstlisting}
1073
1074 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}
1075
1076 \fi