5

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
  • 99
  • 1
  • 2
  • 6

4 Answers4

13

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
  • 37,825
  • 9
  • 89
  • 86
  • 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,036
  • 2
  • 19
  • 45
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,112
  • 1
  • 11
  • 11
-2

To answer your question:

There is no built in function. Checkout berak for copypasta code that solves your problem.

Sebastian Schmitz
  • 1,860
  • 2
  • 20
  • 40