【问题标题】:How to convert color image to pure black and white image(0-255 format)如何将彩色图像转换为纯黑白图像(0-255格式)
【发布时间】:2013-01-28 20:25:58
【问题描述】:
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;
        }
}

我得到了一张黑白输出图像,但是当我放大图像时,我发现了一些灰色区域。我希望输出图像只包含黑色或白色。

请让我知道我目前的方法是正确还是不正确?如果我是,请建议另一种方式。

【问题讨论】:

  • 你为什么关心alpha

标签: java image swing image-processing bufferedimage


【解决方案1】:

您正在正确地将图像从彩色转换为黑白;但是,当您将输出另存为JPEG 时,会根据lossy compression 创建一些颜色。

只需将输出保存到PNG(或JPEG 以外的任何位置),输出将只有黑白,如您所料。

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

例如,如果您有一个保存为PNG 的二值图像,则直方图可能类似于(仅限黑白像素):

对于同一张图片,如果你保存为JPEG,你可以看到直方图中白色和黑色附近的一些像素开始出现

【讨论】:

  • 是的,除了JPEG 我只是举个例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 2011-08-25
  • 2021-05-02
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多