Percentile Thresholding

I’m trying to use percentile thresholding on my images. The default option in ImageJ I believe is 0.5, but I would like it to be 0.8. I had a browse through the forums and found the following macro:

percentage = 80; 
nBins = 256; 
resetMinAndMax(); 
getHistogram(values, counts, nBins); 
// find culmulative sum 
nPixels = 0; 
for (i = 0; i<counts.length; i++) 
  nPixels += counts[i]; 
nBelowThreshold = nPixels * percentage / 100; 
sum = 0; 
for (i = 0; i<counts.length; i++) { 
  sum = sum + counts[i]; 
  if (sum >= nBelowThreshold) { 
    setThreshold(values[0], values[i]); 
    print(values[0]+"-"+values[i]+": "+sum/nPixels*100+"%"); 
    i = 99999999;//break 
  } 
} 

Would this give me the correct thresholding values? It seems like this is something that could be adjusted in the thresholding sliders.

Thanks,

1 Like

I tried testing this with a ramp image. I went to file->new->image and chose type=‘8-bit’’,fill with=‘ramp’

It calculated a threshold of 204… 204/256=0.79something. So it looks to me like it works as intended.

And yes, this can also be adjusted with the sliders, image->adjust->threshold brings up a popup. The ‘percentage’ of pixels that are within the threshold(s) is visible just above the slider.

2 Likes

hey, sorry to dredge this up. what would i add to the macro such that the background is black instead of white? cheers.

@BirthingXS Did you check the value of Process :arrow_forward: Binary :arrow_forward: Options…?

You can toggle it in macro code using:

setOption("BlackBackground", true);