Histogram black and white pixel count for multiple ROIs


First post here. I am trying to write a macro that will threshold and binarize an image then import pre-constructed ROIs (attached here) and count the number of white and black pixels in each ROI, then save these results in an excel file. Once I get the macro to work I will batch process ~20-40 images.

So far I have gotten to importing the ROIs successfully.

The macro I wrote to get the histogram information from each ROI only reports the information from the first ROI in the results table.

My macro is below and ROIs are attached.RoiSet.zip (1.8 KB)

//Thresholding and binarizing
run("Auto Local Threshold...", "method=Phansalkar radius=15 parameter_1=0 parameter_2=0 white");
setOption("BlackBackground", true);

//importing the ROIs
run("ROI Manager...");
roiManager("Open", "/Users/Desktop/RoiSet.zip");

//get histogram values for each ROI
selectWindow("ROI Manager");
roiCount = roiManager("count");
for (i=0; i<roiCount; i++) {
    roiManager("select", i);
    nBins = 256;
    getHistogram(value, count, nBins);
    for (i=0; i<nBins; i++) {
      setResult("Count", i, count[i]);


the idea is correct, there is only a simple error in your macro. You use i as the variable in both for loops the outer and the inner. Just use a different counter variable in the inner loop and it should work.

Best regards,

Hi Volker,

Thank you for your reply. It worked but I am still seeing the results for the last ROI in the results table instead of the histogram results for all 6 of my ROIs. Please see attached picture.

Ideally I would get the counts for 0 and 255 for each ROI printed in the results table after I run the macro but I cannot figure out how to do that.

Thank you again for your help!