2013-06-20 71 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