OpenCV 2 Centroid

keshavdv picture keshavdv · Jan 31, 2012 · Viewed 32.4k times · Source

I am trying to find the centroid of a contour but am having trouble implementing the example code in C++ (OpenCV 2.3.1). Can anyone help me out?

Answer

Abid Rahman K picture Abid Rahman K · Jan 31, 2012

To find the centroid of a contour, you can use the method of moments. And functions are implemented OpenCV.

Check out these moments function (central and spatial moments).

Below code is taken from OpenCV 2.3 docs tutorial. Full code here.


/// Find contours
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

/// Get the moments
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mu[i] = moments( contours[i], false ); }

///  Get the mass centers:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); } 

Also check out this SOF, although it is in Python, it would be useful. It finds all parameters of a contour.