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