Script for finding max brightness and correcting B&C values


I would need a script, which would find a maximum brightness on an image stack and then correct the Brightness/Contrast settings to a minimum display value of 0 and maximum display value of e.g. 0.9-times the brightness maximum.

Currently, I am doing this manually. I have an image stack (16-bit images in grayscale), I run histogram on the stack (CTRL+h) then I look at the log scale of the histogram (so I can see the few pixels at the max values) and manually correct the Brightness/Contrast settings. I have hundreds of stacks with different max brightness. Usually, the images have only a few pixels near the maximum so I visually decide what max value to use (e.g. 0.9 of the max intensity – i.e. 10% below the max brightness).

Is there a way to automate this? The best way would probably be a script, which I would run on all open stacks and where I could manually change the max intensity factor.



You can find an IJ macro in the link below, that emulates ImageJ automatic brightness & contrast button.

Maybe modify the code for your own purpose.


Hi Kota,

thank you for the macro. It works but only on individual image within the stack. In my stacks (i.e., videos) there are 135 images (frames) and I need to do histogram on all images in the stack. From such histogram I need to then find the max brightness and apply it to all images in the stack. Would it be possible to write such macro? Usually I have 135 images in the stack but this number changes from video to video so it should be a parameter in the macro.

Below are my modifications of the macro. My stack images are 128x64 pixel in size and 16-bit greyscale (nBins=4095).

Thank you,

 limit = pixcount/1;
 threshold = pixcount/AUTO_THRESHOLD;
 nBins = 4095;
 getHistogram(values, histA, nBins);
 i = -1;
 found = false;
 do {
         counts = histA[++i];
         if (counts > limit) counts = 0;
         found = counts > threshold;
 }while ((!found) && (i < histA.length-1))
 hmin = values[i];
 i = histA.length;
 do {
         counts = histA[--i];
         if (counts > limit) counts = 0; 
         found = counts > threshold;
 } while ((!found) && (i > 0))
 hmax = values[i];

 setMinAndMax(hmin, hmax);
 print(hmin, hmax);

Hi again,

I did not check the code in detail, but I guess it will be easy to get the max of pixel values in the stack if you use the function

Stack.getStatistics(voxelCount, mean, min, max, stdDev)


Great, it works! Thank you for pointing to the function.