Search code examples
javaimage-processingcolorsimagemagickim4java

How to binarize image using im4java?


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%"?


Solution

  • 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.