Global image threshold using Otsu's method
T = graythresh(
T from grayscale image
I, using Otsu's method .
Otsu's method chooses a threshold that minimizes the intraclass variance of the
thresholded black and white pixels. The global threshold
can be used with
imbinarize to convert a
grayscale image to a binary image.
Convert Intensity Image to Binary Image Using Level Threshold
Read a grayscale image into the workspace.
I = imread('coins.png');
Calculate a threshold using
graythresh. The threshold is normalized to the range [0, 1].
level = graythresh(I)
level = 0.4941
Convert the image into a binary image using the threshold.
BW = imbinarize(I,level);
Display the original image next to the binary image.
I — Grayscale image
Grayscale image, specified as a numeric array of any dimensionality. The
graythresh function converts multidimensional arrays
to 2-D arrays using the
reshape function, and ignores any
nonzero imaginary part of
T — Global threshold
Global threshold, returned as a nonnegative number in the range [0, 1].
EM — Effectiveness metric
Effectiveness metric of the threshold, returned as a nonnegative number in the range [0, 1]. The lower bound is attainable only by images having a single gray level, and the upper bound is attainable only by two-valued images.
By default, the function
imbinarizecreates a binary image using a threshold obtained using Otsu’s method. This default threshold is identical to the threshold returned by
imbinarizeonly returns the binary image. If you want to know the level or the effectiveness metric, use
 Otsu, N., "A Threshold Selection Method from Gray-Level Histograms." IEEE Transactions on Systems, Man, and Cybernetics. Vol. 9, No. 1, 1979, pp. 62–66.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
graythresh supports the generation of C
code (requires MATLAB®
Coder™). For more information, see Code Generation for Image Processing.