6

I want to find the center of a contour without doing so much calculations. Is there a built in function for that in opencv?

shahd
  • 109
  • 1
  • 2
  • 6

3 Answers3

15

for the 'geometric center', get the boundingRect() of the contour, then:

   cx = br.x+br.width/2; cy = br.y+br.height/2; 

for the 'center of mass' get the moments() of the contour, then:

   cx = m.m10 / m.m00;   cy = m.m01 / m.m00;
berak
  • 39,159
  • 9
  • 91
  • 89
  • 1
    Thank your answer was easy to implement not complicated like examples that I found. – shahd Mar 14 '14 at 09:17
  • Using "moments" can fail with ZeroDivisionError because of bad contours, see https://stackoverflow.com/a/35247571/1619432 (no proper solution given). – handle Oct 14 '18 at 16:38
0

Either you haven't done any research, or these questions already asked and answered here are not what you are asking:

centroid of contour/object in opencv in c?

OpenCV 2 Centroid

If latter is the case, please elaborate the question in more detail.

Community
  • 1
  • 1
bosnjak
  • 8,424
  • 2
  • 21
  • 47
0

hope this could help you. this link has python and C++ code snippet

std::vector<cv::Point> centers; 
for (int i=0; i<contours.size(); i++){
     cv::Moments M = cv::moments(contours[i]);
     cv::Point center(M.m10/M.m00, M.m01/M.m00);
     centers.push_back(center);
}
J.Zhao
  • 2,250
  • 1
  • 14
  • 12