java洪水填充问题

sxpgvts3  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(368)

我需要写一个洪水填充算法,以彩色像素的图像是在黑色的边界。我根据这里的一些帖子写了以下内容:

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));

            }
        }
    }
}

这不符合预期。例如,在以下测试图像上:

随机矩形将根据我点击的位置重新着色。例如,单击紫色矩形下方的任意位置将重新着色紫色矩形。在紫色矩形内单击可重新启用绿色矩形。我已经检查了它,并将正确的参数传递给方法,所以问题可能在我的循环中的某个地方。

cyvaqqii

cyvaqqii1#

你的算法是正确的,只有你的输入参数是不正确的。
随机矩形将根据我点击的位置重新着色。例如,单击紫色矩形下方的任意位置将重新着色紫色矩形。在紫色矩形内单击可重新启用绿色矩形。
如果你看这张图片,彩色矩形并不是随机的。真正的问题是y坐标不正确。特别是你的y坐标是倒转的。
这是因为libgdx大多数时候使用的是左下角的y-up坐标系,但是在 Pixmap 它是左上y向下的。
一个简单的解决方法就是通过 y = pixmap.getHeight() - y .

相关问题