Mass center of contour is showing incorrectly in opencv java

asked 2019-12-15 21:37:09 -0500

I am searching the correct method for mass center of contour in opencv 3.4.5 for a while but the the mass center fluctuates between (0,0) position. I cannot find where I am getting wrong.

This is my implementation for calculating mass center of largest contour.

Imgproc.findContours(threshFrame, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_NONE);

for (int id = 0; id < contours.size(); id++) {
     Mat c = contours.get(id);
     double cArea = Imgproc.contourArea(c);

     if (cArea > maxArea) {
           maxArea = cArea;
           maxAreaID = id;
            }
  }

  Moments largestContour = Imgproc.moments(contours.get(maxAreaID), false);

  double cx = (largestContour.get_m10() / largestContour.get_m00()+ 1e-5);
  double cy = (largestContour.get_m01() / largestContour.get_m00()+ 1e-5);
edit retag flag offensive close merge delete

Comments

1

When finding (even with careful checking of data in debugger) fails, seeing helps, especially others... You should draw an example image with all contours and mass centers, and soneone could figure out where things go wrong.

mvuori gravatar imagemvuori ( 2019-12-16 04:36:54 -0500 )edit

btw, use RETR_EXTERNAL, if you're only interested in the largest (outer) contour

berak gravatar imageberak ( 2019-12-16 06:02:42 -0500 )edit