By local here is meant that the threshold is computed for each pixel according to the image characteristings within a window of radius r (in pixel units) around it. The segmented phase is always shown as white (255). 1
For global thresholding rather than local, see Global Thresholding in Java.
ImageJ Auto Local Threshold plugin is an open source Java implementation that brings us nine local thresholding methods for processing and analyzing scientific images, converting them to black and white.
To use ImageJ as a library in your Maven project, add the dependency: 2
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.53j</version>
</dependency>
Copy the Auto Local Threshold method of your choice from https://github.com/fiji/Auto_Local_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Local_Threshold.java to your project
- duplicateImage
- required for all methods.
- Bernsen
- Contrast
- Mean
- Median
- MidGrey
- Niblack
- Otsu
- Phansalkar
- Sauvola
After the image is in memory as a BufferedImage bufferedImage
object, you need to load it into an ImageJ ImagePlus
object and pass it as a parameter to the chosen method.
ImagePlus imagePlus = new ImagePlus();
imagePlus.setImage(bufferedImage);
Bernsen(imagePlus, 15, 0, 0, true);
imagePlus.updateAndDraw();
imagePlus.getProcessor().setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
bufferedImage = imagePlus.getBufferedImage();
Now that your image has only white and black values, you can use a TYPE_BYTE_BINARY
BufferedImage
.
BufferedImage bwBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics2D = bwBufferedImage.createGraphics();
graphics2D.drawImage(bim, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), null);
graphics2D.dispose();