For loop based on nSlices

Does anyone know how to create a for loop that will flip through each slice and perform a task? I am trying to write a macro that will perform an action on every slice of a stack but want it to run based on “nSlices” and not a certain number.

something that will loop from 1-nSlices in one slice increments.

Thank you!

Hello Richard -

You can use the IJ macro language (ijm) to query a stack for
its number of slices.

See:

Built-in Macro Functions

and search the web page for:

“Stack.getDimensions”

Here is an example macro that prints out the number of slices
in an open stack, and then sets the stack to display its last
slice:

Stack.getDimensions (width, height, channels, slices, frames)
print ("slices = " + slices)
Stack.setSlice (slices)

Thanks, mm

Hi @mountain_man,

nSlices doesn’t seem to be working for me in for loops involving stacks. I am using Fiji, ImageJVersion 2.1.0/1.53e, Build 5f3140693; MacOS 10.15.6.

Using a stack made from Blobs.gif (or tif stacks that I tried), this workaround works as expected:

run("Blobs (25K)");
run("Duplicate...", " ");
run("Duplicate...", " ");
run("Images to Stack", "name=Stack title=blobs use");
getDimensions(width, height, channels, slices, frames);
for (zslice = 1; zslice <= slices; zslice++) {
	print("zslice="+zslice);
	selectWindow("Stack");
	Stack.setSlice(zslice);
	run("Duplicate...", "title=temp"+zslice);
}

but this version, using nSlices, gets stuck at the first loop:

run("Blobs (25K)");
run("Duplicate...", " ");
run("Duplicate...", " ");
run("Images to Stack", "name=Stack title=blobs use");
for (zslice = 1; zslice <= nSlices; zslice++) {
	print("zslice="+zslice);
	selectWindow("Stack");
	Stack.setSlice(zslice);
	run("Duplicate...", "title=temp"+zslice);
}

Thanks.

Guy

1 Like

Hi @Guy,

nSlices is a function, not a number. See inline documentation:

So the moment you duplicate your image the nSlices will return the new number. Try it by adding print(nSlices) as last line of your loop.

So what do to? you could write slices=nSlices before the loop ad then use slices as upper limit.

But I really recommend you to stick with getDimensions(width, height, channels, slices, frames) instead. nSlices does not behave for hyperstacks as intuitively expected (it counts all frames, zslices, channels together) - try it with the mitosis.tif sample data set.

3 Likes