Calculates all of the moments up to the third order of a polygon or rasterized shape.
Moments moments
(InputArray array, bool binaryImage=false )¶
cv2.
moments
(array[, binaryImage]) → retval¶
void cvMoments
(const CvArr* arr, CvMoments* moments, int binary=0 )¶
cv.
Moments
(arr, binary=0) → moments¶Parameters: 


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:
class Moments
{
public:
Moments();
Moments(double m00, double m10, double m01, double m20, double m11,
double m02, double m30, double m21, double m12, double m03 );
Moments( const CvMoments& moments );
operator CvMoments() const;
// spatial moments
double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
// central moments
double mu20, mu11, mu02, mu30, mu21, mu12, mu03;
// central normalized moments
double nu20, nu11, nu02, nu30, nu21, nu12, nu03;
}
In case of a raster image, the spatial moments are computed as:
The central moments are computed as:
where is the mass center:
The normalized central moments are computed as:
Note
, , hence the values are not stored.
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.
Note
Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with selfintersections, e.g. a zero area (m00
) for butterflyshaped contours.
See also
Calculates seven Hu invariants.
void HuMoments
(const Moments& m, OutputArray hu)¶
void HuMoments
(const Moments& moments, double hu[7])¶
cv2.
HuMoments
(m[, hu]) → hu¶
void cvGetHuMoments
(CvMoments* moments, CvHuMoments* hu_moments)¶
cv.
GetHuMoments
(moments) → hu¶Parameters: 


The function calculates seven Hu invariants (introduced in [Hu62]; see also http://en.wikipedia.org/wiki/Image_moment) defined as:
where stands for .
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.
See also
Finds contours in a binary image.
void findContours
(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())¶
void findContours
(InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())¶
cv2.
findContours
(image, mode, method[, contours[, hierarchy[, offset]]]) → contours, hierarchy¶
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) )¶
cv.
FindContours
(image, storage, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE, offset=(0, 0)) → contours¶Parameters: 


The function retrieves contours from the binary image using the algorithm
[Suzuki85]. The contours are a useful tool for shape analysis and object detection and recognition. See squares.c
in the OpenCV sample directory.
Note
Source image
is modified by this function. Also, the function does not take into account 1pixel 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.
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
).
Note
Draws contours outlines or filled contours.
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() )¶
cv2.
drawContours
(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) → None¶
void cvDrawContours
(CvArr* img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )¶
cv.
DrawContours
(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0)) → None¶Parameters: 


