2013-06-20 26 views
1

我使用洪水填充算法对图像进行排序。如果它遇到相同的颜色,我希望它将该像素复制到一个名为“填充”的相同大小的数组中。填充的数组然后转换回图像并保存为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; 
} 

奖金问题:我想洪水填充也承认,类似的颜色,但不完全相同的,因为我处理的照片。

+0

创建'像素'的位移似乎有点奇怪......如果您有3字节的RGB或int RGB样本,您似乎还没有下定决心。也很难知道'int [] []图像'是什么。尝试发布一个完全可运行但剥离的代码版本。 – haraldK

+0

另外,你是不是多次覆盖相同的像素?递归似乎有点失控。你还需要边界检查。 – haraldK

回答

1

你张贴缺少两个重要元素的floodFill功能:

  1. 如果含有相同的颜色作为第一像素的面积一直延伸到图像的边界,该功能会尝试在无效索引处访问image。您可以通过首先检查正在检查的像素的x和y坐标并在出现边界时立即返回来解决此问题。
  2. 如果存在多个相同颜色的相邻像素,该函数将无限地引起递归,因为初始调用将在第二个像素上调用floodFill,然后该像素将继续在第一个像素上调用floodFill,依此类推。您需要一种方法来确保您只在特定像素上调用floodFill一次。

由于您没有观察到这两种症状,也没有观察到任何结果图像,所以我猜测初始像素的颜色检查不正确。当您将一个整数传递给Color构造函数时,您确定它使用该整数的RBG解释吗?

+0

我对递归进行了建议的调整,这仍然导致黑色的JPG。我将对如何正确使用Color构造函数做更多的研究。你是对的,这可能是问题的根源。感谢您的帮助。 – user2506643