Java 洪水填充问题

标签 java image-processing libgdx flood-fill

我需要编写一个填充算法来为黑色边框内的图像像素着色。我根据 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

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

最佳答案

你的算法是正确的,只是你的输入参数不正确。

Random rectangles will get recolored depending of where I've clicked. For example, clicking anywhere below purple rectangle will recolor purple rectangle. Clicking inside purple rectangle recolors the green rectangle.

如果您看图片,彩色矩形并不是真正随机的。真正的问题是 Y 坐标不正确。具体来说,您的 Y 坐标是倒置的。

那是因为大多数时候 LibGDX 使用左下、y 向上的坐标系统,但在 Pixmap 的情况下,它是左上 y 向下。

解决此问题的一个简单方法是通过执行 y = pixmap.getHeight() - y 来反转 Y 值。

关于Java 洪水填充问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29914125/

相关文章:

opengl - libgdx:在哪里放置 Gdx.gl.glClearColor()

java - ActorGestureListener Fling 未注册

java - 双缓冲和 libgdx

java - Eclipse,在自动生成的代码中更改异常变量名称

java - SSL 连接超时和读取超时

java - hibernate/JPA : How to find sub entities using InheritanceType. 已加入

matlab - 从2D图像获取深度图像

php - 如何在没有 GD 的情况下在 PHP 中合并两个图像?

java - Android表格行横线

python - 与图像不同的是与keras的conv2D进行卷积