Skip to content

Instantly share code, notes, and snippets.

@freegroup
Forked from zz85/otsu.js
Created June 5, 2020 22:46
Show Gist options
  • Save freegroup/380adf00adf87432cc3e627f3904d205 to your computer and use it in GitHub Desktop.
Save freegroup/380adf00adf87432cc3e627f3904d205 to your computer and use it in GitHub Desktop.
Otsu's method - Automatic Histogram Based Image Thresholding
// Read https://en.wikipedia.org/wiki/Otsu%27s_method (added this since JS examples in wikipedia didn't work)
function otsu(histData /* Array of 256 greyscale values */, total /* Total number of pixels */) {
let sum = 0;
for (let t=0 ; t<256 ; t++) sum += t * histData[t];
let sumB = 0;
let wB = 0;
let wF = 0;
let varMax = 0;
let threshold = 0;
for (let t=0 ; t<256 ; t++) {
wB += histData[t]; // Weight Background
if (wB == 0) continue;
wF = total - wB; // Weight Foreground
if (wF == 0) break;
sumB += t * histData[t];
let mB = sumB / wB; // Mean Background
let mF = (sum - sumB) / wF; // Mean Foreground
// Calculate Between Class Variance
let varBetween = wB * wF * (mB - mF) * (mB - mF);
// Check if new maximum found
if (varBetween > varMax) {
varMax = varBetween;
threshold = t;
}
}
return threshold;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment