Search code examples
c++cimage-processingcentroid

Finding an Images Contours Centroid


I am trying to calculate an image centroid like so:

// Calculate centroid
    double signedArea = 0.0;
    sskp_point centroid;
    for(int i=0;i<numPoints;i++)
    {
        double a = (points[i].x*points[(i+1)%numPoints].y)-(points[(i+1)%numPoints].x*points[i].y);
        signedArea += a;
        centroid.x += (points[i].x*points[(i+1)%numPoints].x)*a;
        centroid.y += (points[i].y*points[(i+1)%numPoints].y)*a;
        printf("points[%d] = { %f, %f }\n",i,points[i].x,points[i].y);
    }
    signedArea /= 2.0;
    centroid.x /= (6*signedArea);
    centroid.y /= (6*signedArea);
    printf("centroid = { %f, %f }\n",centroid.x,centroid.y);

I have adapted this from the algorithm here, however it is giving me the wrong results, can anyone tell me what is wrong with this adaptation?


Solution

  • You have written centroid.x += (points[i].x*points[(i+1)%numPoints].x)*a; instead it should be centroid.x += (points[i].x+points[(i+1)%numPoints].x)*a; you have to replace * with + here.