Improving macro for speed - pixel value replacement

I have large 3D volumes with many blobs of unique value on black background, so blob #1 has value “1” … blob #n had value “n”. Now I need “n” indivudual stacks with only one blob in it for further processing.
Currently this macro achieves what I need:

Stack.getStatistics(voxelCount, mean, min, n, stdDev);
digits = lengthOf( toString(n,0)); 
for (i = 1; i <= n; i++) {
  run("Duplicate...", "title=blob"+i+" duplicate");
  code = "if(v=="+i+"){v=255;}else{v=0;}";
  run("Macro...", "code="+code+"; stack");
  i2s = i;
  while (lengthOf(""+i2s)<digits) i2s="0"+i2s; //fills leading zeros
  saveAs("Tiff", "blob"+i2s+".tif");

I think that the slowest part is the run("Macro..." line. Does anyone have a clever idea to replace this clumsy replacement by a faster operation?
I am sure there are solutions, but I probably look/search with the wrong terms…

You just want to set the values in your stack a certain way?
Maybe the Math operations are faster:

run("Set...", "value=1 stack");

If you want to stick to imagej macro then you can try this:
Batch mode, which also runs faster: setBatchMode(true)
Maybe Clij offers you some performance gains:

Thank you for the anser, but thats not what I need.
My code sets all pixels with value “i” to 255 an all other pixels to 0.
Your line would set the value all pixels in stack to 1.
Of course my code snipplet is running inside setBatchMode(true), I left it out here to shorten the code.

Ok, sorry.
The MorphoLibJ Plugins offer to select specific labels based on grey value:
Select Label(s) enters a set of labels, and creates a new label image containing only the selected labels.

I tested it, it is quite a bit faster then the Macro option.

If you want you could explain what you want to do in general.
Then one could propose other ideas…

Great, the hint with MorphoLib is the solution. Thank you.
In my case it runs now in 1/10th of the time - sufficiently fast :smiley:

All what I did is the replace of the run("Macro..."-part by:

run("Select Label(s)", "label(s)="+i);
setMinAndMax(0, 1);
1 Like