Additionally, Z should be initialised
to:
Z = nSlices();
getSliceNumber() returns the index of the current slice, not the
number of slices in the stack.
See
http://rsbweb.nih.gov/ij/developer/macro/functions.html for
documentation on macro functions.
For historical reasons, slice numbers start at 1 so you are
correct to iterate from 1 to Z inclusive (i.e. with a <=) .
But, (x,y) coordinates start at 0 so you must end your row and
column loops with < and not <= else you will go beyond the
end of the pixel array.
Michael