【问题标题】:Using a Flood Fill Algorith to create an Array使用填充算法创建数组
【发布时间】:2013-06-21 04:04:29
【问题描述】:

我正在使用填充算法对图像进行排序。如果它遇到相同的颜色,我希望它将该像素复制到一个相同大小的数组中,称为填充。然后将填充的数组转换回图像并保存为 jpg。但是,当我打开 jpg 时,它看起来完全是黑色的。

public static void findFace(int[][] image) throws IOException {
    int height = image.length;
    int width = image[0].length;

    Color centerStart = new Color(image[width / 2][height / 2]);
    int[][] filled = new int[width][height];

    floodFill(width / 2, height / 2, centerStart, image, filled);

    //construct the filled array as image. Show if the face was found.
    BufferedImage bufferImage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int Pixel = filled[x][y] << 16 | filled[x][y] << 8 | filled[x][y];
            bufferImage2.setRGB(x, y, Pixel);
        }
    }

    //save filled array as image file
    File outputfile = new File("/home/lily/Pictures/APicaDay/saved.jpg");
    ImageIO.write(bufferImage2, "jpg", outputfile);
}

public static int[][] floodFill(int x, int y, Color targetColor, int[][] image, int[][] filled) {
    if (image[x][y] != targetColor.getRGB()) {
        return filled;
    }

    filled[x][y] = image[x][y];

    floodFill(x - 1, y, targetColor, image, filled);
    floodFill(x + 1, y, targetColor, image, filled);
    floodFill(x, y - 1, targetColor, image, filled);
    floodFill(x, y + 1, targetColor, image, filled);

    return filled;
}

额外问题:我希望泛光填充也接受相似但不完全相同的颜色,因为我正在处理照片。

【问题讨论】:

  • 创建Pixel 的位移似乎有点奇怪......如果您有 3 字节 RGB 或 int RGB 样本,您似乎还没有下定决心。也很难知道int[][] image 到底是什么。尝试发布一个完全可运行但精简版的代码。
  • 另外,你不是多次覆盖同一个像素吗?递归似乎有点失控。您还需要边界检查。

标签: java recursion flood-fill


【解决方案1】:

您发布的floodFill 函数缺少两个重要元素:

  1. 如果包含与第一个像素相同颜色的区域一直延伸到图像的边界,该函数将尝试在无效索引处访问image。您可以通过首先检查您正在检查的像素的 x 和 y 坐标来解决此问题,如果超出范围则立即返回。
  2. 如果有多个相同颜色的相邻像素,该函数将导致无限递归,因为初始调用将在第二个像素上调用floodFill,然后将继续在第一个像素上调用floodFill , 等等。您需要一种方法来确保只对特定像素调用一次floodFill

由于您没有观察到这两种症状中的任何一种,并且您没有从生成的图像中观察到任何东西,我猜初始像素的颜色检查不正确。当您将整数传递给Color 构造函数时,您确定它使用了对该整数的 RBG 解释吗?

【讨论】:

  • 我对递归进行了建议的调整,但仍然导致黑色 jpg。我将对如何正确使用 Color 构造函数进行更多研究。你是对的,这可能是问题的根源。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
相关资源
最近更新 更多