2017-04-07 79 views
0

我有一張圖片,我試圖去除所有綠色像素。我如何使用簡單的java和2D數組來做到這一點?使用java替換圖片中的綠色像素

到目前爲止,我的代碼如下所示:(。現在,我想只能用白色像素替換綠色像素,因爲我不知道如何完全刪除像素)

public void removeGreen() { 

     Picture pic = new Picture("IMG_7320.JPG"); 
     Pixel pixel = null; 
     for (int row = 0; row < pic.getHeight(); row++) { 
      for (int col = 0; col < pic.getWidth(); col++) { 
       pixel = getPixel(row,col); 
       pixel.getColor(); 
       if(pixel.getRed() < 40 & pixel.getBlue() < 160 & pixel.getGreen() > 220) { 
        Color white = new Color(255,255,255); 
        pixel.setColor(white); 
       } 
      } 
     } 
    } 

而且我使用測試removeGreen()方法,在我的主要方法的代碼,如下所示:

//method to test removeGreen 

    public static void testRemoveGreen() { 

     Picture me = new Picture("IMG_7320.JPG"); 
     me.explore(); 
     me.removeGreen(); 
     me.explore(); 
    } 


所以,我的代碼現在看起來像這樣:

公共無效removeGreen(圖像PIC){

爲(INT行= 0;行< pic.getHeight();行++){

for (int col = 0; col < pic.getWidth(); col++) { 
     Pixel pixel = pic.getPixel(row,col); 

     if((pixel.getRed() < 40) && (pixel.getBlue() < 160) && (pixel.getGreen() > 220)) { 
      Color white = new Color(255,255,255); 
      pixel.setColor(white); 
     } 
    } 

} }

和我的主要方法仍是相同的。我仍然不明白爲什麼該方法無法正常工作。

+1

所以你想用另一個圖像的像素替換它們?一種綠色屏幕?澄清你的問題。如果不按照順序調整圖像大小,則永遠不能刪除像素,因此,假設您使用的圖像格式支持Alpha通道,則最好做到透明。 – Havenard

+1

另外,在我看來,你在收集數據和修改圖像'this''的同時迭代圖像'pic',做出決定。 – Havenard

回答

0

以下表明通過的pic參數已更改。

public static void removeGreen(Picture pic) { 
     for (int row = 0; row < pic.getHeight(); row++) { 
      for (int col = 0; col < pic.getWidth(); col++) { 
       Pixel pixel = pic.getPixel(row,col); 
       if (pixel.getRed() < 40 && pixel.getBlue() < 160 
         && pixel.getGreen() > 220) { 
        pixel.setColor(Color.white); 
       } 
      } 
     } 
    } 

&&是一條捷徑AND:x && y()不會叫y是x是假的。

注意pic.getPixel。如果removeGreen用作Picture的方法,則刪除參數和static關鍵字,並刪除pic.

public static void testRemoveGreen() { 
    Picture me = new Picture("IMG_7320.JPG"); 
    me.explore(); 
    removeGreen(me); 
    me.explore(); 
} 

由於.jpg,JPEG格式不具有透明度,因此需要將某些顏色(如白色)顯示爲「背景」。

相關問題