How threshold any image (for black and white color separation) in java?

问题描述 投票:0回答:2

已解决:问题是“jpeg 压缩”。另存为“.png”有效。

我使用 java 中的 canny 过滤器程序检测了图像的边缘。 应用过滤器后......

This is my image 如果放大... Zoomed

都有深浅不一的黑色和白色。
我希望我所有的边缘像素都是纯白色(#FFFFFF),其余部分是黑色。

注意:除了上面的(#F7F7F7)之外,不同的像素可能有不同的阴影。上面的缩放图像只是一个例子。

编辑: 我写了这段代码来对图像生效......

public void convert(){
    try{
        BufferedImage img = ImageIO.read(new File("input.jpg"));
        int rgb;
        int height = img.getHeight();
        int width = img.getWidth();
        File f = new File("newThreshold.jpg");
        Color white = new Color(255,255,255);
        int wh = white.getRGB();

        for (int h = 0; h<height; h++){
            for (int w = 0; w<width; w++){  

                rgb = img.getRGB(w, h);
                red = (rgb & 0x00ff0000) >> 16;
                green = (rgb & 0x0000ff00) >> 8;
                blue  =  rgb & 0x000000ff;
                if(red >= 200 || blue >= 200 || green >= 200){
                     img.setRGB(w,h,wh);
                }
            }
        }

        ImageIO.write(img,"jpg",f);
    }
    catch(Exception e){
    }
}

即使在运行代码之后,我的图像也没有任何变化。
即使红色、绿色和蓝色值在 200 以上,我的图像也没有改变。

更新:将图像保存为“.png”而不是“.jpg”有效!

java image png jpeg
2个回答
2
投票

您可以遍历图像中的每个像素并确定它是否高于某个阈值,如果将其值设置为纯白色。如果需要,您也可以对较暗的区域执行相同的操作。

例子:

public Image thresholdWhite(Image in, int threshold)
{
    Pixel[][] pixels = in.getPixels();
    for(int i = 0; i < pixels.length; ++i)
    {
        for(int j = 0; j < pixels[i].length; ++j)
        {
            byte red = pixels[i][j].getRed();
            byte green = pixels[i][j].getGreen();
            byte blue = pixels[i][j].getBlue();
            /* In case it isn't a grayscale image, if it is grayscale this if can be removed (the block is still needed though) */
            if(Math.abs(red - green) >= 16 && Math.abs(red - blue) >= 16 && Math.abs(blue- green) >= 16)
            {
                if(red >= threshold || blue >= threshold || green >= threshold)
                {
                    pixels[i][j] = new Pixel(Colors.WHITE);
                }
            }
        }
    }
    return new Image(pixels);
}

-1
投票

这是我作为 Java 开发人员的建议。

https://gist.github.com/angstyloop/37d4454442beea452b718bb11469f2a4

© www.soinside.com 2019 - 2024. All rights reserved.