我试图在连接的二进制图像区域上实现泛洪填充,但是我得到了StackOverflow错误。此外,如何使用不同的颜色对每个区域进行着色。
谢谢
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);
}
}
发布于 2014-01-04 17:48:45
PMF是正确的;您应该为此使用迭代算法。
迭代算法为:
Fill(coordinate)
stack = new Stack<Coordinate>()
stack.Push(coordinate)
while !stack.IsEmpty
current = stack.Pop();
if bitmap[current] is not white then continue
bitmap[current] = black
stack.Push(current.NorthNeighbour)
stack.Push(current.SouthNeighbour)
etc.
你明白这是怎么回事了吗?这个想法是,不是使用调用堆栈作为临时存储,而是实际分配您自己的堆栈。
发布于 2014-01-04 17:38:44
我猜这个问题与递归的顺序有关。在最坏的情况下,您将(几乎)首先处理整个图像的深度。递归的深度可以与图像中的总像素一样深。
假设我们从10x10图像的左下角开始。最初的几个步骤是:
我们递归地输入第一个堆栈深度(x,y-1),直到y=0堆栈深度,下一步我们可以做的是FloodFill(x+1,y),直到x= 9,y=0堆栈深度19
因此,您需要的堆栈大小至少为图像的2*width+2*height -上面只是一个快速分析。这可能太多了。
建议:使用迭代算法。
https://stackoverflow.com/questions/20923478
复制相似问题