Ask Your Question

Revision history [back]

Mass center of contour is showing incorrectly in opencv java

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);