我正在使用Java。
我正在开发一个绘图程序,“Paint Can”工具使用Flood Fill算法,但它太昂贵了。算法,洪水填充(深度优先搜索)
下面是代码:
private int[] dx = { -1, 0, 1, 0 };
private int[] dy = { 0, 1, 0, -1 };
public void floodFill(int x, int y, Color target_color, Color replacement_color) {
Stack<Integer[]> stack = new Stack<Integer[]>();
if (imageBuffer.getRGB(x, y) == replacement_color.getRGB())
return;
stack.push(new Integer[] { x, y });
while (!stack.isEmpty()) {
Integer[] aux = stack.peek();
imageBuffer.setRGB(aux[0], aux[1], replacement_color.getRGB());
stack.pop();
for (int i = 0; i < 4; i++) {
if (imageBuffer.getRGB(aux[0] + dx[i], aux[1] + dy[i]) == target_color.getRGB())
stack.push(new Integer[] { aux[0] + dx[i], aux[1] + dy[i] });
}
}
}
有人可以帮我做这个更有效率?
需要(对于1020x700像素图像)大约1200ms执行。
我认为最主要的是你需要一个更好的算法。 http://en.wikipedia.org/wiki/Flood_fill是一个很好的资源。有一些微观优化你可以做到(例如'replacement_color.getRGB()'每次评估,因为它'target_color.getRGB()',但我不认为这会有很大的不同。 –