Bounding Box

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 built a bounding box around a given shape. Here is the code:

public static void BoundingBox(Bitmap b, ref Point upperLeft, ref Point lowerRight)
{
    ImagerBitmap i = new ImagerBitmap(b.Clone() as Bitmap);
    Queue<Point> q = new Queue<Point>();
    q.Enqueue(upperLeft);

    int jump = 10;

    while (q.Count > 0)
    {
     Point p = q.Dequeue();
     AddToStack(q, b, i, new Point(p.X + jump, p.Y), ref upperLeft, ref lowerRight);
     AddToStack(q, b, i, new Point(p.X - jump, p.Y), ref upperLeft, ref lowerRight);
     AddToStack(q, b, i, new Point(p.X, p.Y + jump), ref upperLeft, ref lowerRight);
     AddToStack(q, b, i, new Point(p.X, p.Y - jump), ref upperLeft, ref lowerRight);
    }
    i.UnlockBitmap();
}

private static void AddToStack(Queue<Point> q, Bitmap b, ImagerBitmap i, Point p, ref Point upperLeft, ref Point lowerRight)
{
    if (p.X < b.Width
     && p.Y < b.Height
     && i.GetGreyPixel(p.X, p.Y) != 0)
    {
     if (upperLeft.X > p.X)
     {
         upperLeft.X = p.X;
         q.Enqueue(p);
     }
     if (upperLeft.Y > p.Y)
     {
         upperLeft.Y = p.Y;
         q.Enqueue(p);
     }
     if (lowerRight.X < p.X)
     {
         lowerRight.X = p.X;
         q.Enqueue(p);
     }
     if (lowerRight.Y < p.Y)
     {
         lowerRight.Y = p.Y;
         q.Enqueue(p);
     }
    }
}

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

Comments

No Comments