2013-02-13 184 views
8
public class BlackWhite { 

    public static void main(String[] args) 
    { 
     try 
     { 
     BufferedImage original = ImageIO.read(new File("colorimage")); 
     BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(),BufferedImage.TYPE_BYTE_BINARY); 

     int red; 
     int newPixel; 
     int threshold =230; 

      for(int i=0; i<original.getWidth(); i++) 
      { 
       for(int j=0; j<original.getHeight(); j++) 
       { 

        // Get pixels 
        red = new Color(original.getRGB(i, j)).getRed(); 

        int alpha = new Color(original.getRGB(i, j)).getAlpha(); 

        if(red > threshold) 
        { 
         newPixel = 0; 
        } 
        else 
        { 
         newPixel = 255; 
        } 
        newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel); 
        binarized.setRGB(i, j, newPixel); 

       } 
      } 
      ImageIO.write(binarized, "jpg",new File("blackwhiteimage")); 
     } 
     catch (IOException e) 
     { 
       e.printStackTrace(); 
     }  
    } 

    private static int colorToRGB(int alpha, int red, int green, int blue) { 
      int newPixel = 0; 
      newPixel += alpha; 
      newPixel = newPixel << 8; 
      newPixel += red; newPixel = newPixel << 8; 
      newPixel += green; newPixel = newPixel << 8; 
      newPixel += blue; 

      return newPixel; 
     } 
} 

我得到了一個黑白輸出圖像,但是當我放大圖像時,我發現了一些灰色區域。我希望輸出圖像只包含黑色或白色。如何將彩色圖像轉換爲純黑白圖像(0-255格式)

請讓我知道,如果我在我目前的做法是正確或不正確的?如果我是,請以另一種方式提出建議。

+0

你爲什麼關心'alpha'? – TheBronx 2013-02-13 10:15:29

回答

16

您正在將圖像從顏色正確地轉換爲黑色和白色;但是,在將輸出保存爲JPEG時,由於lossy compression的結果會創建一些顏色。

只需將輸出保存到PNG(或JPEG以外的任何其他位置),並且輸出將只有黑白兩色,正如您所期望的那樣。

ImageIO.write(binarized, "png",new File("blackwhiteimage")); 

例如,如果你有一個保存爲PNG二進制圖像直方圖可以是這樣的(僅適用於嚴格的黑色和白色像素):

PNG histogram

而對於相同的圖像,如果您保存爲JPEG,您可以看到在直方圖中,白色和黑色附近的一些像素開始出現

JPEG histogram

+0

或gif,tif,bmp,... – Junuxx 2013-02-13 10:14:11

+0

除了'JPEG'外,其他都沒有,我只是舉了一個例子 – iTech 2013-02-13 10:14:46

+0

謝謝它的作品:) – Yogesh 2013-02-13 10:15:34

相關問題