Macro for batch saving of histogram results

Hello
I want to create a macro for batch operation on a folder of files. It should record the pixel counts of the binarised images (therefore I only need value = 0 or value = 255) and save them ideally all to one excel sheet with the filenames and the pixel counts in two columns. Here is my very messy macro which I hope can be easily polished!

dir1 = getDirectory("Choose Source Directory ");
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);
setBatchMode(true);
nBins = 256;

for (i=0; i<list.length; i++) {
 showProgress(i+1, list.length);
 open(dir1+list[i]);
 setOption("BlackBackground", false);
getHistogram(value, count, nBins);
run("Histogram");
setResult("Value", i, value[i]);
setResult("Count", i, count[i]);
updateResults();
run("Read and Write Excel");
 close();
}

Hello,
I know this is super late but did you ever figure out how to do this? I’m looking to save the y start distribution histogram Bin start points as well as each bin’s count to a csv file

Hi @Andy_Speak

On the off chance this is still helpful, I just had a quick look at this. I don’t quite understand why you’re using the variable i both to iterate the file list and to pull the count and value index. For each image you will only get the i’th value from the histogram.

If you’re trying to simply count the number of positive (or negative) pixels in your binary images, you can do this more easily by measuring the Raw Integrated Density and dividing this by 255. Here is a snippet adjusting your code to make this measurement then save (for each file) a row in a tab separated output file (which can be opened in Excel).

Capture

@cqferrier
You can use the same framework to output the CSVs, however it’s unclear exactly what you want. Are you working with Binary Masks? I would suggest adapting the framework above but using

getHistogram(values, counts, nBins[, histMin, histMax])

(link)

to pull the histogram values then use

Array.show("title", array1, array2, ...)

(link)

To create a results table which you can then save out as a csv (an alternative being to iterate through the array and use the print(f... example above (which would probably be my preference.

Anyway, if you want to clarify your question, I’m sure I or others will be happy to help.