简体   繁体   中英

How to threshold and BufferedImage in Java

I have read my original image as BufferedImage in Java and then following some operations, I am trying to threshold my image to either high(255) or low(0) but when I save my image, actually I try to overwrite it with new values, the pixels value are not only 0 and 255, some neighbouring values appear, I don't understand why.

READING MY IMAGE

File input = new File("/../Screenshots/1.jpg");
BufferedImage image = ImageIO.read(input);
for (int i = 0; i < image.getWidth(); i++) {
        for (int j = 0; j < image.getHeight(); j++) {
            Color c = new Color(image.getRGB(i, j));
            powerspectrum[i][j] = (int) ((c.getRed() * 0.299)
                    + (c.getGreen() * 0.587) + (c.getBlue() * 0.114));
        }
    }

THRESHOLDING MY IMAGE

for (int i = 0; i < image.getWidth(); i++) {
        for (int j = 0; j < image.getHeight(); j++) {
            if (gradient[i][j] <= upperthreshold
                    && gradient[i][j] >= lowerthreshold)
                spaces[i][j] = 255;
            else
                spaces[i][j] = 0;
            Color gradColor = new Color(spaces[i][j], spaces[i][j],
                    spaces[i][j]);
            image.setRGB(i, j, gradColor.getRGB());
        }
    }

SAVING MY IMAGE

File gradoutput = new File("/../Screenshots/3_GradThresh.jpg");
    ImageIO.write(image, "jpg", gradoutput);

I don't know how to cut off the other intensity values.

I suspect this is because JPG is a lossy format. When you are saving a JPG to disk, it is doing compression. Try working with bitmap to see if that removes these neighboring gray area values.

+1 with the jpg compression issue. In image processing, we use PNG (best compression format without loss) or TIFF (worst scenario).

Btw, the methods setRGB/getRGB have terrible performances. The fastest is to modify directly the DataBuffer, but you have to do it for each type of image encoding. An alternative solution (but slower) is to use the Raster. Then you don't have to worry about the encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM