Otsu's Method is way of implementing automatic thresholding. It is a binarization algorithm which can be used to select the optimal threshold between foreground and background quantities based on finding the minimum point of cross variance. This is particularly useful when performing segmentation in image processing.
You can find an awesome description of the algorithm, which inspired this repository, here.
Using npm
:
npm install --save otsu
Using yarn
:
yarn add otsu
It's really simple to find the threshold of your image. All you have to do is supply the data!
In the example below, we have a one-dimensional array of intensity data. Most greyscale image formats, such as MNIST, can be fed directly into otsu this way. However, images that consist of multiple attributes per pixel (such as (r,g,b)
) will first require pre-processing.
import otsu from 'otsu';
const intensity = [255, 0, 128, 4, 95 ...];
const t = otsu(intensity);
console.log(t); // i.e. 128
const thresholded = intensity.map(e => (e > t ? 1 : 0));