|  1 |    initial version    |  
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.
    |  2 |    No.2 Revision    |  
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.
    |  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;