Skip to content

Instantly share code, notes, and snippets.

@freegroup
Forked from zz85/otsu.js
Created June 5, 2020 22:46
Show Gist options
  • Select an option

  • Save freegroup/380adf00adf87432cc3e627f3904d205 to your computer and use it in GitHub Desktop.

Select an option

Save freegroup/380adf00adf87432cc3e627f3904d205 to your computer and use it in GitHub Desktop.

Revisions

  1. @zz85 zz85 revised this gist Nov 7, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion otsu.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    // Read https://en.wikipedia.org/wiki/Otsu%27s_method
    // 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;
  2. @zz85 zz85 created this gist Nov 7, 2016.
    37 changes: 37 additions & 0 deletions otsu.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // Read https://en.wikipedia.org/wiki/Otsu%27s_method

    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;
    }