Ask Your Question

Revision history [back]

You need to add the positions of non-zero pixels in horizontal (vertical) directions and divide them by the number of columns (rows) to get the center of gravity.

You need to add the positions of non-zero pixels in horizontal (vertical) directions and divide them by the number of columns (rows) nonzero pixels to get the center of gravity.

click to hide/show revision 3
Moved pseudocode into answer from comment.

You need to add the positions of non-zero pixels in horizontal (vertical) directions and divide them by the number of nonzero pixels to get the center of gravity.

xsum = 0;
ysum = 0;
num_nonzero_pxl = 0;
for each pixel (p(x,y))
    if pixel p(x,y) is non-zero {
        xsum += x;
        ysum += y;
        num_nonzero_pxl++;
    }
cgix=xsum/num_nonzero_pxl;
cgiy=ysum/num_nonzero_pxl;