Stack Based Flood Fill Algorithm

For a recent project I needed a Flood Fill Algorithm (see Flood Fill in Wikipedia, http://en.wikipedia.org/wiki/Flood_fill). Here is my implementation in C++.

 

Some things to note

1)      I am using the ImagerBitmapClass from a previous post (http://drowningintechnicaldebt.com/blogs/shawnweisfeld/archive/2006/11/06/Bitmap-Processing-in-C_2300_.aspx), which I converted to C++

2)      I am doing this fill in grey scale, you can easily change it to use full color objects

3)      I am looking for all white objects, converting the first blob of white pixels to a given color, then moving to the next blob with a new color


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
marker = 100;
for (int row = 0; row < iright->GetBitmapHeight(); row++)
{
  for (int column = 0; column < iright->GetBitmapWidth(); column++)
  {
    if (iright->GetGreyPixel(column, row) == 255)
    {
      System::Collections::Generic::Queue<System::Drawing::Point> q = gcnew System::Collections::Generic::Queue<System::Drawing::Point>();
      q.Enqueue(System::Drawing::Point(column, row));
      iright->SetPixel(column, row, marker);
      while (q.Count > 0)
      {
        Point p = q.Dequeue();
        if (iright->AddToStack(p.X+1, p.Y, marker))
        {
          q.Enqueue(System::Drawing::Point(p.X+1, p.Y));
          iright->SetPixel(p.X+1, p.Y, marker);
        }
        if (iright->AddToStack(p.X, p.Y+1, marker))
        {
          q.Enqueue(System::Drawing::Point(p.X, p.Y+1));
          iright->SetPixel(p.X, p.Y+1, marker);
        }
        if (iright->AddToStack(p.X-1, p.Y, marker))
        {
          q.Enqueue(System::Drawing::Point(p.X-1, p.Y));
          iright->SetPixel(p.X-1, p.Y, marker);
        }
        if (iright->AddToStack(p.X, p.Y-1, marker))
        {
          q.Enqueue(System::Drawing::Point(p.X, p.Y-1));
          iright->SetPixel(p.X, p.Y-1, marker);
        }
      }
      marker += 20;
    }
  }
}
inline bool AddToStack(int x, int y, int marker)
{
  if ((x < 0) || (x >= this->GetBitmapWidth()))
  {
    return false;
  }
  if ((y < 0) || (y >= this->GetBitmapHeight()))
  {
    return false;
  }
  int px = this->GetGreyPixel(x, y);
  if (px == 255 && px != marker)
  {
    return true;
  }
  return false;
}
Published Monday, December 04, 2006 7:14 AM by sweisfeld
Filed under: , , ,

Comments

No Comments