Center of Mass

In my earlier post I put together an image processing class (http://drowningintechnicaldebt.com/blogs/shawnweisfeld/archive/2006/11/06/Bitmap-Processing-in-C_2300_.aspx). I needed a method that found the center of a given mass of pixels. Here is the code:

public static Point CenterOfMass(Bitmap b)
{
    ImagerBitmap i = new ImagerBitmap(b.Clone() as Bitmap);
    int cogX = 0;
    int cogY = 0;
    int cogTotal = 0;

    for (int column = 0; column < i.Bitmap.Width; column++)
    {
     for (int row = 0; row < i.Bitmap.Height; row++)
     {
         int px = i.GetGreyPixel(column, row);
         cogX += (px * column);
         cogY += (px * row);
         cogTotal += px;
     }
    }
    i.UnlockBitmap();
    return new Point(cogX / cogTotal, cogY / cogTotal);
}

Published Monday, May 14, 2007 10:23 AM by sweisfeld
Filed under: ,

Comments

No Comments