# Math behind image stacking?

I couldn’t find any real answer as to how Fiji adds up pixels, i.e. the actual the actual math, and not intuitive explanations.

Does anyone have any information on this?

What exactly do you mean by “image stacking”? Are you talking of the different projection methods in Image > Stacks > Z Project…?

You can have a look at the source code of e.g. the `ij.plugin.ZProjector` class:

2 Likes

Yes, that’s exactly what I mean by image stacking

I don’t do much (= any, at all) coding, and I can’t really figure out what’s going on.

Say I have 5 images, each a single pixel, that I want to stack with the SD method. The pixel values are

2
15
169
255
112

The mean is 111 and the standard deviation is 106. What does this mean then? Three of the images are within mean +/- stdev, and are thus accepted. Are they then summed? How? 15+169+112 is 296, but this is outside the 8-bit range of 0-255. What then? This would mean that stacking turns all my images into oversaturated blobs, but that’s not the case.

How does it work? I hope I’m not making a fool of myself

Consider the following macro for illustration (just copy and paste it to the script editor, choose Language > IJ1 Macro, and press Run):

``````// Create five single-pixel images with different values
newImage("Value 2", "8-bit black", 1, 1, 1);
setPixel(0, 0, 2);
newImage("Value 15", "8-bit black", 1, 1, 1);
setPixel(0, 0, 15);
newImage("Value 169", "8-bit black", 1, 1, 1);
setPixel(0, 0, 169);
newImage("Value 255", "8-bit black", 1, 1, 1);
setPixel(0, 0, 255);
newImage("Value 112", "8-bit black", 1, 1, 1);
setPixel(0, 0, 112);
run("Images to Stack", "name=Stack title=[] use");

// Create SD projection
selectWindow("Stack");
run("Z Project...", "projection=[Standard Deviation]");
print("Result of the 'Standard Deviation' projection: " + getPixel(0,0));

// Create Mean projection
selectWindow("Stack");
run("Z Project...", "projection=[Average Intensity]");
print("Result of the 'Average Intensity' projection: " + getPixel(0,0));
``````

Running this macro will produce the following result:

``````Result of the 'Standard Deviation' projection: 106.2982
Result of the 'Average Intensity' projection: 110
``````

Each pixel of the resulting image is generated by calculating the standard deviation (or the mean) of all pixels along its x,y position on the z axis.

The only inconsistency here is that ‘Standard Deviation’ will produce a 32-bit float image (hence the exact number), whereas ‘Average Intensity’ will be 8-bit, the same as the input stack. That’s why the mean value of 110.6 is clipped to the integer value of 110 in your case.

Hope that clarifies your issue

3 Likes