CLAHE Python bindings
[profile/ivi/opencv.git] / modules / imgproc / doc / structural_analysis_and_shape_descriptors.rst
1 Structural Analysis and Shape Descriptors
2 =========================================
3
4 .. highlight:: cpp
5
6 moments
7 -----------
8 Calculates all of the moments up to the third order of a polygon or rasterized shape.
9
10 .. ocv:function:: Moments moments( InputArray array, bool binaryImage=false )
11
12 .. ocv:pyfunction:: cv2.moments(array[, binaryImage]) -> retval
13
14 .. ocv:cfunction:: void cvMoments( const CvArr* arr, CvMoments* moments, int binary=0 )
15
16 .. ocv:pyoldfunction:: cv.Moments(arr, binary=0) -> moments
17
18     :param array: Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( :math:`1 \times N`  or  :math:`N \times 1` ) of 2D points (``Point``  or  ``Point2f`` ).
19
20     :param binaryImage: If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only.
21
22     :param moments: Output moments.
23
24 The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The results are returned in the structure ``Moments`` defined as: ::
25
26     class Moments
27     {
28     public:
29         Moments();
30         Moments(double m00, double m10, double m01, double m20, double m11,
31                 double m02, double m30, double m21, double m12, double m03 );
32         Moments( const CvMoments& moments );
33         operator CvMoments() const;
34
35         // spatial moments
36         double  m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
37         // central moments
38         double  mu20, mu11, mu02, mu30, mu21, mu12, mu03;
39         // central normalized moments
40         double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
41     }
42
43 In case of a raster image, the spatial moments :math:`\texttt{Moments::m}_{ji}` are computed as:
44
45 .. math::
46
47     \texttt{m} _{ji}= \sum _{x,y}  \left ( \texttt{array} (x,y)  \cdot x^j  \cdot y^i \right )
48
49 The central moments
50 :math:`\texttt{Moments::mu}_{ji}` are computed as:
51
52 .. math::
53
54     \texttt{mu} _{ji}= \sum _{x,y}  \left ( \texttt{array} (x,y)  \cdot (x -  \bar{x} )^j  \cdot (y -  \bar{y} )^i \right )
55
56 where
57 :math:`(\bar{x}, \bar{y})` is the mass center:
58
59 .. math::
60
61     \bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}
62
63 The normalized central moments
64 :math:`\texttt{Moments::nu}_{ij}` are computed as:
65
66 .. math::
67
68     \texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .
69
70 .. note::
71
72     :math:`\texttt{mu}_{00}=\texttt{m}_{00}`,
73     :math:`\texttt{nu}_{00}=1`
74     :math:`\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0` , hence the values are not stored.
75
76 The moments of a contour are defined in the same way but computed using the Green's formula (see http://en.wikipedia.org/wiki/Green_theorem). So, due to a limited raster resolution, the moments computed for a contour are slightly different from the moments computed for the same rasterized contour.
77
78 .. note::
79
80      Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with self-intersections, e.g. a zero area (``m00``) for butterfly-shaped contours.
81
82 .. seealso::
83
84     :ocv:func:`contourArea`,
85     :ocv:func:`arcLength`
86
87
88
89 HuMoments
90 -------------
91 Calculates seven Hu invariants.
92
93 .. ocv:function:: void HuMoments( const Moments& m, OutputArray hu )
94
95 .. ocv:function:: void HuMoments( const Moments& moments, double hu[7] )
96
97 .. ocv:pyfunction:: cv2.HuMoments(m[, hu]) -> hu
98
99 .. ocv:cfunction:: void cvGetHuMoments( CvMoments* moments, CvHuMoments* hu_moments )
100
101 .. ocv:pyoldfunction:: cv.GetHuMoments(moments) -> hu
102
103     :param moments: Input moments computed with  :ocv:func:`moments` .
104     :param hu: Output Hu invariants.
105
106 The function calculates seven Hu invariants (introduced in [Hu62]_; see also
107 http://en.wikipedia.org/wiki/Image_moment) defined as:
108
109 .. math::
110
111     \begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[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}] \\ hu[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}) \\ hu[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}] \\ \end{array}
112
113 where
114 :math:`\eta_{ji}` stands for
115 :math:`\texttt{Moments::nu}_{ji}` .
116
117 These values are proved to be invariants to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of infinite image resolution. In case of raster images, the computed Hu invariants for the original and transformed images are a bit different.
118
119 .. seealso:: :ocv:func:`matchShapes`
120
121
122 findContours
123 ----------------
124 Finds contours in a binary image.
125
126 .. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
127
128 .. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())
129
130 .. ocv:pyfunction:: cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> contours, hierarchy
131
132 .. ocv:cfunction:: int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** first_contour, int header_size=sizeof(CvContour), int mode=CV_RETR_LIST, int method=CV_CHAIN_APPROX_SIMPLE, CvPoint offset=cvPoint(0,0) )
133
134 .. ocv:pyoldfunction:: cv.FindContours(image, storage, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE, offset=(0, 0)) -> contours
135
136     :param image: Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as  ``binary`` . You can use  :ocv:func:`compare` ,  :ocv:func:`inRange` ,  :ocv:func:`threshold` ,  :ocv:func:`adaptiveThreshold` ,  :ocv:func:`Canny` , and others to create a binary image out of a grayscale or color one. The function modifies the  ``image``  while extracting the contours.
137
138     :param contours: Detected contours. Each contour is stored as a vector of points.
139
140     :param hierarchy: Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour  ``contours[i]`` , the elements  ``hierarchy[i][0]`` ,  ``hiearchy[i][1]`` ,  ``hiearchy[i][2]`` , and  ``hiearchy[i][3]``  are set to 0-based indices in  ``contours``  of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour  ``i``  there are no next, previous, parent, or nested contours, the corresponding elements of  ``hierarchy[i]``  will be negative.
141
142     :param mode: Contour retrieval mode (if you use Python see also a note below).
143
144             * **CV_RETR_EXTERNAL** retrieves only the extreme outer contours. It sets  ``hierarchy[i][2]=hierarchy[i][3]=-1``  for all the contours.
145
146             * **CV_RETR_LIST** retrieves all of the contours without establishing any hierarchical relationships.
147
148             * **CV_RETR_CCOMP** retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level.
149
150             * **CV_RETR_TREE** retrieves all of the contours and reconstructs a full hierarchy of nested contours. This full hierarchy is built and shown in the OpenCV  ``contours.c``  demo.
151
152     :param method: Contour approximation method (if you use Python see also a note below).
153
154             * **CV_CHAIN_APPROX_NONE** stores absolutely all the contour points. That is, any 2 subsequent points ``(x1,y1)`` and ``(x2,y2)`` of the contour will be either horizontal, vertical or diagonal neighbors, that is, ``max(abs(x1-x2),abs(y2-y1))==1``.
155
156             * **CV_CHAIN_APPROX_SIMPLE** compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points.
157
158             * **CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS** applies one of the flavors of the Teh-Chin chain approximation algorithm. See  [TehChin89]_ for details.
159
160     :param offset: 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.
161
162 The function retrieves contours from the binary image using the algorithm
163 [Suzuki85]_. The contours are a useful tool for shape analysis and object detection and recognition. See ``squares.c`` in the OpenCV sample directory.
164
165 .. note:: Source ``image`` is modified by this function. Also, the function does not take into account 1-pixel border of the image (it's filled with 0's and used for neighbor analysis in the algorithm), therefore the contours touching the image border will be clipped.
166
167 .. note:: If you use the new Python interface then the ``CV_`` prefix has to be omitted in contour retrieval mode and contour approximation method parameters (for example, use ``cv2.RETR_LIST`` and ``cv2.CHAIN_APPROX_NONE`` parameters). If you use the old Python interface then these parameters have the ``CV_`` prefix (for example, use ``cv.CV_RETR_LIST`` and ``cv.CV_CHAIN_APPROX_NONE``).
168
169 drawContours
170 ----------------
171 Draws contours outlines or filled contours.
172
173 .. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours,                   int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
174
175 .. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None
176
177 .. ocv:cfunction:: void cvDrawContours( CvArr *img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )
178 .. ocv:pyoldfunction:: cv.DrawContours(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0))-> None
179
180     :param image: Destination image.
181
182     :param contours: All the input contours. Each contour is stored as a point vector.
183
184     :param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
185
186     :param color: Color of the contours.
187
188     :param thickness: Thickness of lines the contours are drawn with. If it is negative (for example,  ``thickness=CV_FILLED`` ), the contour interiors are
189         drawn.
190
191     :param lineType: Line connectivity. See  :ocv:func:`line`  for details.
192
193     :param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see  ``maxLevel`` ).
194
195     :param maxLevel: Maximal level for drawn contours. If it is 0, only
196         the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is  ``hierarchy``  available.
197
198     :param offset: Optional contour shift parameter. Shift all the drawn contours by the specified  :math:`\texttt{offset}=(dx,dy)` .
199
200     :param contour: Pointer to the first contour.
201
202     :param externalColor: Color of external contours.
203
204     :param holeColor: Color of internal contours (holes).
205
206 The function draws contour outlines in the image if
207 :math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
208 :math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
209
210     #include "cv.h"
211     #include "highgui.h"
212
213     using namespace cv;
214
215     int main( int argc, char** argv )
216     {
217         Mat src;
218         // the first command-line parameter must be a filename of the binary
219         // (black-n-white) image
220         if( argc != 2 || !(src=imread(argv[1], 0)).data)
221             return -1;
222
223         Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
224
225         src = src > 1;
226         namedWindow( "Source", 1 );
227         imshow( "Source", src );
228
229         vector<vector<Point> > contours;
230         vector<Vec4i> hierarchy;
231
232         findContours( src, contours, hierarchy,
233             CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
234
235         // iterate through all the top-level contours,
236         // draw each connected component with its own random color
237         int idx = 0;
238         for( ; idx >= 0; idx = hierarchy[idx][0] )
239         {
240             Scalar color( rand()&255, rand()&255, rand()&255 );
241             drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
242         }
243
244         namedWindow( "Components", 1 );
245         imshow( "Components", dst );
246         waitKey(0);
247     }
248
249
250
251 approxPolyDP
252 ----------------
253 Approximates a polygonal curve(s) with the specified precision.
254
255 .. ocv:function:: void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed )
256
257 .. ocv:pyfunction:: cv2.approxPolyDP(curve, epsilon, closed[, approxCurve]) -> approxCurve
258
259 .. ocv:cfunction:: CvSeq* cvApproxPoly( const void* src_seq, int header_size, CvMemStorage* storage, int method, double eps, int recursive=0 )
260
261     :param curve: Input vector of a 2D point stored in:
262
263         * ``std::vector`` or ``Mat`` (C++ interface)
264
265         * ``Nx2`` numpy array (Python interface)
266
267         * ``CvSeq`` or `` ``CvMat`` (C interface)
268
269     :param approxCurve: Result of the approximation. The type should match the type of the input curve. In case of C interface the approximated curve is stored in the memory storage and pointer to it is returned.
270
271     :param epsilon: Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation.
272
273     :param closed: If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed.
274
275     :param header_size: Header size of the approximated curve. Normally, ``sizeof(CvContour)`` is used.
276
277     :param storage: Memory storage where the approximated curve is stored.
278
279     :param method: Contour approximation algorithm. Only ``CV_POLY_APPROX_DP`` is supported.
280
281     :param recursive: Recursion flag. If it is non-zero and ``curve`` is ``CvSeq*``, the function ``cvApproxPoly`` approximates all the contours accessible from ``curve`` by ``h_next`` and ``v_next`` links.
282
283 The functions ``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 uses the Douglas-Peucker algorithm
284 http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
285
286 See http://code.opencv.org/projects/opencv/repository/revisions/master/entry/samples/cpp/contours.cpp for the function usage model.
287
288
289 ApproxChains
290 -------------
291 Approximates Freeman chain(s) with a polygonal curve.
292
293 .. ocv:cfunction:: CvSeq* cvApproxChains( CvSeq* src_seq, CvMemStorage* storage, int method=CV_CHAIN_APPROX_SIMPLE, double parameter=0, int minimal_perimeter=0, int recursive=0 )
294
295 .. ocv:pyoldfunction:: cv.ApproxChains(src_seq, storage, method=CV_CHAIN_APPROX_SIMPLE, parameter=0, minimal_perimeter=0, recursive=0)-> contours
296
297     :param src_seq: Pointer to the approximated Freeman chain that can refer to other chains.
298
299     :param storage: Storage location for the resulting polylines.
300
301     :param method: Approximation method (see the description of the function  :ocv:cfunc:`FindContours` ).
302
303     :param parameter: Method parameter (not used now).
304
305     :param minimal_perimeter: Approximates only those contours whose perimeters are not less than  ``minimal_perimeter`` . Other chains are removed from the resulting structure.
306
307     :param recursive: Recursion flag. If it is non-zero, the function approximates all chains that can be obtained from  ``chain``  by using the  ``h_next``  or  ``v_next`` links. Otherwise, the single input chain is approximated.
308
309 This is a standalone contour approximation routine, not represented in the new interface. When :ocv:cfunc:`FindContours` retrieves contours as Freeman chains, it calls the function to get approximated contours, represented as polygons.
310
311
312 arcLength
313 -------------
314 Calculates a contour perimeter or a curve length.
315
316 .. ocv:function:: double arcLength( InputArray curve, bool closed )
317
318 .. ocv:pyfunction:: cv2.arcLength(curve, closed) -> retval
319
320 .. ocv:cfunction:: double cvArcLength( const void* curve, CvSlice slice=CV_WHOLE_SEQ, int is_closed=-1 )
321
322 .. ocv:pyoldfunction:: cv.ArcLength(curve, slice=CV_WHOLE_SEQ, isClosed=-1) -> float
323
324     :param curve: Input vector of 2D points, stored in ``std::vector`` or ``Mat``.
325
326     :param closed: Flag indicating whether the curve is closed or not.
327
328 The function computes a curve length or a closed contour perimeter.
329
330
331
332 boundingRect
333 ----------------
334 Calculates the up-right bounding rectangle of a point set.
335
336 .. ocv:function:: Rect boundingRect( InputArray points )
337
338 .. ocv:pyfunction:: cv2.boundingRect(points) -> retval
339
340 .. ocv:cfunction:: CvRect cvBoundingRect( CvArr* points, int update=0 )
341 .. ocv:pyoldfunction:: cv.BoundingRect(points, update=0)-> CvRect
342
343     :param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
344
345 The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
346
347
348
349
350 contourArea
351 ---------------
352 Calculates a contour area.
353
354 .. ocv:function:: double contourArea( InputArray contour, bool oriented=false )
355
356 .. ocv:pyfunction:: cv2.contourArea(contour[, oriented]) -> retval
357
358 .. ocv:cfunction:: double cvContourArea( const CvArr* contour, CvSlice slice=CV_WHOLE_SEQ, int oriented=0 )
359
360 .. ocv:pyoldfunction:: cv.ContourArea(contour, slice=CV_WHOLE_SEQ) -> float
361
362     :param contour: Input vector of 2D points (contour vertices), stored in ``std::vector`` or ``Mat``.
363
364     :param oriented: Oriented area flag. If it is true, the function returns a signed area value, depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can determine orientation of a contour by taking the sign of an area. By default, the parameter is ``false``, which means that the absolute value is returned.
365
366 The function computes a contour area. Similarly to
367 :ocv:func:`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
368 :ocv:func:`drawContours` or
369 :ocv:func:`fillPoly` , can be different.
370 Also, the function will most certainly give a wrong results for contours with self-intersections.
371
372 Example: ::
373
374     vector<Point> contour;
375     contour.push_back(Point2f(0, 0));
376     contour.push_back(Point2f(10, 0));
377     contour.push_back(Point2f(10, 10));
378     contour.push_back(Point2f(5, 4));
379
380     double area0 = contourArea(contour);
381     vector<Point> approx;
382     approxPolyDP(contour, approx, 5, true);
383     double area1 = contourArea(approx);
384
385     cout << "area0 =" << area0 << endl <<
386             "area1 =" << area1 << endl <<
387             "approx poly vertices" << approx.size() << endl;
388
389
390
391 convexHull
392 --------------
393 Finds the convex hull of a point set.
394
395 .. ocv:function:: void convexHull( InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true )
396
397 .. ocv:pyfunction:: cv2.convexHull(points[, hull[, clockwise[, returnPoints]]]) -> hull
398
399 .. ocv:cfunction:: CvSeq* cvConvexHull2( const CvArr* input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0 )
400
401 .. ocv:pyoldfunction:: cv.ConvexHull2(points, storage, orientation=CV_CLOCKWISE, return_points=0) -> convexHull
402
403     :param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
404
405     :param hull: Output convex hull. It is either an integer vector of indices or vector of points. In the first case, the ``hull`` elements are 0-based indices of the convex hull points in the original array (since the set of convex hull points is a subset of the original point set). In the second case, ``hull`` elements are the convex hull points themselves.
406
407     :param hull_storage: Output memory storage in the old API (``cvConvexHull2`` returns a sequence containing the convex hull points or their indices).
408
409     :param clockwise: Orientation flag. If it is true, the output convex hull is oriented clockwise. Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing to the right, and its Y axis pointing upwards.
410
411     :param orientation: Convex hull orientation parameter in the old API, ``CV_CLOCKWISE`` or ``CV_COUNTERCLOCKWISE``.
412
413     :param returnPoints: Operation flag. In case of a matrix, when the flag is true, the function returns convex hull points. Otherwise, it returns indices of the convex hull points. When the output array is ``std::vector``, the flag is ignored, and the output depends on the type of the vector: ``std::vector<int>`` implies ``returnPoints=true``, ``std::vector<Point>`` implies ``returnPoints=false``.
414
415 The functions find the convex hull of a 2D point set using the Sklansky's algorithm
416 [Sklansky82]_
417 that has
418 *O(N logN)* complexity in the current implementation. See the OpenCV sample ``convexhull.cpp`` that demonstrates the usage of different function variants.
419
420
421 convexityDefects
422 ----------------
423 Finds the convexity defects of a contour.
424
425 .. ocv:function:: void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects )
426
427 .. ocv:pyfunction:: cv2.convexityDefects(contour, convexhull[, convexityDefects]) -> convexityDefects
428
429 .. ocv:cfunction:: CvSeq* cvConvexityDefects(  const CvArr* contour, const CvArr* convexhull, CvMemStorage* storage=NULL )
430
431 .. ocv:pyoldfunction:: cv.ConvexityDefects(contour, convexhull, storage)-> convexityDefects
432
433     :param contour: Input contour.
434
435     :param convexhull: Convex hull obtained using  :ocv:func:`convexHull`  that should contain indices of the contour points that make the hull.
436
437     :param convexityDefects: The output vector of convexity defects. In C++ and the new Python/Java interface each convexity defect is represented as 4-element integer vector (a.k.a. ``cv::Vec4i``): ``(start_index, end_index, farthest_pt_index, fixpt_depth)``, where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and ``fixpt_depth`` is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be ``fixpt_depth/256.0``. In C interface convexity defect is represented by ``CvConvexityDefect`` structure - see below.
438
439     :param storage: Container for the output sequence of convexity defects. If it is NULL, the contour or hull (in that order) storage is used.
440
441 The function finds all convexity defects of the input contour and returns a sequence of the ``CvConvexityDefect`` structures, where ``CvConvexityDetect`` is defined as: ::
442
443      struct CvConvexityDefect
444      {
445         CvPoint* start; // point of the contour where the defect begins
446         CvPoint* end; // point of the contour where the defect ends
447         CvPoint* depth_point; // the farthest from the convex hull point within the defect
448         float depth; // distance between the farthest point and the convex hull
449      };
450
451 The figure below displays convexity defects of a hand contour:
452
453 .. image:: pics/defects.png
454
455 fitEllipse
456 --------------
457 Fits an ellipse around a set of 2D points.
458
459 .. ocv:function:: RotatedRect fitEllipse( InputArray points )
460
461 .. ocv:pyfunction:: cv2.fitEllipse(points) -> retval
462
463 .. ocv:cfunction:: CvBox2D cvFitEllipse2( const CvArr* points )
464 .. ocv:pyoldfunction:: cv.FitEllipse2(points)-> Box2D
465
466     :param points: Input 2D point set, stored in:
467
468         * ``std::vector<>`` or ``Mat`` (C++ interface)
469
470         * ``CvSeq*`` or ``CvMat*`` (C interface)
471
472         * Nx2 numpy array (Python interface)
473
474 The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used.
475
476 fitLine
477 -----------
478 Fits a line to a 2D or 3D point set.
479
480 .. ocv:function:: void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps )
481
482 .. ocv:pyfunction:: cv2.fitLine(points, distType, param, reps, aeps[, line]) -> line
483
484 .. ocv:cfunction:: void cvFitLine( const CvArr* points, int dist_type, double param, double reps, double aeps, float* line )
485
486 .. ocv:pyoldfunction:: cv.FitLine(points, dist_type, param, reps, aeps) -> line
487
488     :param points: Input vector of 2D or 3D points, stored in ``std::vector<>`` or ``Mat``.
489
490     :param line: Output line parameters. In case of 2D fitting, it should be a vector of 4 elements (like ``Vec4f``) - ``(vx, vy, x0, y0)``,  where  ``(vx, vy)``  is a normalized vector collinear to the line and  ``(x0, y0)``  is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like  ``Vec6f``) - ``(vx, vy, vz, x0, y0, z0)``, where ``(vx, vy, vz)`` is a normalized vector collinear to the line and ``(x0, y0, z0)`` is a point on the line.
491
492     :param distType: Distance used by the M-estimator (see the discussion below).
493
494     :param param: Numerical parameter ( ``C`` ) for some types of distances. If it is 0, an optimal value is chosen.
495
496     :param reps: Sufficient accuracy for the radius (distance between the coordinate origin and the line).
497
498     :param aeps: Sufficient accuracy for the angle. 0.01 would be a good default value for ``reps`` and ``aeps``.
499
500 The function ``fitLine`` fits a line to a 2D or 3D point set by minimizing
501 :math:`\sum_i \rho(r_i)` where
502 :math:`r_i` is a distance between the
503 :math:`i^{th}` point, the line and
504 :math:`\rho(r)` is a distance function, one of the following:
505
506 * distType=CV\_DIST\_L2
507
508     .. math::
509
510         \rho (r) = r^2/2  \quad \text{(the simplest and the fastest least-squares method)}
511
512 * distType=CV\_DIST\_L1
513
514     .. math::
515
516         \rho (r) = r
517
518 * distType=CV\_DIST\_L12
519
520     .. math::
521
522         \rho (r) = 2  \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)
523
524 * distType=CV\_DIST\_FAIR
525
526     .. math::
527
528         \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
529
530 * distType=CV\_DIST\_WELSCH
531
532     .. math::
533
534         \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
535
536 * distType=CV\_DIST\_HUBER
537
538     .. math::
539
540         \rho (r) =  \fork{r^2/2}{if $r < C$}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345
541
542 The algorithm is based on the M-estimator (
543 http://en.wikipedia.org/wiki/M-estimator
544 ) technique that iteratively fits the line using the weighted least-squares algorithm. After each iteration the weights
545 :math:`w_i` are adjusted to be inversely proportional to
546 :math:`\rho(r_i)` .
547
548
549
550 isContourConvex
551 -------------------
552 Tests a contour convexity.
553
554 .. ocv:function:: bool isContourConvex( InputArray contour )
555
556 .. ocv:pyfunction:: cv2.isContourConvex(contour) -> retval
557
558 .. ocv:cfunction:: int cvCheckContourConvexity( const CvArr* contour )
559 .. ocv:pyoldfunction:: cv.CheckContourConvexity(contour)-> int
560
561     :param contour: Input vector of 2D points, stored in:
562
563             * ``std::vector<>`` or ``Mat`` (C++ interface)
564
565             * ``CvSeq*`` or ``CvMat*`` (C interface)
566
567             * Nx2 numpy array (Python interface)
568
569 The function tests whether the input contour is convex or not. The contour must be simple, that is, without self-intersections. Otherwise, the function output is undefined.
570
571
572
573 minAreaRect
574 ---------------
575 Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
576
577 .. ocv:function:: RotatedRect minAreaRect( InputArray points )
578
579 .. ocv:pyfunction:: cv2.minAreaRect(points) -> retval
580
581 .. ocv:cfunction:: CvBox2D cvMinAreaRect2( const CvArr* points, CvMemStorage* storage=NULL )
582
583 .. ocv:pyoldfunction:: cv.MinAreaRect2(points, storage=None) -> Box2D
584
585     :param points: Input vector of 2D points, stored in:
586
587         * ``std::vector<>`` or ``Mat`` (C++ interface)
588
589         * ``CvSeq*`` or ``CvMat*`` (C interface)
590
591         * Nx2 numpy array (Python interface)
592
593 The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample ``minarea.cpp`` .
594
595
596
597 minEnclosingCircle
598 ----------------------
599 Finds a circle of the minimum area enclosing a 2D point set.
600
601 .. ocv:function:: void minEnclosingCircle( InputArray points, Point2f& center, float& radius )
602
603 .. ocv:pyfunction:: cv2.minEnclosingCircle(points) -> center, radius
604
605 .. ocv:cfunction:: int cvMinEnclosingCircle( const CvArr* points, CvPoint2D32f* center, float* radius )
606
607 .. ocv:pyoldfunction:: cv.MinEnclosingCircle(points)-> (int, center, radius)
608
609     :param points: Input vector of 2D points, stored in:
610
611         * ``std::vector<>`` or ``Mat`` (C++ interface)
612
613         * ``CvSeq*`` or ``CvMat*`` (C interface)
614
615         * Nx2 numpy array (Python interface)
616
617     :param center: Output center of the circle.
618
619     :param radius: Output radius of the circle.
620
621 The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample ``minarea.cpp`` .
622
623
624
625 matchShapes
626 ---------------
627 Compares two shapes.
628
629 .. ocv:function:: double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter )
630
631 .. ocv:pyfunction:: cv2.matchShapes(contour1, contour2, method, parameter) -> retval
632
633 .. ocv:cfunction:: double cvMatchShapes( const void* object1, const void* object2, int method, double parameter=0 )
634 .. ocv:pyoldfunction:: cv.MatchShapes(object1, object2, method, parameter=0) -> float
635
636     :param object1: First contour or grayscale image.
637
638     :param object2: Second contour or grayscale image.
639
640     :param method: Comparison method: ``CV_CONTOURS_MATCH_I1`` , \ ``CV_CONTOURS_MATCH_I2`` \
641         or ``CV_CONTOURS_MATCH_I3``  (see the details below).
642
643     :param parameter: Method-specific parameter (not supported now).
644
645 The function compares two shapes. All three implemented methods use the Hu invariants (see
646 :ocv:func:`HuMoments` ) as follows (
647 :math:`A` denotes ``object1``,:math:`B` denotes ``object2`` ):
648
649 * method=CV_CONTOURS_MATCH_I1
650
651     .. math::
652
653         I_1(A,B) =  \sum _{i=1...7}  \left |  \frac{1}{m^A_i} -  \frac{1}{m^B_i} \right |
654
655 * method=CV_CONTOURS_MATCH_I2
656
657     .. math::
658
659         I_2(A,B) =  \sum _{i=1...7}  \left | m^A_i - m^B_i  \right |
660
661 * method=CV_CONTOURS_MATCH_I3
662
663     .. math::
664
665         I_3(A,B) =  \max _{i=1...7}  \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }
666
667 where
668
669 .. math::
670
671     \begin{array}{l} m^A_i =  \mathrm{sign} (h^A_i)  \cdot \log{h^A_i} \\ m^B_i =  \mathrm{sign} (h^B_i)  \cdot \log{h^B_i} \end{array}
672
673 and
674 :math:`h^A_i, h^B_i` are the Hu moments of
675 :math:`A` and
676 :math:`B` , respectively.
677
678
679
680 pointPolygonTest
681 --------------------
682 Performs a point-in-contour test.
683
684 .. ocv:function:: double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist )
685
686 .. ocv:pyfunction:: cv2.pointPolygonTest(contour, pt, measureDist) -> retval
687
688 .. ocv:cfunction:: double cvPointPolygonTest( const CvArr* contour, CvPoint2D32f pt, int measure_dist )
689 .. ocv:pyoldfunction:: cv.PointPolygonTest(contour, pt, measure_dist) -> float
690
691     :param contour: Input contour.
692
693     :param pt: Point tested against the contour.
694
695     :param 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 a contour or not.
696
697 The function determines whether the
698 point is inside a contour, outside, or lies on an edge (or coincides
699 with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value,
700 correspondingly. When ``measureDist=false`` , the return value
701 is +1, -1, and 0, respectively. Otherwise, the return value
702 is a signed distance between the point and the nearest contour
703 edge.
704
705 See below a sample output of the function where each image pixel is tested against the contour.
706
707 .. image:: pics/pointpolygon.png
708
709 .. [Fitzgibbon95] Andrew W. Fitzgibbon, R.B.Fisher. *A Buyer's Guide to Conic Fitting*. Proc.5th British Machine Vision Conference, Birmingham, pp. 513-522, 1995.
710
711 .. [Hu62] M. Hu. *Visual Pattern Recognition by Moment Invariants*, IRE Transactions on Information Theory, 8:2, pp. 179-187, 1962.
712
713 .. [Sklansky82] Sklansky, J., *Finding the Convex Hull of a Simple Polygon*. PRL 1 $number, pp 79-83 (1982)
714
715 .. [Suzuki85] Suzuki, S. and Abe, K., *Topological Structural Analysis of Digitized Binary Images by Border Following*. CVGIP 30 1, pp 32-46 (1985)
716
717 .. [TehChin89] Teh, C.H. and Chin, R.T., *On the Detection of Dominant Points on Digital Curve*. PAMI 11 8, pp 859-872 (1989)