Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You should use moments() function.

Moments m = moments(difference, false);
Point p1(m.m10/m.m00, m.m01/m.m00);

Code of sample:

int main(int argc, char *argv[])
{
    Mat box = imread("box.png",0);
    Mat difference;
    threshold(box, difference, 200, 255, CV_8UC1);
    float sumx=0, sumy=0;
    float num_pixel = 0;
    for(int x=0; x<difference.cols; x++) {
        for(int y=0; y<difference.rows; y++) {
            int val = difference.at<uchar>(y,x);
            if( val >= 50) {
                sumx += x;
                sumy += y;
                num_pixel++;
            }
        }
    }
    Point p(sumx/num_pixel, sumy/num_pixel);
    cout << Mat(p) << endl;

    Moments m = moments(difference, false);
    Point p1(m.m10/m.m00, m.m01/m.m00);
    cout << Mat(p1) << endl;

    circle(difference, p, 5, Scalar(128,0,0), -1);
    imshow("difff", difference);
    waitKey(0);
    return 0;
}