I'm trying to implement flood fill on connected binary image regions, however I get StackOverflow error. Furthermore, how can I color each region with different color.
Thanks
public void FloodFill(int x, int y)
{
Bitmap bitmap = (Bitmap)pictureBox1.Image;
if ((x < 0) || (y < 0) || (x >= bitmap.Width) || (y >= bitmap.Height)) { return; }
Color cl = bitmap.GetPixel(x, y); // error An unhandled exception of type 'System.StackOverflowException' occurred in System.Drawing.dll
if ((cl.R != 255) || (cl.G != 255) || (cl.B != 255)) { return; }
if ((cl.R == 255) && (cl.G == 255) && (cl.B == 255)) {
bitmap.SetPixel(x, y, Color.FromArgb(255, 255, 0, 0));
}
FloodFill(x, y - 1);
FloodFill(x + 1, y - 1);
FloodFill(x + 1, y);
FloodFill(x + 1, y + 1);
FloodFill(x, y + 1);
FloodFill(x - 1, y + 1);
FloodFill(x - 1, y);
FloodFill(x - 1, y - 1);
}
for (int i = 0; i < pictureBox1.Width; i++)
{
for (int j = 0; j < pictureBox1.Height; j++) {
Point p = new Point(i, j);
FloodFill(p.X, p.Y);
}
}