]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cv_struct_shape_analysis.tex
InitLineIterator, describe return type and add doctests
[opencv.git] / opencv / doc / cv_struct_shape_analysis.tex
1 \section{Structural Analysis and Shape Descriptors}
2
3 \ifCPy
4
5 \cvCPyFunc{ApproxChains}
6 Approximates Freeman chain(s) with a polygonal curve.
7
8 \cvdefC{
9 CvSeq* cvApproxChains( \par CvSeq* src\_seq,\par CvMemStorage* storage,\par int method=CV\_CHAIN\_APPROX\_SIMPLE,\par double parameter=0,\par int minimal\_perimeter=0,\par int recursive=0 );
10 }
11 \cvdefPy{ApproxChains(src\_seq,storage,method=CV\_CHAIN\_APPROX\_SIMPLE,parameter=0,minimal\_perimeter=0,recursive=0)-> chains}
12
13 \begin{description}
14 \cvarg{src\_seq}{Pointer to the chain that can refer to other chains}
15 \cvarg{storage}{Storage location for the resulting polylines}
16 \cvarg{method}{Approximation method (see the description of the function \cvCPyCross{FindContours})}
17 \cvarg{parameter}{Method parameter (not used now)}
18 \cvarg{minimal\_perimeter}{Approximates only those contours whose perimeters are not less than \texttt{minimal\_perimeter}. Other chains are removed from the resulting structure}
19 \cvarg{recursive}{If not 0, the function approximates all chains that access can be obtained to from \texttt{src\_seq} by using the \texttt{h\_next} or \texttt{v\_next links}. If 0, the single chain is approximated}
20 \end{description}
21
22 This is a stand-alone approximation routine. The function \texttt{cvApproxChains} works exactly in the same way as \cvCPyCross{FindContours} with the corresponding approximation flag. The function returns pointer to the first resultant contour. Other approximated contours, if any, can be accessed via the \texttt{v\_next} or \texttt{h\_next} fields of the returned structure.
23
24 \cvCPyFunc{ApproxPoly}
25 Approximates polygonal curve(s) with the specified precision.
26
27 \cvdefC{
28 CvSeq* cvApproxPoly( \par const void* src\_seq,\par int header\_size,\par CvMemStorage* storage,\par int method,\par double parameter,\par int parameter2=0 );
29 }
30 \cvdefPy{
31 ApproxPoly(src\_seq, storage, method, parameter=0, parameter2=0) -> sequence
32 }
33
34 \begin{description}
35 \cvarg{src\_seq}{Sequence of an array of points}
36 \ifC
37 \cvarg{header\_size}{Header size of the approximated curve[s]}
38 \fi
39 \cvarg{storage}{Container for the approximated contours. If it is NULL, the input sequences' storage is used}
40 \cvarg{method}{Approximation method; only \texttt{CV\_POLY\_APPROX\_DP} is supported, that corresponds to the Douglas-Peucker algorithm}
41 \cvarg{parameter}{Method-specific parameter; in the case of \texttt{CV\_POLY\_APPROX\_DP} it is a desired approximation accuracy}
42 \cvarg{parameter2}{If case if \texttt{src\_seq} is a sequence, the parameter determines whether the single sequence should be approximated or all sequences on the same level or below \texttt{src\_seq} (see \cvCPyCross{FindContours} for description of hierarchical contour structures). If \texttt{src\_seq} is an array CvMat* of points, the parameter specifies whether the curve is closed (\texttt{parameter2}!=0) or not (\texttt{parameter2} =0)}
43 \end{description}
44
45 The function approximates one or more curves and
46 returns the approximation result[s]. In the case of multiple curves,
47 the resultant tree will have the same structure as the input one (1:1
48 correspondence).
49
50 \cvCPyFunc{ArcLength}
51 Calculates the contour perimeter or the curve length.
52
53 \cvdefC{
54 double cvArcLength( \par const void* curve,\par CvSlice slice=CV\_WHOLE\_SEQ,\par int isClosed=-1 );
55 }
56 \cvdefPy{ArcLength(curve,slice=CV\_WHOLE\_SEQ,isClosed=-1)-> double}
57
58 \begin{description}
59 \cvarg{curve}{Sequence or array of the curve points}
60 \cvarg{slice}{Starting and ending points of the curve, by default, the whole curve length is calculated}
61 \cvarg{isClosed}{Indicates whether the curve is closed or not. There are 3 cases:
62 \begin{itemize}
63   \item $\texttt{isClosed}=0$ the curve is assumed to be unclosed.
64   \item $\texttt{isClosed}>0$ the curve is assumed to be closed.
65   \item $\texttt{isClosed}<0$ if curve is sequence, the flag \texttt{CV\_SEQ\_FLAG\_CLOSED} of \texttt{((CvSeq*)curve)->flags} is checked to determine if the curve is closed or not, otherwise (curve is represented by array (CvMat*) of points) it is assumed to be unclosed.
66 \end{itemize}}
67 \end{description}
68
69 The function calculates the length or curve as the sum of lengths of segments between subsequent points
70
71 \cvCPyFunc{BoundingRect}
72 Calculates the up-right bounding rectangle of a point set.
73
74 \cvdefC{
75 CvRect cvBoundingRect( CvArr* points, int update=0 );
76 }\cvdefPy{BoundingRect(points,update=0)-> CvRect}
77
78 \begin{description}
79 \cvarg{points}{2D point set, either a sequence or vector (\texttt{CvMat}) of points}
80 \cvarg{update}{The update flag. See below.}
81 \end{description}
82
83 The function returns the up-right bounding rectangle for a 2d point set.
84 Here is the list of possible combination of the flag values and type of \texttt{points}:
85
86 \begin{tabular}{|c|c|p{3in}|}
87 \hline
88 update & points & action \\ \hline
89 0 & \texttt{CvContour\*} & the bounding rectangle is not calculated, but it is taken from \texttt{rect} field of the contour header.\\ \hline
90 1 & \texttt{CvContour\*} & the bounding rectangle is calculated and written to \texttt{rect} field of the contour header.\\ \hline
91 0 & \texttt{CvSeq\*} or \texttt{CvMat\*} & the bounding rectangle is calculated and returned.\\ \hline
92 1 & \texttt{CvSeq\*} or \texttt{CvMat\*} & runtime error is raised.\\ \hline
93 \end{tabular}
94
95 \cvCPyFunc{BoxPoints}
96 Finds the box vertices.
97
98 \cvdefC{
99 void cvBoxPoints( \par CvBox2D box,\par CvPoint2D32f pt[4] );
100 }\cvdefPy{BoxPoints(box)-> points}
101
102 \begin{description}
103 \cvarg{box}{Box}
104 \cvarg{points}{Array of vertices}
105 \end{description}
106
107 The function calculates the vertices of the input 2d box.
108
109 \ifC
110 Here is the function code:
111
112 \begin{lstlisting}
113 void cvBoxPoints( CvBox2D box, CvPoint2D32f pt[4] )
114 {
115     float a = (float)cos(box.angle)*0.5f;
116     float b = (float)sin(box.angle)*0.5f;
117
118     pt[0].x = box.center.x - a*box.size.height - b*box.size.width;
119     pt[0].y = box.center.y + b*box.size.height - a*box.size.width;
120     pt[1].x = box.center.x + a*box.size.height - b*box.size.width;
121     pt[1].y = box.center.y - b*box.size.height - a*box.size.width;
122     pt[2].x = 2*box.center.x - pt[0].x;
123     pt[2].y = 2*box.center.y - pt[0].y;
124     pt[3].x = 2*box.center.x - pt[1].x;
125     pt[3].y = 2*box.center.y - pt[1].y;
126 }
127 \end{lstlisting}
128 \fi
129
130 \cvCPyFunc{CalcPGH}
131 Calculates a pair-wise geometrical histogram for a contour.
132
133 \cvdefC{
134 void cvCalcPGH( const CvSeq* contour, CvHistogram* hist );
135 }\cvdefPy{CalcPGH(contour,hist)-> None}
136
137 \begin{description}
138 \cvarg{contour}{Input contour. Currently, only integer point coordinates are allowed}
139 \cvarg{hist}{Calculated histogram; must be two-dimensional}
140 \end{description}
141
142 The function calculates a
143 2D pair-wise geometrical histogram (PGH), described in
144 \cvCPyCross{Iivarinen97}
145 for the contour. The algorithm considers every pair of contour
146 edges. The angle between the edges and the minimum/maximum distances
147 are determined for every pair. To do this each of the edges in turn
148 is taken as the base, while the function loops through all the other
149 edges. When the base edge and any other edge are considered, the minimum
150 and maximum distances from the points on the non-base edge and line of
151 the base edge are selected. The angle between the edges defines the row
152 of the histogram in which all the bins that correspond to the distance
153 between the calculated minimum and maximum distances are incremented
154 (that is, the histogram is transposed relatively to the \cvCPyCross{Iivarninen97}
155 definition). The histogram can be used for contour matching.
156
157 \cvCPyFunc{CalcEMD2}
158 Computes the "minimal work" distance between two weighted point configurations.
159
160 \cvdefC{
161 float cvCalcEMD2( \par const CvArr* signature1,\par const CvArr* signature2,\par int distance\_type,\par CvDistanceFunction distance\_func=NULL,\par const CvArr* cost\_matrix=NULL,\par CvArr* flow=NULL,\par float* lower\_bound=NULL,\par void* userdata=NULL );
162 }\cvdefPy{CalcEMD2(signature1, signature2, distance\_type, distance\_func = None, cost\_matrix=None, flow=None, lower\_bound=None, userdata = None) -> float}
163
164 \begin{description}
165 \cvarg{signature1}{First signature, a $\texttt{size1}\times \texttt{dims}+1$ floating-point matrix. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have a single column (weights only) if the user-defined cost matrix is used}
166 \cvarg{signature2}{Second signature of the same format as \texttt{signature1}, though the number of rows may be different. The total weights may be different, in this case an extra "dummy" point is added to either \texttt{signature1} or \texttt{signature2}}
167 \cvarg{distance\_type}{Metrics used; \texttt{CV\_DIST\_L1, CV\_DIST\_L2}, and \texttt{CV\_DIST\_C} stand for one of the standard metrics; \texttt{CV\_DIST\_USER} means that a user-defined function \texttt{distance\_func} or pre-calculated \texttt{cost\_matrix} is used}
168 \ifC
169 \cvarg{distance\_func}{The user-supplied distance function. It takes coordinates of two points and returns the distance between the points
170 \texttt{
171 typedef float (*CvDistanceFunction)(const float* f1, const float* f2, void* userdata);
172 }
173 }
174 \else
175 \cvarg{distance\_func}{The user-supplied distance function. It takes coordinates of two points \texttt{pt0} and \texttt{pt1}, and returns the distance between the points, with sigature
176 \texttt{
177 func(pt0, pt1, userdata) -> float
178 }
179 }
180 \fi
181 \cvarg{cost\_matrix}{The user-defined $\texttt{size1}\times \texttt{size2}$ cost matrix. At least one of \texttt{cost\_matrix} and \texttt{distance\_func} must be NULL. Also, if a cost matrix is used, lower boundary (see below) can not be calculated, because it needs a metric function}
182 \cvarg{flow}{The resultant $\texttt{size1} \times \texttt{size2}$ flow matrix: $\texttt{flow}_{i,j}$ is a flow from $i$ th point of \texttt{signature1} to $j$ th point of \texttt{signature2}}
183 \cvarg{lower\_bound}{Optional input/output parameter: lower boundary of distance between the two signatures that is a distance between mass centers. The lower boundary may not be calculated if the user-defined cost matrix is used, the total weights of point configurations are not equal, or if the signatures consist of weights only (i.e. the signature matrices have a single column). The user \textbf{must} initialize \texttt{*lower\_bound}. If the calculated distance between mass centers is greater or equal to \texttt{*lower\_bound} (it means that the signatures are far enough) the function does not calculate EMD. In any case \texttt{*lower\_bound} is set to the calculated distance between mass centers on return. Thus, if user wants to calculate both distance between mass centers and EMD, \texttt{*lower\_bound} should be set to 0}
184 \cvarg{userdata}{Pointer to optional data that is passed into the user-defined distance function}
185 \end{description}
186
187 The function computes the earth mover distance and/or
188 a lower boundary of the distance between the two weighted point
189 configurations. One of the applications described in \cvCPyCross{RubnerSept98} is
190 multi-dimensional histogram comparison for image retrieval. EMD is a a
191 transportation problem that is solved using some modification of a simplex
192 algorithm, thus the complexity is exponential in the worst case, though, on average
193 it is much faster. In the case of a real metric the lower boundary
194 can be calculated even faster (using linear-time algorithm) and it can
195 be used to determine roughly whether the two signatures are far enough
196 so that they cannot relate to the same object.
197
198 \cvCPyFunc{CheckContourConvexity}
199 Tests contour convexity.
200
201 \cvdefC{
202 int cvCheckContourConvexity( const CvArr* contour );
203 }\cvdefPy{CheckContourConvexity(contour)-> int}
204
205 \begin{description}
206 \cvarg{contour}{Tested contour (sequence or array of points)}
207 \end{description}
208
209 The function tests whether the input contour is convex or not. The contour must be simple, without self-intersections.
210
211 \cvclass{CvConvexityDefect}\label{CvConvexityDefect}
212
213 \ifC
214 Structure describing a single contour convexity defect.
215
216 \begin{lstlisting}
217 typedef struct CvConvexityDefect
218 {
219     CvPoint* start; /* point of the contour where the defect begins */
220     CvPoint* end; /* point of the contour where the defect ends */
221     CvPoint* depth_point; /* the farthest from the convex hull point within the defect */
222     float depth; /* distance between the farthest point and the convex hull */
223 } CvConvexityDefect;
224 \end{lstlisting}
225 \else
226
227 A single contour convexity defect, represented by a tuple \texttt{(start, end, depthpoint, depth)}.
228
229 \begin{description}
230 \cvarg{start}{(x, y) point of the contour where the defect begins}
231 \cvarg{end}{(x, y) point of the contour where the defect ends}
232 \cvarg{depthpoint}{(x, y) point farthest from the convex hull point within the defect}
233 \cvarg{depth}{distance between the farthest point and the convex hull}
234 \end{description}
235
236 \fi
237
238 % ===== Picture. Convexity defects of hand contour. =====
239 \includegraphics[width=0.5\textwidth]{pics/defects.png}
240
241 \cvCPyFunc{ContourArea}
242 Calculates the area of a whole contour or a contour section.
243
244 \cvdefC{
245 double cvContourArea( \par const CvArr* contour, \par CvSlice slice=CV\_WHOLE\_SEQ );
246 }
247 \cvdefPy{ContourArea(contour,slice=CV\_WHOLE\_SEQ)-> double}
248
249 \begin{description}
250 \cvarg{contour}{Contour (sequence or array of vertices)}
251 \cvarg{slice}{Starting and ending points of the contour section of interest, by default, the area of the whole contour is calculated}
252 \end{description}
253
254 The function calculates the area of a whole contour
255 or a contour section. In the latter case the total area bounded by the
256 contour arc and the chord connecting the 2 selected points is calculated
257 as shown on the picture below:
258
259 \includegraphics[width=0.5\textwidth]{pics/contoursecarea.png}
260
261 Orientation of the contour affects the area sign, thus the function may return a \emph{negative} result. Use the \texttt{fabs()} function from C runtime to get the absolute value of the area.
262
263 \cvCPyFunc{ContourFromContourTree}
264 Restores a contour from the tree.
265
266 \cvdefC{
267 CvSeq* cvContourFromContourTree( \par const CvContourTree* tree,\par CvMemStorage* storage,\par CvTermCriteria criteria );
268 }\cvdefPy{ContourFromContourTree(tree,storage,criteria)-> contour}
269
270 \begin{description}
271 \cvarg{tree}{Contour tree}
272 \cvarg{storage}{Container for the reconstructed contour}
273 \cvarg{criteria}{Criteria, where to stop reconstruction}
274 \end{description}
275
276 The function restores the contour from its binary tree representation. The parameter \texttt{criteria} determines the accuracy and/or the number of tree levels used for reconstruction, so it is possible to build an approximated contour. The function returns the reconstructed contour.
277
278 \cvCPyFunc{ConvexHull2}
279 Finds the convex hull of a point set.
280
281 \cvdefC{
282 CvSeq* cvConvexHull2( \par const CvArr* input,\par void* storage=NULL,\par int orientation=CV\_CLOCKWISE,\par int return\_points=0 );
283 }
284 \cvdefPy{ConvexHull2(points,storage,orientation=CV\_CLOCKWISE,return\_points=0)-> convex\_hull}
285
286 \begin{description}
287 \cvarg{points}{Sequence or array of 2D points with 32-bit integer or floating-point coordinates}
288 \cvarg{storage}{The destination array (CvMat*) or memory storage (CvMemStorage*) that will store the convex hull. If it is an array, it should be 1d and have the same number of elements as the input array/sequence. On output the header is modified as to truncate the array down to the hull size.  If \texttt{storage} is NULL then the convex hull will be stored in the same storage as the input sequence}
289 \cvarg{orientation}{Desired orientation of convex hull: \texttt{CV\_CLOCKWISE} or \texttt{CV\_COUNTER\_CLOCKWISE}}
290 \cvarg{return\_points}{If non-zero, the points themselves will be stored in the hull instead of indices if \texttt{storage} is an array, or pointers if \texttt{storage} is memory storage}
291 \end{description}
292
293 The function finds the convex hull of a 2D point set using Sklansky's algorithm. If \texttt{storage} is memory storage, the function creates a sequence containing the hull points or pointers to them, depending on \texttt{return\_points} value and returns the sequence on output.  If \texttt{storage} is a CvMat, the function returns NULL.
294
295 \ifC
296
297 Example. Building convex hull for a sequence or array of points
298
299 \begin{lstlisting}
300 #include "cv.h"
301 #include "highgui.h"
302 #include <stdlib.h>
303
304 #define ARRAY  0 /* switch between array/sequence method by replacing 0<=>1 */
305
306 void main( int argc, char** argv )
307 {
308     IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
309     cvNamedWindow( "hull", 1 );
310
311 #if !ARRAY
312         CvMemStorage* storage = cvCreateMemStorage();
313 #endif
314
315     for(;;)
316     {
317         int i, count = rand()%100 + 1, hullcount;
318         CvPoint pt0;
319 #if !ARRAY
320         CvSeq* ptseq = cvCreateSeq( CV_SEQ_KIND_GENERIC|CV_32SC2,
321                                     sizeof(CvContour),
322                                     sizeof(CvPoint),
323                                     storage );
324         CvSeq* hull;
325
326         for( i = 0; i < count; i++ )
327         {
328             pt0.x = rand() % (img->width/2) + img->width/4;
329             pt0.y = rand() % (img->height/2) + img->height/4;
330             cvSeqPush( ptseq, &pt0 );
331         }
332         hull = cvConvexHull2( ptseq, 0, CV_CLOCKWISE, 0 );
333         hullcount = hull->total;
334 #else
335         CvPoint* points = (CvPoint*)malloc( count * sizeof(points[0]));
336         int* hull = (int*)malloc( count * sizeof(hull[0]));
337         CvMat point_mat = cvMat( 1, count, CV_32SC2, points );
338         CvMat hull_mat = cvMat( 1, count, CV_32SC1, hull );
339
340         for( i = 0; i < count; i++ )
341         {
342             pt0.x = rand() % (img->width/2) + img->width/4;
343             pt0.y = rand() % (img->height/2) + img->height/4;
344             points[i] = pt0;
345         }
346         cvConvexHull2( &point_mat, &hull_mat, CV_CLOCKWISE, 0 );
347         hullcount = hull_mat.cols;
348 #endif
349         cvZero( img );
350         for( i = 0; i < count; i++ )
351         {
352 #if !ARRAY
353             pt0 = *CV_GET_SEQ_ELEM( CvPoint, ptseq, i );
354 #else
355             pt0 = points[i];
356 #endif
357             cvCircle( img, pt0, 2, CV_RGB( 255, 0, 0 ), CV_FILLED );
358         }
359
360 #if !ARRAY
361         pt0 = **CV_GET_SEQ_ELEM( CvPoint*, hull, hullcount - 1 );
362 #else
363         pt0 = points[hull[hullcount-1]];
364 #endif
365
366         for( i = 0; i < hullcount; i++ )
367         {
368 #if !ARRAY
369             CvPoint pt = **CV_GET_SEQ_ELEM( CvPoint*, hull, i );
370 #else
371             CvPoint pt = points[hull[i]];
372 #endif
373             cvLine( img, pt0, pt, CV_RGB( 0, 255, 0 ));
374             pt0 = pt;
375         }
376
377         cvShowImage( "hull", img );
378
379         int key = cvWaitKey(0);
380         if( key == 27 ) // 'ESC'
381             break;
382
383 #if !ARRAY
384         cvClearMemStorage( storage );
385 #else
386         free( points );
387         free( hull );
388 #endif
389     }
390 }
391 \end{lstlisting}
392 \fi
393
394 \cvCPyFunc{ConvexityDefects}
395 Finds the convexity defects of a contour.
396
397 \cvdefC{
398 CvSeq* cvConvexityDefects( \par const CvArr* contour,\par const CvArr* convexhull,\par CvMemStorage* storage=NULL );
399 }\cvdefPy{ConvexityDefects(contour,convexhull,storage)-> convexity\_defects}
400
401 \begin{description}
402 \cvarg{contour}{Input contour}
403 \cvarg{convexhull}{Convex hull obtained using \cvCPyCross{ConvexHull2} that should contain pointers or indices to the contour points, not the hull points themselves (the \texttt{return\_points} parameter in \cvCPyCross{ConvexHull2} should be 0)}
404 \cvarg{storage}{Container for the output sequence of convexity defects. If it is NULL, the contour or hull (in that order) storage is used}
405 \end{description}
406
407 The function finds all convexity defects of the input contour and returns a sequence of the CvConvexityDefect structures.
408
409 \cvCPyFunc{CreateContourTree}
410 Creates a hierarchical representation of a contour.
411
412 \cvdefC{
413 CvContourTree* cvCreateContourTree( \par const CvSeq* contour,\par CvMemStorage* storage,\par double threshold );
414 }
415 \cvdefPy{CreateContourTree(contour,storage,threshold)-> contour\_tree}
416
417 \begin{description}
418 \cvarg{contour}{Input contour}
419 \cvarg{storage}{Container for output tree}
420 \cvarg{threshold}{Approximation accuracy}
421 \end{description}
422
423 The function creates a binary tree representation for the input \texttt{contour} and returns the pointer to its root. If the parameter \texttt{threshold} is less than or equal to 0, the function creates a full binary tree representation. If the threshold is greater than 0, the function creates a representation with the precision \texttt{threshold}: if the vertices with the interceptive area of its base line are less than \texttt{threshold}, the tree should not be built any further. The function returns the created tree.
424
425 \ifC % {
426
427 \cvCPyFunc{EndFindContours}
428 Finishes the scanning process.
429
430 \cvdefC{
431 CvSeq* cvEndFindContours( \par CvContourScanner* scanner );
432 }
433
434 \begin{description}
435 \cvarg{scanner}{Pointer to the contour scanner}
436 \end{description}
437
438 The function finishes the scanning process and returns a pointer to the first contour on the highest level.
439
440 \fi % }
441
442 \cvCPyFunc{FindContours}
443 Finds the contours in a binary image.
444
445 \cvdefC{
446 int cvFindContours(\par CvArr* image,\par CvMemStorage* storage,\par CvSeq** first\_contour,\par
447                     int header\_size=sizeof(CvContour),\par int mode=CV\_RETR\_LIST,\par
448                     int method=CV\_CHAIN\_APPROX\_SIMPLE,\par CvPoint offset=cvPoint(0,0) );
449 }
450 \cvdefPy{FindContours(image, storage, mode=CV\_RETR\_LIST, method=CV\_CHAIN\_APPROX\_SIMPLE, offset=(0,0)) -> cvseq}
451
452 \begin{description}
453 \cvarg{image}{The source, an 8-bit single channel image. Non-zero pixels are treated as 1's, zero pixels remain 0's - the image is treated as \texttt{binary}. To get such a binary image from grayscale, one may use \cvCPyCross{Threshold}, \cvCPyCross{AdaptiveThreshold} or \cvCPyCross{Canny}. The function modifies the source image's content}
454 \cvarg{storage}{Container of the retrieved contours}
455 \ifC
456 \cvarg{first\_contour}{Output parameter, will contain the pointer to the first outer contour}
457 \cvarg{header\_size}{Size of the sequence header, $\ge \texttt{sizeof(CvChain)}$ if $\texttt{method} =\texttt{CV\_CHAIN\_CODE}$,
458 and $\ge \texttt{sizeof(CvContour)}$ otherwise}
459 \fi
460 \cvarg{mode}{Retrieval mode
461 \begin{description}
462   \cvarg{CV\_RETR\_EXTERNAL}{retrives only the extreme outer contours}
463   \cvarg{CV\_RETR\_LIST}{retrieves all of the contours and puts them in the list}
464   \cvarg{CV\_RETR\_CCOMP}{retrieves all of the contours and organizes them into a two-level hierarchy: on the top level are the external boundaries of the components, on the second level are the boundaries of the holes}
465   \cvarg{CV\_RETR\_TREE}{retrieves all of the contours and reconstructs the full hierarchy of nested contours}
466 \end{description}}
467 \cvarg{method}{Approximation method (for all the modes, except \texttt{CV\_LINK\_RUNS}, which uses built-in approximation)
468 \begin{description}
469   \cvarg{CV\_CHAIN\_CODE}{outputs contours in the Freeman chain code. All other methods output polygons (sequences of vertices)}
470   \cvarg{CV\_CHAIN\_APPROX\_NONE}{translates all of the points from the chain code into points}
471   \cvarg{CV\_CHAIN\_APPROX\_SIMPLE}{compresses horizontal, vertical, and diagonal segments and leaves only their end points}
472   \cvarg{CV\_CHAIN\_APPROX\_TC89\_L1,CV\_CHAIN\_APPROX\_TC89\_KCOS}{applies one of the flavors of the Teh-Chin chain approximation algorithm.}
473   \cvarg{CV\_LINK\_RUNS}{uses a completely different contour retrieval algorithm by linking horizontal segments of 1's. Only the \texttt{CV\_RETR\_LIST} retrieval mode can be used with this method.}
474 \end{description}}
475 \cvarg{offset}{Offset, by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context}
476 \end{description}
477
478 The function retrieves contours from the
479 binary image and returns the number of retrieved contours. The
480 pointer \texttt{first\_contour} is filled by the function. It will
481 contain a pointer to the first outermost contour or \texttt{NULL} if no
482 contours are detected (if the image is completely black). Other
483 contours may be reached from \texttt{first\_contour} using the
484 \texttt{h\_next} and \texttt{v\_next} links. The sample in the
485 \cvCPyCross{DrawContours} discussion shows how to use contours for
486 connected component detection. Contours can be also used for shape
487 analysis and object recognition - see \texttt{squares.c} in the OpenCV
488 sample directory.
489
490
491 \ifC % {
492
493 \cvCPyFunc{FindNextContour}
494 Finds the next contour in the image.
495
496 \cvdefC{
497 CvSeq* cvFindNextContour( \par CvContourScanner scanner );
498 }
499
500 \begin{description}
501 \cvarg{scanner}{Contour scanner initialized by \cvCPyCross{StartFindContours} }
502 \end{description}
503
504 The function locates and retrieves the next contour in the image and returns a pointer to it. The function returns NULL if there are no more contours.
505
506 \fi % }
507
508 \cvCPyFunc{FitEllipse2}
509 Fits an ellipse around a set of 2D points.
510
511 \cvdefC{
512 CvBox2D cvFitEllipse2( \par const CvArr* points );
513 }
514 \cvdefPy{FitEllipse2(points)-> Box2D}
515
516 \begin{description}
517 \cvarg{points}{Sequence or array of points}
518 \end{description}
519
520 The function calculates the ellipse that fits best
521 (in least-squares sense) around a set of 2D points. The meaning of the
522 returned structure fields is similar to those in \cvCPyCross{Ellipse} except
523 that \texttt{size} stores the full lengths of the ellipse axises,
524 not half-lengths.
525
526 \cvCPyFunc{FitLine}
527 Fits a line to a 2D or 3D point set.
528
529 \cvdefC{
530 void  cvFitLine( \par const CvArr* points,\par int dist\_type,\par double param,\par double reps,\par double aeps,\par float* line );
531 }
532 \cvdefPy{FitLine(points, dist\_type, param, reps, aeps) -> line}
533
534 \begin{description}
535 \cvarg{points}{Sequence or array of 2D or 3D points with 32-bit integer or floating-point coordinates}
536 \cvarg{dist\_type}{The distance used for fitting (see the discussion)}
537 \cvarg{param}{Numerical parameter (\texttt{C}) for some types of distances, if 0 then some optimal value is chosen}
538 \cvarg{reps}{Sufficient accuracy for the radius (distance between the coordinate origin and the line).  0.01 is a good default value.}
539 \cvarg{aeps}{Sufficient accuracy for the angle.  0.01 is a good default value.}
540 \cvarg{line}{The output line parameters. In the case of a 2d fitting,
541 it is \cvC{an array} \cvPy{a tuple} of 4 floats \texttt{(vx, vy, x0, y0)} where \texttt{(vx, vy)} is a normalized vector collinear to the
542 line and \texttt{(x0, y0)} is some point on the line. in the case of a
543 3D fitting it is \cvC{an array} \cvPy{a tuple} of 6 floats \texttt{(vx, vy, vz, x0, y0, z0)}
544 where \texttt{(vx, vy, vz)} is a normalized vector collinear to the line
545 and \texttt{(x0, y0, z0)} is some point on the line}
546 \end{description}
547
548 The function fits a line to a 2D or 3D point set by minimizing $\sum_i \rho(r_i)$ where $r_i$ is the distance between the $i$ th point and the line and $\rho(r)$ is a distance function, one of:
549
550 \begin{description}
551
552 \item[dist\_type=CV\_DIST\_L2]
553 \[ \rho(r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)} \]
554
555 \item[dist\_type=CV\_DIST\_L1]
556 \[ \rho(r) = r \]
557
558 \item[dist\_type=CV\_DIST\_L12]
559 \[ \rho(r) = 2 \cdot (\sqrt{1 + \frac{r^2}{2}} - 1) \]
560
561 \item[dist\_type=CV\_DIST\_FAIR]
562 \[ \rho\left(r\right) = C^2 \cdot \left( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)}\right) \quad \text{where} \quad C=1.3998 \]
563
564 \item[dist\_type=CV\_DIST\_WELSCH]
565 \[ \rho\left(r\right) = \frac{C^2}{2} \cdot \left( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)}\right) \quad \text{where} \quad C=2.9846 \]
566
567 \item[dist\_type=CV\_DIST\_HUBER]
568 \[ \rho(r) = \fork
569 {r^2/2}{if $r < C$}
570 {C \cdot (r-C/2)}{otherwise}  \quad \text{where} \quad C=1.345
571 \]
572 \end{description}
573
574 \cvCPyFunc{GetCentralMoment}
575 Retrieves the central moment from the moment state structure.
576
577 \cvdefC{
578 double cvGetCentralMoment( \par CvMoments* moments,\par int x\_order,\par int y\_order );
579 }
580 \cvdefPy{GetCentralMoment(moments, x\_order, y\_order) -> double}
581
582 \begin{description}
583 \cvarg{moments}{Pointer to the moment state structure}
584 \cvarg{x\_order}{x order of the retrieved moment, $\texttt{x\_order} >= 0$}
585 \cvarg{y\_order}{y order of the retrieved moment, $\texttt{y\_order} >= 0$ and $\texttt{x\_order} + \texttt{y\_order} <= 3$}
586 \end{description}
587
588 The function retrieves the central moment, which in the case of image moments is defined as:
589
590 \[
591 \mu_{x\_order, \, y\_order} = \sum_{x,y} (I(x,y) \cdot (x-x_c)^{x\_order} \cdot (y-y_c)^{y\_order})
592 \]
593
594 where $x_c,y_c$ are the coordinates of the gravity center:
595
596 \[
597 x_c=\frac{M_{10}}{M_{00}}, y_c=\frac{M_{01}}{M_{00}}
598 \]
599
600 \cvCPyFunc{GetHuMoments}
601 Calculates the seven Hu invariants.
602
603 \cvdefC{void cvGetHuMoments( const CvMoments* moments,CvHuMoments* hu );}
604 \cvdefPy{GetHuMoments(moments) -> hu}
605
606 \begin{description}
607 \cvarg{moments}{The input moments, computed with \cvCPyCross{Moments}}
608 \cvarg{hu}{The output Hu invariants}
609 \end{description}
610
611 The function calculates the seven Hu invariants, see \url{http://en.wikipedia.org/wiki/Image_moment}, that are defined as:
612
613 \[ \begin{array}{l}
614 hu_1=\eta_{20}+\eta_{02}\\
615 hu_2=(\eta_{20}-\eta_{02})^{2}+4\eta_{11}^{2}\\
616 hu_3=(\eta_{30}-3\eta_{12})^{2}+ (3\eta_{21}-\eta_{03})^{2}\\
617 hu_4=(\eta_{30}+\eta_{12})^{2}+ (\eta_{21}+\eta_{03})^{2}\\
618 hu_5=(\eta_{30}-3\eta_{12})(\eta_{30}+\eta_{12})[(\eta_{30}+\eta_{12})^{2}-3(\eta_{21}+\eta_{03})^{2}]+(3\eta_{21}-\eta_{03})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]\\
619 hu_6=(\eta_{20}-\eta_{02})[(\eta_{30}+\eta_{12})^{2}- (\eta_{21}+\eta_{03})^{2}]+4\eta_{11}(\eta_{30}+\eta_{12})(\eta_{21}+\eta_{03})\\
620 hu_7=(3\eta_{21}-\eta_{03})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]-(\eta_{30}-3\eta_{12})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]\\
621 \end{array}
622 \]
623
624 where $\eta_{ji}$ denote the normalized central moments.
625
626 These values are proved to be invariant to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. Of course, this invariance was proved with the assumption of infinite image resolution. In case of a raster images the computed Hu invariants for the original and transformed images will be a bit different.
627
628 \ifPy
629 \begin{lstlisting}
630 >>> import cv
631 >>> original = cv.LoadImageM("building.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)
632 >>> print cv.GetHuMoments(cv.Moments(original))
633 (0.0010620951868446141, 1.7962726159653835e-07, 1.4932744974469421e-11, 4.4832441315737963e-12, -1.0819359198251739e-23, -9.5726503811945833e-16, -3.5050592804744648e-23)
634 >>> flipped = cv.CloneMat(original)
635 >>> cv.Flip(original, flipped)
636 >>> print cv.GetHuMoments(cv.Moments(flipped))
637 (0.0010620951868446141, 1.796272615965384e-07, 1.4932744974469935e-11, 4.4832441315740249e-12, -1.0819359198259393e-23, -9.572650381193327e-16, 3.5050592804745877e-23)
638 \end{lstlisting}
639 \fi
640
641 \cvCPyFunc{GetNormalizedCentralMoment}
642 Retrieves the normalized central moment from the moment state structure.
643
644 \cvdefC{
645 double cvGetNormalizedCentralMoment( \par CvMoments* moments,\par int x\_order,\par int y\_order );
646 }\cvdefPy{GetNormalizedCentralMoment(moments, x\_order, y\_order) -> double}
647
648 \begin{description}
649 \cvarg{moments}{Pointer to the moment state structure}
650 \cvarg{x\_order}{x order of the retrieved moment, $\texttt{x\_order} >= 0$}
651 \cvarg{y\_order}{y order of the retrieved moment, $\texttt{y\_order} >= 0$ and $\texttt{x\_order} + \texttt{y\_order} <= 3$}
652 \end{description}
653
654 The function retrieves the normalized central moment:
655
656 \[
657 \eta_{x\_order, \, y\_order} = \frac{\mu_{x\_order, \, y\_order}}{M_{00}^{(y\_order+x\_order)/2+1}}
658 \]
659
660 \cvCPyFunc{GetSpatialMoment}
661 Retrieves the spatial moment from the moment state structure.
662
663 \cvdefC{
664 double cvGetSpatialMoment( \par CvMoments* moments, \par int x\_order, \par int y\_order );
665 }
666 \cvdefPy{GetSpatialMoment(moments, x\_order, y\_order) -> double}
667
668 \begin{description}
669 \cvarg{moments}{The moment state, calculated by \cvCPyCross{Moments}}
670 \cvarg{x\_order}{x order of the retrieved moment, $\texttt{x\_order} >= 0$}
671 \cvarg{y\_order}{y order of the retrieved moment, $\texttt{y\_order} >= 0$ and $\texttt{x\_order} + \texttt{y\_order} <= 3$}
672 \end{description}
673
674 The function retrieves the spatial moment, which in the case of image moments is defined as:
675
676 \[
677 M_{x\_order, \, y\_order} = \sum_{x,y} (I(x,y) \cdot x^{x\_order} \cdot y^{y\_order})
678 \]
679
680 where $I(x,y)$ is the intensity of the pixel $(x, y)$.
681
682 \cvCPyFunc{MatchContourTrees}
683 Compares two contours using their tree representations.
684
685 \cvdefC{
686 double cvMatchContourTrees( \par const CvContourTree* tree1,\par const CvContourTree* tree2,\par int method,\par double threshold );
687 }\cvdefPy{MatchContourTrees(tree1,tree2,method,threshold)-> double}
688
689 \begin{description}
690 \cvarg{tree1}{First contour tree}
691 \cvarg{tree2}{Second contour tree}
692 \cvarg{method}{Similarity measure, only \texttt{CV\_CONTOUR\_TREES\_MATCH\_I1} is supported}
693 \cvarg{threshold}{Similarity threshold}
694 \end{description}
695
696 The function calculates the value of the matching measure for two contour trees. The similarity measure is calculated level by level from the binary tree roots. If at a certain level the difference between contours becomes less than \texttt{threshold}, the reconstruction process is interrupted and the current difference is returned.
697
698 \cvCPyFunc{MatchShapes}
699 Compares two shapes.
700
701 \cvdefC{
702 double cvMatchShapes( \par const void* object1,\par const void* object2,\par int method,\par double parameter=0 );
703 }\cvdefPy{MatchShapes(object1,object2,method,parameter=0)-> None}
704
705 \begin{description}
706 \cvarg{object1}{First contour or grayscale image}
707 \cvarg{object2}{Second contour or grayscale image}
708 \cvarg{method}{Comparison method;
709  \texttt{CV\_CONTOUR\_MATCH\_I1}, 
710  \texttt{CV\_CONTOURS\_MATCH\_I2} 
711 or 
712  \texttt{CV\_CONTOURS\_MATCH\_I3}}
713 \cvarg{parameter}{Method-specific parameter (is not used now)}
714 \end{description}
715
716 The function compares two shapes. The 3 implemented methods all use Hu moments (see \cvCPyCross{GetHuMoments}) ($A$ is \texttt{object1}, $B$ is \texttt{object2}):
717
718 \begin{description}
719 \item[method=CV\_CONTOUR\_MATCH\_I1]
720 \[ I_1(A,B) = \sum_{i=1...7} \left| \frac{1}{m^A_i} - \frac{1}{m^B_i} \right| \]
721
722 \item[method=CV\_CONTOUR\_MATCH\_I2]
723 \[ I_2(A,B) = \sum_{i=1...7} \left| m^A_i - m^B_i \right| \]
724
725 \item[method=CV\_CONTOUR\_MATCH\_I3]
726 \[ I_3(A,B) = \sum_{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| } \]
727 \end{description}
728
729 where
730
731 \[
732 \begin{array}{l}
733 m^A_i = sign(h^A_i) \cdot \log{h^A_i}
734 m^B_i = sign(h^B_i) \cdot \log{h^B_i}
735 \end{array}
736 \]
737
738 and $h^A_i, h^B_i$ are the Hu moments of $A$ and $B$ respectively.
739
740
741 \cvCPyFunc{MinAreaRect2}
742 Finds the circumscribed rectangle of minimal area for a given 2D point set.
743
744 \cvdefC{
745 CvBox2D  cvMinAreaRect2( \par const CvArr* points,\par CvMemStorage* storage=NULL );
746 }\cvdefPy{MinAreaRect2(points,storage=NULL)-> CvBox2D}
747
748 \begin{description}
749 \cvarg{points}{Sequence or array of points}
750 \cvarg{storage}{Optional temporary memory storage}
751 \end{description}
752
753 The function finds a circumscribed rectangle of the minimal area for a 2D point set by building a convex hull for the set and applying the rotating calipers technique to the hull.
754
755 Picture. Minimal-area bounding rectangle for contour
756
757 \includegraphics[width=0.5\textwidth]{pics/minareabox.png}
758
759 \cvCPyFunc{MinEnclosingCircle}
760 Finds the circumscribed circle of minimal area for a given 2D point set.
761
762 \cvdefC{
763 int cvMinEnclosingCircle( \par const CvArr* points,\par CvPoint2D32f* center,\par float* radius );
764 }
765 \cvdefPy{MinEnclosingCircle(points)-> (int,center,radius)}
766
767 \begin{description}
768 \cvarg{points}{Sequence or array of 2D points}
769 \cvarg{center}{Output parameter; the center of the enclosing circle}
770 \cvarg{radius}{Output parameter; the radius of the enclosing circle}
771 \end{description}
772
773 The function finds the minimal circumscribed
774 circle for a 2D point set using an iterative algorithm. It returns nonzero
775 if the resultant circle contains all the input points and zero otherwise
776 (i.e. the algorithm failed).
777
778 \cvCPyFunc{Moments}
779 Calculates all of the moments up to the third order of a polygon or rasterized shape.
780
781 \cvdefC{
782 void cvMoments( \par const CvArr* arr,\par CvMoments* moments,\par int binary=0 );
783 }
784 \cvdefPy{Moments(arr, binary = 0) -> moments}
785
786 \begin{description}
787 \cvarg{arr}{Image (1-channel or 3-channel with COI set) or polygon (CvSeq of points or a vector of points)}
788 \cvarg{moments}{Pointer to returned moment's state structure}
789 \cvarg{binary}{(For images only) If the flag is non-zero, all of the zero pixel values are treated as zeroes, and all of the others are treated as 1's}
790 \end{description}
791
792 The function calculates spatial and central moments up to the third order and writes them to \texttt{moments}. The moments may then be used then to calculate the gravity center of the shape, its area, main axises and various shape characeteristics including 7 Hu invariants.
793
794 \cvCPyFunc{PointPolygonTest}
795 Point in contour test.
796
797 \cvdefC{
798 double cvPointPolygonTest( \par const CvArr* contour,\par CvPoint2D32f pt,\par int measure\_dist );
799 }\cvdefPy{PointPolygonTest(contour,pt,measure\_dist)-> double}
800
801 \begin{description}
802 \cvarg{contour}{Input contour}
803 \cvarg{pt}{The point tested against the contour}
804 \cvarg{measure\_dist}{If it is non-zero, the function estimates the distance from the point to the nearest contour edge}
805 \end{description}
806
807 The function determines whether the
808 point is inside a contour, outside, or lies on an edge (or coinsides
809 with a vertex). It returns positive, negative or zero value,
810 correspondingly. When $\texttt{measure\_dist} =0$, the return value
811 is +1, -1 and 0, respectively. When $\texttt{measure\_dist} \ne 0$,
812 it is a signed distance between the point and the nearest contour
813 edge.
814
815 Here is the sample output of the function, where each image pixel is tested against the contour.
816
817 \includegraphics[width=0.5\textwidth]{pics/pointpolygon.png}
818
819 \ifC
820
821 \cvCPyFunc{PointSeqFromMat}
822 Initializes a point sequence header from a point vector.
823
824 \cvdefC{
825 CvSeq* cvPointSeqFromMat( \par int seq\_kind,\par const CvArr* mat,\par CvContour* contour\_header,\par CvSeqBlock* block );
826 }
827
828 \begin{description}
829 \cvarg{seq\_kind}{Type of the point sequence: point set (0), a curve (\texttt{CV\_SEQ\_KIND\_CURVE}), closed curve (\texttt{CV\_SEQ\_KIND\_CURVE+CV\_SEQ\_FLAG\_CLOSED}) etc.}
830 \cvarg{mat}{Input matrix. It should be a continuous, 1-dimensional vector of points, that is, it should have type \texttt{CV\_32SC2} or \texttt{CV\_32FC2}}
831 \cvarg{contour\_header}{Contour header, initialized by the function}
832 \cvarg{block}{Sequence block header, initialized by the function}
833 \end{description}
834
835 The function initializes a sequence
836 header to create a "virtual" sequence in which elements reside in
837 the specified matrix. No data is copied. The initialized sequence
838 header may be passed to any function that takes a point sequence
839 on input. No extra elements can be added to the sequence,
840 but some may be removed. The function is a specialized variant of
841 \cvCPyCross{MakeSeqHeaderForArray} and uses
842 the latter internally. It returns a pointer to the initialized contour
843 header. Note that the bounding rectangle (field \texttt{rect} of
844 \texttt{CvContour} strucuture) is not initialized by the function. If
845 you need one, use \cvCPyCross{BoundingRect}.
846
847 Here is a simple usage example.
848
849 \begin{lstlisting}
850 CvContour header;
851 CvSeqBlock block;
852 CvMat* vector = cvCreateMat( 1, 3, CV_32SC2 );
853
854 CV_MAT_ELEM( *vector, CvPoint, 0, 0 ) = cvPoint(100,100);
855 CV_MAT_ELEM( *vector, CvPoint, 0, 1 ) = cvPoint(100,200);
856 CV_MAT_ELEM( *vector, CvPoint, 0, 2 ) = cvPoint(200,100);
857
858 IplImage* img = cvCreateImage( cvSize(300,300), 8, 3 );
859 cvZero(img);
860
861 cvDrawContours( img,
862     cvPointSeqFromMat(CV_SEQ_KIND_CURVE+CV_SEQ_FLAG_CLOSED,
863                       vector,
864                       &header,
865                       &block),
866                 CV_RGB(255,0,0),
867                 CV_RGB(255,0,0),
868                 0, 3, 8, cvPoint(0,0));
869 \end{lstlisting}
870
871
872 \cvCPyFunc{ReadChainPoint}
873 Gets the next chain point.
874
875 \cvdefC{
876 CvPoint cvReadChainPoint( CvChainPtReader* reader );
877 }
878
879 \begin{description}
880 \cvarg{reader}{Chain reader state}
881 \end{description}
882
883 The function returns the current chain point and updates the reader position.
884
885 \cvCPyFunc{StartFindContours}
886 Initializes the contour scanning process.
887
888 \cvdefC{
889 CvContourScanner cvStartFindContours(\par CvArr* image,\par CvMemStorage* storage,\par
890                                       int header\_size=sizeof(CvContour),\par
891                                       int mode=CV\_RETR\_LIST,\par
892                                       int method=CV\_CHAIN\_APPROX\_SIMPLE,\par
893                                       CvPoint offset=cvPoint(0,\par0) );
894 }
895
896 \begin{description}
897 \cvarg{image}{The 8-bit, single channel, binary source image}
898 \cvarg{storage}{Container of the retrieved contours}
899 \cvarg{header\_size}{Size of the sequence header, $>=sizeof(CvChain)$ if \texttt{method} =CV\_CHAIN\_CODE, and $>=sizeof(CvContour)$ otherwise}
900 \cvarg{mode}{Retrieval mode; see \cvCPyCross{FindContours}}
901 \cvarg{method}{Approximation method. It has the same meaning in \cvCPyCross{FindContours}, but \texttt{CV\_LINK\_RUNS} can not be used here}
902 \cvarg{offset}{ROI offset; see \cvCPyCross{FindContours}}
903 \end{description}
904
905 The function initializes and returns a pointer to the contour scanner. The scanner is used in \cvCPyCross{FindNextContour} to retrieve the rest of the contours.
906
907 \cvCPyFunc{StartReadChainPoints}
908 Initializes the chain reader.
909
910 \cvdefC{
911 void cvStartReadChainPoints( CvChain* chain, CvChainPtReader* reader );
912 }
913
914 The function initializes a special reader.
915
916 \cvCPyFunc{SubstituteContour}
917 Replaces a retrieved contour.
918
919 \cvdefC{
920 void cvSubstituteContour( \par CvContourScanner scanner, \par CvSeq* new\_contour );
921 }
922
923 \begin{description}
924 \cvarg{scanner}{Contour scanner initialized by \cvCPyCross{StartFindContours} }
925 \cvarg{new\_contour}{Substituting contour}
926 \end{description}
927
928 The function replaces the retrieved
929 contour, that was returned from the preceding call of
930 \cvCPyCross{FindNextContour} and stored inside the contour scanner
931 state, with the user-specified contour. The contour is inserted
932 into the resulting structure, list, two-level hierarchy, or tree,
933 depending on the retrieval mode. If the parameter \texttt{new\_contour}
934 is \texttt{NULL}, the retrieved contour is not included in the
935 resulting structure, nor are any of its children that might be added
936 to this structure later.
937
938 \fi
939
940 \fi
941
942
943 \ifCpp
944
945 \cvCppFunc{moments}
946 Calculates all of the moments up to the third order of a polygon or rasterized shape.
947
948 \cvdefCpp{Moments moments( const Mat\& array, bool binaryImage=false );}
949
950 where the class \texttt{Moments} is defined as:
951 \begin{lstlisting}
952 class Moments
953 {
954 public:
955     Moments();
956     Moments(double m00, double m10, double m01, double m20, double m11,
957             double m02, double m30, double m21, double m12, double m03 );
958     Moments( const CvMoments\& moments );
959     operator CvMoments() const;
960     
961     // spatial moments
962     double  m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
963     // central moments
964     double  mu20, mu11, mu02, mu30, mu21, mu12, mu03;
965     // central normalized moments
966     double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
967 };
968 \end{lstlisting}
969
970 \begin{description}
971 \cvarg{array}{A raster image (single-channel, 8-bit or floating-point 2D array) or an array
972     ($1 \times N$ or $N \times 1$) of 2D points (\texttt{Point} or \texttt{Point2f})}
973 \cvarg{binaryImage}{(For images only) If it is true, then all the non-zero image pixels are treated as 1's}
974 \end{description}
975
976 The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape.
977 In case of a raster image, the spatial moments $\texttt{Moments::m}_{ji}$ are computed as:
978
979 \[\texttt{m}_{ji}=\sum_{x,y} \left(\texttt{array}(x,y) \cdot x^j \cdot y^i\right),\]
980
981 the central moments $\texttt{Moments::mu}_{ji}$ are computed as:
982 \[\texttt{mu}_{ji}=\sum_{x,y} \left(\texttt{array}(x,y) \cdot (x - \bar{x})^j \cdot (y - \bar{y})^i\right)\]
983 where $(\bar{x}, \bar{y})$ is the mass center:
984
985 \[
986 \bar{x}=\frac{\texttt{m}_{10}}{\texttt{m}_{00}},\; \bar{y}=\frac{\texttt{m}_{01}}{\texttt{m}_{00}}
987 \]
988
989 and the normalized central moments $\texttt{Moments::nu}_{ij}$ are computed as:
990 \[\texttt{nu}_{ji}=\frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}}.\]
991
992 Note that $\texttt{mu}_{00}=\texttt{m}_{00}$, $\texttt{nu}_{00}=1$ $\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0$, hence the values are not stored.
993
994 The moments of a contour are defined in the same way, but computed using Green's formula
995 (see \url{http://en.wikipedia.org/wiki/Green_theorem}), therefore, because of a limited raster resolution, the moments computed for a contour will be slightly different from the moments computed for the same contour rasterized.
996
997 See also: \cvCppCross{contourArea}, \cvCppCross{arcLength}
998
999 \cvCppFunc{HuMoments}
1000 Calculates the seven Hu invariants.
1001
1002 \cvdefCpp{void HuMoments( const Moments\& moments, double h[7] );}
1003 \begin{description}
1004 \cvarg{moments}{The input moments, computed with \cvCppCross{moments}}
1005 \cvarg{h}{The output Hu invariants}
1006 \end{description}
1007
1008 The function calculates the seven Hu invariants, see \url{http://en.wikipedia.org/wiki/Image_moment}, that are defined as:
1009
1010 \[ \begin{array}{l}
1011 h[0]=\eta_{20}+\eta_{02}\\
1012 h[1]=(\eta_{20}-\eta_{02})^{2}+4\eta_{11}^{2}\\
1013 h[2]=(\eta_{30}-3\eta_{12})^{2}+ (3\eta_{21}-\eta_{03})^{2}\\
1014 h[3]=(\eta_{30}+\eta_{12})^{2}+ (\eta_{21}+\eta_{03})^{2}\\
1015 h[4]=(\eta_{30}-3\eta_{12})(\eta_{30}+\eta_{12})[(\eta_{30}+\eta_{12})^{2}-3(\eta_{21}+\eta_{03})^{2}]+(3\eta_{21}-\eta_{03})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]\\
1016 h[5]=(\eta_{20}-\eta_{02})[(\eta_{30}+\eta_{12})^{2}- (\eta_{21}+\eta_{03})^{2}]+4\eta_{11}(\eta_{30}+\eta_{12})(\eta_{21}+\eta_{03})\\
1017 h[6]=(3\eta_{21}-\eta_{03})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]-(\eta_{30}-3\eta_{12})(\eta_{21}+\eta_{03})[3(\eta_{30}+\eta_{12})^{2}-(\eta_{21}+\eta_{03})^{2}]\\
1018 \end{array}
1019 \]
1020
1021 where $\eta_{ji}$ stand for $\texttt{Moments::nu}_{ji}$.
1022
1023 These values are proved to be invariant to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. Of course, this invariance was proved with the assumption of infinite image resolution. In case of a raster images the computed Hu invariants for the original and transformed images will be a bit different.
1024
1025 See also: \cvCppCross{matchShapes}
1026
1027 \cvCppFunc{findContours}
1028 Finds the contours in a binary image.
1029
1030 \cvdefCpp{void findContours( const Mat\& image, vector<vector<Point> >\& contours,\par
1031                    vector<Vec4i>\& hierarchy, int mode,\par
1032                    int method, Point offset=Point());\newline
1033 void findContours( const Mat\& image, vector<vector<Point> >\& contours,\par
1034                    int mode, int method, Point offset=Point());
1035 }
1036 \begin{description}
1037 \cvarg{image}{The source, an 8-bit single-channel image. Non-zero pixels are treated as 1's, zero pixels remain 0's - the image is treated as \texttt{binary}. You can use \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{threshold}, \cvCppCross{adaptiveThreshold}, \cvCppCross{Canny} etc. to create a binary image out of a grayscale or color one. The function modifies the \texttt{image} while extracting the contours}
1038 \cvarg{contours}{The detected contours. Each contour is stored as a vector of points}
1039 \cvarg{hiararchy}{The optional output vector that will contain information about the image topology. It will have as many elements as the number of contours. For each contour \texttt{contours[i]}, the elements \texttt{hierarchy[i][0]}, \texttt{hiearchy[i][1]}, \texttt{hiearchy[i][2]}, \texttt{hiearchy[i][3]} will be set to 0-based indices in \texttt{contours} of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for some contour \texttt{i} there is no next, previous, parent or nested contours, the corresponding elements of \texttt{hierarchy[i]} will be negative}
1040 \cvarg{mode}{The contour retrieval mode
1041 \begin{description}
1042   \cvarg{CV\_RETR\_EXTERNAL}{retrieves only the extreme outer contours; It will set \texttt{hierarchy[i][2]=hierarchy[i][3]=-1} for all the contours}
1043   \cvarg{CV\_RETR\_LIST}{retrieves all of the contours without establishing any hierarchical relationships}
1044   \cvarg{CV\_RETR\_CCOMP}{retrieves all of the contours and organizes them into a two-level hierarchy: on the top level are the external boundaries of the components, on the second level are the boundaries of the holes. If inside a hole of a connected component there is another contour, it will still be put on the top level}
1045   \cvarg{CV\_RETR\_TREE}{retrieves all of the contours and reconstructs the full hierarchy of nested contours. This full hierarchy is built and shown in OpenCV \texttt{contours.c} demo}
1046 \end{description}}
1047 \cvarg{method}{The contour approximation method.
1048 \begin{description}
1049   \cvarg{CV\_CHAIN\_APPROX\_NONE}{stores absolutely all the contour points. That is, every 2 points of a contour stored with this method are 8-connected neighbors of each other}
1050   \cvarg{CV\_CHAIN\_APPROX\_SIMPLE}{compresses horizontal, vertical, and diagonal segments and leaves only their end points. E.g. an up-right rectangular contour will be encoded with 4 points}
1051   \cvarg{CV\_CHAIN\_APPROX\_TC89\_L1,CV\_CHAIN\_APPROX\_TC89\_KCOS}{applies one of the flavors of the Teh-Chin chain approximation algorithm; see \cite{TehChin89}}
1052 \end{description}}
1053 \cvarg{offset}{The optional offset, by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context}
1054 \end{description}
1055
1056 The function retrieves contours from the
1057 binary image using the algorithm \cite{Suzuki85}. The contours are a useful tool for shape analysis and object detection and recognition. See \texttt{squares.c} in the OpenCV sample directory.
1058
1059 \cvCppFunc{drawContours}
1060 Draws contours' outlines or filled contours.
1061
1062 \cvdefCpp{void drawContours( Mat\& image, const vector<vector<Point> >\& contours,\par
1063                    int contourIdx, const Scalar\& color, int thickness=1,\par
1064                    int lineType=8, const vector<Vec4i>\& hierarchy=vector<Vec4i>(),\par
1065                    int maxLevel=INT\_MAX, Point offset=Point() );}
1066 \begin{description}
1067 \cvarg{image}{The destination image}
1068 \cvarg{contours}{All the input contours. Each contour is stored as a point vector}
1069 \cvarg{contourIdx}{Indicates the contour to draw. If it is negative, all the contours are drawn}
1070 \cvarg{color}{The contours' color}
1071 \cvarg{thickness}{Thickness of lines the contours are drawn with.
1072 If it is negative (e.g. \texttt{thickness=CV\_FILLED}), the contour interiors are
1073 drawn.}
1074 \cvarg{lineType}{The line connectivity; see \cvCppCross{line} description}
1075 \cvarg{hierarchy}{The optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see \texttt{maxLevel})}
1076 \cvarg{maxLevel}{Maximal level for drawn contours. If 0, only
1077 the specified contour is drawn. If 1, the function draws the contour(s) and all the nested contours. If 2, the function draws the contours, all the nested contours and all the nested into nested contours etc. This parameter is only taken into account when there is \texttt{hierarchy} available.}
1078 \cvarg{offset}{The optional contour shift parameter. Shift all the drawn contours by the specified $\texttt{offset}=(dx,dy)$}
1079 \end{description}
1080
1081 The function draws contour outlines in the image if $\texttt{thickness} \ge 0$ or fills the area bounded by the contours if $ \texttt{thickness}<0$. Here is the example on how to retrieve connected components from the binary image and label them
1082
1083 \begin{lstlisting}
1084 #include "cv.h"
1085 #include "highgui.h"
1086
1087 using namespace cv;
1088
1089 int main( int argc, char** argv )
1090 {
1091     Mat src;
1092     // the first command line parameter must be file name of binary 
1093     // (black-n-white) image
1094     if( argc != 2 || !(src=imread(argv[1], 0)).data)
1095         return -1;
1096
1097     Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
1098
1099     src = src > 1;
1100     namedWindow( "Source", 1 );
1101     imshow( "Source", src );
1102
1103     vector<vector<Point> > contours;
1104     vector<Vec4i> hierarchy;
1105     
1106     findContours( src, contours, hierarchy, 
1107         CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
1108
1109     // iterate through all the top-level contours,
1110     // draw each connected component with its own random color
1111     int idx = 0;
1112     for( ; idx >= 0; idx = hiearchy[idx][0] )
1113     {
1114         Scalar color( rand()&255, rand()&255, rand()&255 );
1115         drawContours( dst, contours, idx, color, CV_FILLED, 8, hiearchy );
1116     }
1117
1118     namedWindow( "Components", 1 );
1119     imshow( "Components", dst );
1120     waitKey(0);
1121 }
1122 \end{lstlisting}
1123
1124
1125 \cvCppFunc{approxPolyDP}
1126 Approximates polygonal curve(s) with the specified precision.
1127
1128 \cvdefCpp{void approxPolyDP( const Mat\& curve,\par
1129                    vector<Point>\& approxCurve,\par
1130                    double epsilon, bool closed );\newline
1131 void approxPolyDP( const Mat\& curve,\par
1132                    vector<Point2f>\& approxCurve,\par
1133                    double epsilon, bool closed );}
1134 \begin{description}
1135 \cvarg{curve}{The polygon or curve to approximate. Must be $1 \times N$ or $N \times 1$ matrix of type \texttt{CV\_32SC2} or \texttt{CV\_32FC2}. You can also convert \texttt{vector<Point>} or \texttt{vector<Point2f} to the matrix by calling \texttt{Mat(const vector<T>\&)} constructor.}
1136 \cvarg{approxCurve}{The result of the approximation; The type should match the type of the input curve}
1137 \cvarg{epsilon}{Specifies the approximation accuracy. This is the maximum distance between the original curve and its approximation}
1138 \cvarg{closed}{If true, the approximated curve is closed (i.e. its first and last vertices are connected), otherwise it's not}
1139 \end{description}
1140
1141 The functions \texttt{approxPolyDP} approximate a curve or a polygon with another curve/polygon with less vertices, so that the distance between them is less or equal to the specified precision. It used Douglas-Peucker algorithm \url{http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm}
1142
1143 \cvCppFunc{arcLength}
1144 Calculates a contour perimeter or a curve length.
1145
1146 \cvdefCpp{double arcLength( const Mat\& curve, bool closed );}
1147 \begin{description}
1148 \cvarg{curve}{The input vector of 2D points, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to a matrix with \texttt{Mat(const vector<T>\&)} constructor}
1149 \cvarg{closed}{Indicates, whether the curve is closed or not}
1150 \end{description}
1151
1152 The function computes the curve length or the closed contour perimeter.
1153
1154 \cvCppFunc{boundingRect}
1155 Calculates the up-right bounding rectangle of a point set.
1156
1157 \cvdefCpp{Rect boundingRect( const Mat\& points );}
1158 \begin{description}
1159 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1160 \end{description}
1161
1162 The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
1163
1164
1165 \cvCppFunc{estimateRigidTransform}
1166 Computes optimal affine transformation between two 2D point sets
1167
1168 \cvdefCpp{Mat estimateRigidTransform( const Mat\& srcpt, const Mat\& dstpt,\par
1169                             bool fullAffine );}
1170 \begin{description}
1171 \cvarg{srcpt}{The first input 2D point set}
1172 \cvarg{dst}{The second input 2D point set of the same size and the same type as \texttt{A}}
1173 \cvarg{fullAffine}{If true, the function finds the optimal affine transformation with no any additional resrictions (i.e. there are 6 degrees of freedom); otherwise, the class of transformations to choose from is limited to combinations of translation, rotation and uniform scaling (i.e. there are 5 degrees of freedom)}
1174 \end{description}
1175
1176 The function finds the optimal affine transform $[A|b]$ (a $2 \times 3$ floating-point matrix) that approximates best the transformation from $\texttt{srcpt}_i$ to $\texttt{dstpt}_i$:
1177
1178 \[ [A^*|b^*] = arg \min_{[A|b]} \sum_i \|\texttt{dstpt}_i - A {\texttt{srcpt}_i}^T - b \|^2 \]
1179
1180 where $[A|b]$ can be either arbitrary (when \texttt{fullAffine=true}) or have form
1181 \[\begin{bmatrix}a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\] when \texttt{fullAffine=false}.
1182
1183 See also: \cvCppCross{getAffineTransform}, \cvCppCross{getPerspectiveTransform}, \cvCppCross{findHomography}
1184
1185 \cvCppFunc{estimateAffine3D}
1186 Computes optimal affine transformation between two 3D point sets
1187
1188 \cvdefCpp{int estimateAffine3D(const Mat\& srcpt, const Mat\& dstpt, Mat\& out,\par
1189                      vector<uchar>\& outliers,\par
1190                      double ransacThreshold = 3.0,\par
1191                      double confidence = 0.99);}
1192 \begin{description}
1193 \cvarg{srcpt}{The first input 3D point set}
1194 \cvarg{dstpt}{The second input 3D point set}
1195 \cvarg{out}{The output 3D affine transformation matrix $3 \times 4$}
1196 \cvarg{outliers}{The output vector indicating which points are outliers}
1197 \cvarg{ransacThreshold}{The maximum reprojection error in RANSAC algorithm to consider a point an inlier}
1198 \cvarg{confidence}{The confidence level, between 0 and 1, with which the matrix is estimated}
1199 \end{description}
1200
1201 The function estimates the optimal 3D affine transformation between two 3D point sets using RANSAC algorithm.
1202
1203
1204 \cvCppFunc{contourArea}
1205 Calculates the contour area
1206
1207 \cvdefCpp{double contourArea( const Mat\& contour );    }
1208 \begin{description}
1209 \cvarg{contour}{The contour vertices, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1210 \end{description}
1211
1212 The function computes the contour area. Similarly to \cvCppCross{moments} the area is computed using the Green formula, thus the returned area and the number of non-zero pixels, if you draw the contour using \cvCppCross{drawContours} or \cvCppCross{fillPoly}, can be different.
1213 Here is a short example:
1214
1215 \begin{lstlisting}
1216 vector<Point> contour;
1217 contour.push_back(Point2f(0, 0));
1218 contour.push_back(Point2f(10, 0));
1219 contour.push_back(Point2f(10, 10));
1220 contour.push_back(Point2f(5, 4));
1221
1222 double area0 = contourArea(contour);
1223 vector<Point> approx;
1224 approxPolyDP(contour, approx, 5, true);
1225 double area1 = contourArea(approx);
1226
1227 cout << "area0 =" << area0 << endl <<
1228         "area1 =" << area1 << endl <<
1229         "approx poly vertices" << approx.size() << endl; 
1230 \end{lstlisting}
1231
1232 \cvCppFunc{convexHull}    
1233 Finds the convex hull of a point set.
1234
1235 \cvdefCpp{void convexHull( const Mat\& points, vector<int>\& hull,\par
1236                  bool clockwise=false );\newline
1237 void convexHull( const Mat\& points, vector<Point>\& hull,\par
1238                  bool clockwise=false );\newline
1239 void convexHull( const Mat\& points, vector<Point2f>\& hull,\par
1240                  bool clockwise=false );}
1241 \begin{description}
1242 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1243 \cvarg{hull}{The output convex hull. It is either a vector of points that form the hull, or a vector of 0-based point indices of the hull points in the original array (since the set of convex hull points is a subset of the original point set).}
1244 \cvarg{clockwise}{If true, the output convex hull will be oriented clockwise, otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate system is assumed - the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.}
1245 \end{description}
1246
1247 The functions find the convex hull of a 2D point set using Sklansky's algorithm \cite{Sklansky82} that has $O(N logN)$ or $O(N)$ complexity (where $N$ is the number of input points), depending on how the initial sorting is implemented (currently it is $O(N logN)$. See the OpenCV sample \texttt{convexhull.c} that demonstrates the use of the different function variants. 
1248
1249
1250 \cvCppFunc{fitEllipse}
1251 Fits an ellipse around a set of 2D points.
1252
1253 \cvdefCpp{RotatedRect fitEllipse( const Mat\& points );}
1254 \begin{description}
1255 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1256 \end{description}
1257
1258 The function calculates the ellipse that fits best
1259 (in least-squares sense) a set of 2D points. It returns the rotated rectangle in which the ellipse is inscribed.
1260
1261 \cvCppFunc{fitLine}
1262 Fits a line to a 2D or 3D point set.
1263
1264 \cvdefCpp{void fitLine( const Mat\& points, Vec4f\& line, int distType,\par
1265               double param, double reps, double aeps );\newline
1266 void fitLine( const Mat\& points, Vec6f\& line, int distType,\par
1267               double param, double reps, double aeps );}
1268 \begin{description}
1269 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by
1270 \texttt{vector<Point>}, \texttt{vector<Point2f>}, \texttt{vector<Point3i>} or \texttt{vector<Point3f>} converted to the matrix by \texttt{Mat(const vector<T>\&)} constructor}
1271 \cvarg{line}{The output line parameters. In the case of a 2d fitting,
1272 it is a vector of 4 floats \texttt{(vx, vy,
1273 x0, y0)} where \texttt{(vx, vy)} is a normalized vector collinear to the
1274 line and \texttt{(x0, y0)} is some point on the line. in the case of a
1275 3D fitting it is vector of 6 floats \texttt{(vx, vy, vz, x0, y0, z0)}
1276 where \texttt{(vx, vy, vz)} is a normalized vector collinear to the line
1277 and \texttt{(x0, y0, z0)} is some point on the line}
1278 \cvarg{distType}{The distance used by the M-estimator (see the discussion)}
1279 \cvarg{param}{Numerical parameter (\texttt{C}) for some types of distances, if 0 then some optimal value is chosen}
1280 \cvarg{reps, aeps}{Sufficient accuracy for the radius (distance between the coordinate origin and the line) and angle, respectively; 0.01 would be a good default value for both.}
1281 \end{description}
1282
1283 The functions \texttt{fitLine} fit a line to a 2D or 3D point set by minimizing $\sum_i \rho(r_i)$ where $r_i$ is the distance between the $i^{th}$ point and the line and $\rho(r)$ is a distance function, one of:
1284
1285 \begin{description}
1286 \item[distType=CV\_DIST\_L2]
1287 \[ \rho(r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)} \]
1288
1289 \item[distType=CV\_DIST\_L1]
1290 \[ \rho(r) = r \]
1291
1292 \item[distType=CV\_DIST\_L12]
1293 \[ \rho(r) = 2 \cdot (\sqrt{1 + \frac{r^2}{2}} - 1) \]
1294
1295 \item[distType=CV\_DIST\_FAIR]
1296 \[ \rho\left(r\right) = C^2 \cdot \left( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)}\right) \quad \text{where} \quad C=1.3998 \]
1297
1298 \item[distType=CV\_DIST\_WELSCH]
1299 \[ \rho\left(r\right) = \frac{C^2}{2} \cdot \left( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)}\right) \quad \text{where} \quad C=2.9846 \]
1300
1301 \item[distType=CV\_DIST\_HUBER]
1302 \[ \rho(r) = \fork
1303 {r^2/2}{if $r < C$}
1304 {C \cdot (r-C/2)}{otherwise}  \quad \text{where} \quad C=1.345
1305 \]
1306 \end{description}
1307
1308 The algorithm is based on the M-estimator (\url{http://en.wikipedia.org/wiki/M-estimator}) technique, that iteratively fits the line using weighted least-squares algorithm and after each iteration the weights $w_i$ are adjusted to beinversely proportional to $\rho(r_i)$. 
1309
1310
1311 \cvCppFunc{isContourConvex}
1312 Tests contour convexity.
1313
1314 \cvdefCpp{bool isContourConvex( const Mat\& contour );}
1315 \begin{description}
1316 \cvarg{contour}{The tested contour, a matrix of type \texttt{CV\_32SC2} or \texttt{CV\_32FC2}, or \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1317 \end{description}
1318
1319 The function tests whether the input contour is convex or not. The contour must be simple, i.e. without self-intersections, otherwise the function output is undefined.
1320
1321
1322 \cvCppFunc{minAreaRect}
1323 Finds the minimum area rotated rectangle enclosing a 2D point set.
1324
1325 \cvdefCpp{RotatedRect minAreaRect( const Mat\& points );}
1326 \begin{description}
1327 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1328 \end{description}
1329
1330 The function calculates and returns the minimum area bounding rectangle (possibly rotated) for the specified point set. See the OpenCV sample \texttt{minarea.c}
1331
1332 \cvCppFunc{minEnclosingCircle}
1333 Finds the minimum area circle enclosing a 2D point set.
1334
1335 \cvdefCpp{void minEnclosingCircle( const Mat\& points, Point2f\& center, float\& radius );    }
1336 \begin{description}
1337 \cvarg{points}{The input 2D point set, represented by \texttt{CV\_32SC2} or \texttt{CV\_32FC2} matrix, or by \texttt{vector<Point>} or \texttt{vector<Point2f>} converted to the matrix using \texttt{Mat(const vector<T>\&)} constructor.}
1338 \cvarg{center}{The output center of the circle}
1339 \cvarg{radius}{The output radius of the circle}
1340 \end{description}
1341
1342 The function finds the minimal enclosing circle of a 2D point set using iterative algorithm. See the OpenCV sample \texttt{minarea.c}
1343
1344 \cvCppFunc{matchShapes}
1345 Compares two shapes.
1346
1347 \cvdefCpp{double matchShapes( const Mat\& object1,\par
1348                     const Mat\& object2,\par
1349                     int method, double parameter=0 );}
1350 \begin{description}
1351 \cvarg{object1}{The first contour or grayscale image}
1352 \cvarg{object2}{The second contour or grayscale image}
1353 \cvarg{method}{Comparison method:
1354  \texttt{CV\_CONTOUR\_MATCH\_I1},\\ 
1355  \texttt{CV\_CONTOURS\_MATCH\_I2}\\ 
1356 or 
1357  \texttt{CV\_CONTOURS\_MATCH\_I3} (see the discussion below)}
1358 \cvarg{parameter}{Method-specific parameter (is not used now)}
1359 \end{description}
1360
1361 The function compares two shapes. The 3 implemented methods all use Hu invariants (see \cvCppCross{HuMoments}) as following ($A$ denotes \texttt{object1}, $B$ denotes \texttt{object2}):
1362
1363 \begin{description}
1364 \item[method=CV\_CONTOUR\_MATCH\_I1]
1365 \[ I_1(A,B) = \sum_{i=1...7} \left| \frac{1}{m^A_i} - \frac{1}{m^B_i} \right| \]
1366
1367 \item[method=CV\_CONTOUR\_MATCH\_I2]
1368 \[ I_2(A,B) = \sum_{i=1...7} \left| m^A_i - m^B_i \right| \]
1369
1370 \item[method=CV\_CONTOUR\_MATCH\_I3]
1371 \[ I_3(A,B) = \sum_{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| } \]
1372 \end{description}
1373
1374 where
1375
1376 \[
1377 \begin{array}{l}
1378 m^A_i = \mathrm{sign}(h^A_i) \cdot \log{h^A_i} \\
1379 m^B_i = \mathrm{sign}(h^B_i) \cdot \log{h^B_i}
1380 \end{array}
1381 \]
1382
1383 and $h^A_i, h^B_i$ are the Hu moments of $A$ and $B$ respectively.
1384
1385
1386 \cvCppFunc{pointPolygonTest}
1387 Performs point-in-contour test.
1388
1389 \cvdefCpp{double pointPolygonTest( const Mat\& contour,\par
1390                          Point2f pt, bool measureDist );}
1391 \begin{description}
1392 \cvarg{contour}{The input contour}
1393 \cvarg{pt}{The point tested against the contour}
1394 \cvarg{measureDist}{If true, the function estimates the signed distance from the point to the nearest contour edge; otherwise, the function only checks if the point is inside or not.}
1395 \end{description}
1396
1397 The function determines whether the
1398 point is inside a contour, outside, or lies on an edge (or coincides
1399 with a vertex). It returns positive (inside), negative (outside) or zero (on an edge) value,
1400 correspondingly. When \texttt{measureDist=false}, the return value
1401 is +1, -1 and 0, respectively. Otherwise, the return value
1402 it is a signed distance between the point and the nearest contour
1403 edge.
1404
1405 Here is the sample output of the function, where each image pixel is tested against the contour.
1406
1407 \includegraphics[width=0.5\textwidth]{pics/pointpolygon.png}
1408
1409 \fi