Extract all pixels having certain value (IJ2 ops)

Hi there,

I am looking for an easy way to extract all pixels having certain value from an image. I have tried the obvious:

ops.eval("image == value", {image": image, "value": value }

but apparently binary ops are not implemented for images. I would like to avoid iterating over all pixels (because that’s slow in Jython).

Hi @radoslaw.ejsmont,

That would be nice but’s not implemented (yet). See this thread for more info:



Hi @radoslaw.ejsmont,

That should be easy enough through the Cursor interface, or through a localizing cursor depending on what info you need from the voxels. For example, if you just need to know the number of pixels above certain value x you can call:

ImgPlus<T| imgplus;
Cursor<T> cursor = imgPlus.cursor();
final DoubleType count = new DoubleType();
cursor.forEach(voxel -> {
  if (voxel.getRealDouble() >= t) {

Best regards,

Yeah, I know… But it’s super slow in Python…

What about the ops in the Threshold namespace? They work with the same principle, but at least the “heavy-lifting” would happen in Java

ops.threshold.apply only works with values above… I know I could invert image, apply properly calculated inverse threshold, multiply the two and get the mask I want, but then I may as well just go with localizing cursor :slight_smile:

1 Like

Ended up using legacy API (best performance):

ImageMath.applyMacro(ip, "v=(v==" + str(value) +")", False)


See also this related issue:

On which kind of images are you running this? I assume that it runs just fine on non-Float/DoubleType images but could give you a headache for those. Did you check how == is implemented on floats in the macro language?

16-bit - so that was just fine

I wish I had more time (maybe in the summer) to play with ops.math and ops.binary and port them to non-scalar values. Ideally you should be able to do ops.eval("((img == a) || (img == b)) * img", {'img': img, 'a': a, 'b': b}) for example :wink:

1 Like