How to binarize image using im4java?

579 Views Asked by At

I want to turn my color image into B&W. Basically, I want to call this ImageMagick command:

convert input.png -threshold 80% output.png

but using the im4java library. I'm aware of the IMOperation.threshold() method, but I don't know how to write the equivalent of the above command using that method. The method is overloaded:

threshold() 

threshold(java.lang.Integer red) 

threshold(java.lang.Integer red, java.lang.Integer green) 

threshold(java.lang.Integer red, java.lang.Integer green, java.lang.Integer blue)

threshold(java.lang.Integer red, java.lang.Integer green, java.lang.Integer blue,
  java.lang.Integer opacity) 

threshold(java.lang.Integer red, java.lang.Integer green, java.lang.Integer blue,
  java.lang.Integer opacity, java.lang.Boolean percent) 

I tried calling different overloads of the method using different values as arguments, but none of them produce a good result (I usually get either an all white image or an all black image).

So what's the im4java equivalent of "threshold 80%"?

2

There are 2 best solutions below

0
On BEST ANSWER

Apparently, I needed to use blackThreshold:

op.blackThreshold(80.0, true);

I'm not sure if it's equivalent to the ImageMagick command I specified, the output seems a bit different, but for all practical purposes it gives me what I needed.

0
On

Just in the case you're considering other Java frameworks. Using Marvin Image Processing Framework:

MarvinImage image = MarvinImageIO.loadImage('image.jpg');
blackAndWhite(image, 30);

Example of output regarding different BW levels:

enter image description here