Java 如何将 BufferedImage 转换为黑白?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18932415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:37:24  来源:igfitidea点击:

How to convert a BufferedImage to black and white?

javaimagebufferedimagemonochrome

提问by user2790209

How can I convert an existing colored BufferedImage to monochrome? I want the image to be completely split between only two rgb codes, black and white. So if there's a border around the image which is a lighter or darker shade of the background, and the background is being converted to white, then I want the border to be converted to white as well, and so on.

如何将现有的彩色 BufferedImage 转换为单色?我希望图像仅在两个 rgb 代码(黑色和白色)之间完全分割。因此,如果图像周围有一个边框,它是背景的较浅或较深的阴影,并且背景正在转换为白色,那么我希望边框也转换为白色,依此类推。

How can I do this?

我怎样才能做到这一点?

If its necessary to save the image / load it from disk, I can do that if necessary.

如果有必要保存图像/从磁盘加载它,我可以在必要时这样做。

Edit:Code to test this:

编辑:代码来测试这个:

package test;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashSet;
import javax.imageio.ImageIO;

public class Test
{
    public static void main(String[] args)
    {
        try
        {
            BufferedImage img = ImageIO.read(new File("http://i.stack.imgur.com/yhCnH.png") );
            BufferedImage gray = new BufferedImage(img.getWidth(), img.getHeight(),
                    BufferedImage.TYPE_BYTE_GRAY);

            Graphics2D g = gray.createGraphics();
            g.drawImage(img, 0, 0, null);

            HashSet<Integer> colors = new HashSet<>();
            int color = 0;
            for (int y = 0; y < gray.getHeight(); y++)
            {
                for (int x = 0; x < gray.getWidth(); x++)
                {
                    color = gray.getRGB(x, y);
                    System.out.println(color);
                    colors.add(color);
                }
            }

            System.out.println(colors.size() );
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Image used:

使用的图像:

image

图片

Using this, I get the output of 24 as the last output, i.e there were 24 colors found in this image, when there should be 2.

使用这个,我得到 24 的输出作为最后一个输出,即在这个图像中发现了 24 种颜色,而应该有 2 种颜色。

采纳答案by user2790209

The solution was to use BufferedImage.TYPE_BYTE_BINARYas the type rather than TYPE_BYTE_GRAY. Using BINARY causes a pure black & white copy of the image to be created, with no colors except b & w. Not pretty looking, but perfect for things like OCR where the colors need to be exact.

解决方案是使用BufferedImage.TYPE_BYTE_BINARYas 类型而不是TYPE_BYTE_GRAY. 使用 BINARY 会创建图像的纯黑白副本,除了黑白之外没有其他颜色。看起来不漂亮,但非常适合像 OCR 这样的颜色需要精确的东西。