The function draws contour outlines in the image if or fills the area bounded by the contours if . The example below shows how to retrieve connected components from the binary image and label them:
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main( int argc, char** argv )
{
Mat src;
// the first commandline parameter must be a filename of the binary
// (blacknwhite) image
if( argc != 2  !(src=imread(argv[1], 0)).data)
return 1;
Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
src = src > 1;
namedWindow( "Source", 1 );
imshow( "Source", src );
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( src, contours, hierarchy,
CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
// iterate through all the toplevel contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( rand()&255, rand()&255, rand()&255 );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
namedWindow( "Components", 1 );
imshow( "Components", dst );
waitKey(0);
}
Note
Approximates a polygonal curve(s) with the specified precision.
void approxPolyDP
(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)¶
cv2.
approxPolyDP
(curve, epsilon, closed[, approxCurve]) → approxCurve¶
CvSeq* cvApproxPoly
(const void* src_seq, int header_size, CvMemStorage* storage, int method, double eps, int recursive=0 )¶Parameters: 


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 DouglasPeucker algorithm
http://en.wikipedia.org/wiki/RamerDouglasPeucker_algorithm
See https://github.com/opencv/opencv/tree/master/samples/cpp/contours2.cpp for the function usage model.
Approximates Freeman chain(s) with a polygonal curve.
CvSeq* cvApproxChains
(CvSeq* src_seq, CvMemStorage* storage, int method=CV_CHAIN_APPROX_SIMPLE, double parameter=0, int minimal_perimeter=0, int recursive=0 )¶
cv.
ApproxChains
(src_seq, storage, method=CV_CHAIN_APPROX_SIMPLE, parameter=0, minimal_perimeter=0, recursive=0) → contours¶Parameters: 


This is a standalone contour approximation routine, not represented in the new interface. When FindContours()
retrieves contours as Freeman chains, it calls the function to get approximated contours, represented as polygons.
Calculates a contour perimeter or a curve length.
double arcLength
(InputArray curve, bool closed)¶
cv2.
arcLength
(curve, closed) → retval¶
double cvArcLength
(const void* curve, CvSlice slice=CV_WHOLE_SEQ, int is_closed=1 )¶
cv.
ArcLength
(curve, slice=CV_WHOLE_SEQ, isClosed=1) → float¶Parameters: 


The function computes a curve length or a closed contour perimeter.
Calculates the upright bounding rectangle of a point set.
Rect boundingRect
(InputArray points)¶
cv2.
boundingRect
(points) → retval¶
CvRect cvBoundingRect
(CvArr* points, int update=0 )¶
cv.
BoundingRect
(points, update=0) → CvRect¶Parameters:  points – Input 2D point set, stored in std::vector or Mat . 

The function calculates and returns the minimal upright bounding rectangle for the specified point set.
Calculates a contour area.
double contourArea
(InputArray contour, bool oriented=false )¶
cv2.
contourArea
(contour[, oriented]) → retval¶
double cvContourArea
(const CvArr* contour, CvSlice slice=CV_WHOLE_SEQ, int oriented=0 )¶
cv.
ContourArea
(contour, slice=CV_WHOLE_SEQ) → float¶Parameters: 


The function computes a contour area. Similarly to
moments()
, the area is computed using the Green formula. Thus, the returned area and the number of nonzero pixels, if you draw the contour using
drawContours()
or
fillPoly()
, can be different.
Also, the function will most certainly give a wrong results for contours with selfintersections.
Example:
vector<Point> contour;
contour.push_back(Point2f(0, 0));
contour.push_back(Point2f(10, 0));
contour.push_back(Point2f(10, 10));
contour.push_back(Point2f(5, 4));
double area0 = contourArea(contour);
vector<Point> approx;
approxPolyDP(contour, approx, 5, true);
double area1 = contourArea(approx);
cout << "area0 =" << area0 << endl <<
"area1 =" << area1 << endl <<
"approx poly vertices" << approx.size() << endl;
Finds the convex hull of a point set.
void convexHull
(InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true )¶
cv2.
convexHull
(points[, hull[, clockwise[, returnPoints]]]) → hull¶
CvSeq* cvConvexHull2
(const CvArr* input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0 )¶
cv.
ConvexHull2
(points, storage, orientation=CV_CLOCKWISE, return_points=0) → convexHull¶Parameters: 


The functions find the convex hull of a 2D point set using the Sklansky’s algorithm
[Sklansky82]
that has
O(N logN) complexity in the current implementation. See the OpenCV sample convexhull.cpp
that demonstrates the usage of different function variants.
Note
Finds the convexity defects of a contour.
void convexityDefects
(InputArray contour, InputArray convexhull, OutputArray convexityDefects)¶
cv2.
convexityDefects
(contour, convexhull[, convexityDefects]) → convexityDefects¶
CvSeq* cvConvexityDefects
(const CvArr* contour, const CvArr* convexhull, CvMemStorage* storage=NULL )¶
cv.
ConvexityDefects
(contour, convexhull, storage) → convexityDefects¶Parameters: 


The function finds all convexity defects of the input contour and returns a sequence of the CvConvexityDefect
structures, where CvConvexityDetect
is defined as:
struct CvConvexityDefect
{
CvPoint* start; // point of the contour where the defect begins
CvPoint* end; // point of the contour where the defect ends
CvPoint* depth_point; // the farthest from the convex hull point within the defect
float depth; // distance between the farthest point and the convex hull
};
The figure below displays convexity defects of a hand contour:
Fits an ellipse around a set of 2D points.
RotatedRect fitEllipse
(InputArray points)¶
cv2.
fitEllipse
(points) → retval¶
CvBox2D cvFitEllipse2
(const CvArr* points)¶
cv.
FitEllipse2
(points) → Box2D¶Parameters:  points – Input 2D point set, stored in:


The function calculates the ellipse that fits (in a leastsquares 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. Developer should keep in mind that it is possible that the returned ellipse/rotatedRect data contains negative indices, due to the data points being close to the border of the containing Mat element.
Note
Fits a line to a 2D or 3D point set.
void fitLine
(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)¶
cv2.
fitLine
(points, distType, param, reps, aeps[, line]) → line¶
void cvFitLine
(const CvArr* points, int dist_type, double param, double reps, double aeps, float* line)¶
cv.
FitLine
(points, dist_type, param, reps, aeps) → line¶Parameters: 


The function fitLine
fits a line to a 2D or 3D point set by minimizing
where
is a distance between the
point, the line and
is a distance function, one of the following:
distType=CV_DIST_L2
distType=CV_DIST_L1
distType=CV_DIST_L12
distType=CV_DIST_FAIR
distType=CV_DIST_WELSCH
distType=CV_DIST_HUBER
The algorithm is based on the Mestimator ( http://en.wikipedia.org/wiki/Mestimator ) technique that iteratively fits the line using the weighted leastsquares algorithm. After each iteration the weights are adjusted to be inversely proportional to .
Tests a contour convexity.
bool isContourConvex
(InputArray contour)¶
cv2.
isContourConvex
(contour) → retval¶
int cvCheckContourConvexity
(const CvArr* contour)¶
cv.
CheckContourConvexity
(contour) → int¶Parameters:  contour – Input vector of 2D points, stored in:


The function tests whether the input contour is convex or not. The contour must be simple, that is, without selfintersections. Otherwise, the function output is undefined.
Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
RotatedRect minAreaRect
(InputArray points)¶
cv2.
minAreaRect
(points) → retval¶
CvBox2D cvMinAreaRect2
(const CvArr* points, CvMemStorage* storage=NULL )¶
cv.
MinAreaRect2
(points, storage=None) → Box2D¶Parameters:  points – Input vector of 2D points, stored in:


The function calculates and returns the minimumarea bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample minarea.cpp
.
Developer should keep in mind that the returned rotatedRect can contain negative indices when data is close the the containing Mat element boundary.
Finds a circle of the minimum area enclosing a 2D point set.
void minEnclosingCircle
(InputArray points, Point2f& center, float& radius)¶
cv2.
minEnclosingCircle
(points) → center, radius¶
int cvMinEnclosingCircle
(const CvArr* points, CvPoint2D32f* center, float* radius)¶
cv.
MinEnclosingCircle
(points)> (int, center, radius)¶Parameters: 


The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample minarea.cpp
.
Compares two shapes.
double matchShapes
(InputArray contour1, InputArray contour2, int method, double parameter)¶
cv2.
matchShapes
(contour1, contour2, method, parameter) → retval¶
double cvMatchShapes
(const void* object1, const void* object2, int method, double parameter=0 )¶
cv.
MatchShapes
(object1, object2, method, parameter=0) → float¶Parameters: 


The function compares two shapes. All three implemented methods use the Hu invariants (see
HuMoments()
) as follows (
denotes object1
,:math:B denotes object2
):
method=CV_CONTOURS_MATCH_I1
method=CV_CONTOURS_MATCH_I2
method=CV_CONTOURS_MATCH_I3
where
and are the Hu moments of and , respectively.
Performs a pointincontour test.
double pointPolygonTest
(InputArray contour, Point2f pt, bool measureDist)¶
cv2.
pointPolygonTest
(contour, pt, measureDist) → retval¶
double cvPointPolygonTest
(const CvArr* contour, CvPoint2D32f pt, int measure_dist)¶
cv.
PointPolygonTest
(contour, pt, measure_dist) → float¶Parameters: 


The function determines whether the
point is inside a contour, outside, or lies on an edge (or coincides
with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value,
correspondingly. When measureDist=false
, the return value
is +1, 1, and 0, respectively. Otherwise, the return value
is a signed distance between the point and the nearest contour
edge.
See below a sample output of the function where each image pixel is tested against the contour.
[Fitzgibbon95]  Andrew W. Fitzgibbon, R.B.Fisher. A Buyer’s Guide to Conic Fitting. Proc.5th British Machine Vision Conference, Birmingham, pp. 513522, 1995. The technique used for ellipse fitting is the first one described in this summary paper. 
[Hu62] 

[Sklansky82]  Sklansky, J., Finding the Convex Hull of a Simple Polygon. PRL 1 $number, pp 7983 (1982) 
[Suzuki85]  Suzuki, S. and Abe, K., Topological Structural Analysis of Digitized Binary Images by Border Following. CVGIP 30 1, pp 3246 (1985) 
[TehChin89]  Teh, C.H. and Chin, R.T., On the Detection of Dominant Points on Digital Curve. PAMI 11 8, pp 859872 (1989) 