Java泛洪填充问题

6

我需要编写一个泛洪算法,用于给图像中黑色边框内的像素着色。我参考了一些 SO 上的帖子,编写了以下代码:

private Queue<Point> queue = new LinkedList<Point>();
private int pickedColorInt = 0;

private void floodFill(Pixmap pixmap, int x, int y){
    //set to true for fields that have been checked
    boolean[][] painted  = new boolean[pixmap.getWidth()][pixmap.getHeight()];

    //skip black pixels when coloring
    int blackColor = Color.rgba8888(Color.BLACK);

    queue.clear();
    queue.add(new Point(x, y));

    while(!queue.isEmpty()){
        Point temp = queue.remove();
        int temp_x = temp.getX();
        int temp_y = temp.getY();

        //only do stuff if point is within pixmap's bounds
        if(temp_x >= 0 && temp_x < pixmap.getWidth() && temp_y >= 0 && temp_y < pixmap.getHeight()) {
            //color of current point
            int pixel = pixmap.getPixel(temp_x, temp_y);
            if (!painted[temp_x][temp_y] && pixel != blackColor) {
                painted[temp_x][temp_y] = true;
                pixmap.drawPixel(temp_x, temp_y, pickedColorInt);

                queue.add(new Point(temp_x + 1, temp_y));
                queue.add(new Point(temp_x - 1, temp_y));
                queue.add(new Point(temp_x, temp_y + 1));
                queue.add(new Point(temp_x, temp_y - 1));

            }
        }
    }
}

这并不像预期的那样工作。例如,在下面的测试图像上:

enter image description here

随机矩形将根据我点击的位置而重新着色。例如,单击紫色矩形下方的任何位置都会重新着色紫色矩形。在紫色矩形内部点击会重新着色绿色矩形。我已经检查过,并且将正确的参数传递给方法,因此问题可能出现在我的循环内部。


3
我认为你没有传入正确的参数。这听起来像是你正在使用某些坐标系,其中一个是Y向上,而另一个是Y向下,所以你的Y坐标可能是错误的。在你的方法开头尝试y = pixmap.getHeight() - y来翻转y坐标。 - noone
哇,这甚至没有在我的脑海中出现过。这是一个libGDX项目,在这个项目中,例如场景坐标、精灵、矩形和类似的对象在左下角有一个(0, 0)坐标。但我猜Pixmap使用左上角作为(0, 0)坐标。谢谢! - Tomislav Turcic
解决了您的问题吗?如果解决了,我会把它写成一个答案,这样它就不会显示为未回答。 - noone
好的,伙计。感谢你的帮助。 - Tomislav Turcic
@没有人似乎你可以将它写成一个答案。 - Robert P
@Springrbua 已完成,谢谢你提醒我。 - noone
1个回答

2
你的算法是正确的,只是输入参数不正确。
引用块: 随机矩形将根据我点击的位置重新着色。例如,在紫色矩形下方的任何位置单击都会重新着色紫色矩形。在紫色矩形内部单击会重新着色绿色矩形。
如果你看一下图片,你就会发现这些彩色矩形并不是真正的随机的。实际问题是Y坐标不正确。具体来说,你的Y坐标是倒置的。
这是因为大多数情况下,LibGDX使用左下角,y向上的坐标系统,但是在Pixmap的情况下,它是顶部左侧y向下的。
解决这个问题的一个简单方法是通过执行y = pixmap.getHeight() - y来反转Y值。

感谢@noone,我已经在我的库中使用了这个解决方案:https://github.com/Gornova/StrategyGameUtils - Vokail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接