【问题标题】:How to convert a BufferedImage to black and white?如何将 BufferedImage 转换为黑白?
【发布时间】:2013-09-26 18:22:04
【问题描述】:

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

我该怎么做?

如果需要保存图像/从磁盘加载图像,我可以根据需要这样做。

编辑: 测试代码:

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();
        }
    }
}

使用的图片:

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

【问题讨论】:

  • 喜欢this?
  • @AndrewThompson 是的,就像那个灰度示例一样!它会完全将所有颜色转换为灰色和白色吗?
  • @AndrewThompson 好吧,我已经尝试过了,但是图像中的其他颜色仍然存在,它不是完全灰色/白色。还有其他建议吗?
  • @AndrewThompson 谢谢,完成
  • @AndrewThompson 好吧,我会在允许的时候接受我的 :)

标签: java image bufferedimage monochrome


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多