Otsu's method

From HandWiki
Revision as of 20:29, 6 February 2024 by Scavis2 (talk | contribs) (change)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Short description: In computer vision and image processing
An example image thresholded using Otsu's algorithm
Original image

In computer vision and image processing, Otsu's method, named after Nobuyuki Otsu (大津展之, Ōtsu Nobuyuki), is used to perform automatic image thresholding.[1] In the simplest form, the algorithm returns a single intensity threshold that separate pixels into two classes, foreground and background. This threshold is determined by minimizing intra-class intensity variance, or equivalently, by maximizing inter-class variance.[2] Otsu's method is a one-dimensional discrete analogue of Fisher's Discriminant Analysis, is related to Jenks optimization method, and is equivalent to a globally optimal k-means[3] performed on the intensity histogram. The extension to multi-level thresholding was described in the original paper,[2] and computationally efficient implementations have since been proposed.[4][5]

Otsu's method

Otsu's method visualization

The algorithm exhaustively searches for the threshold that minimizes the intra-class variance, defined as a weighted sum of variances of the two classes:

[math]\displaystyle{ \sigma^2_w(t)=\omega_0(t)\sigma^2_0(t)+\omega_1(t)\sigma^2_1(t) }[/math]

Weights [math]\displaystyle{ \omega_{0} }[/math] and [math]\displaystyle{ \omega_{1} }[/math] are the probabilities of the two classes separated by a threshold [math]\displaystyle{ t }[/math] ,and [math]\displaystyle{ \sigma^2_{0} }[/math] and [math]\displaystyle{ \sigma^2_{1} }[/math] are variances of these two classes.

The class probability [math]\displaystyle{ \omega_{\{0,1\}}(t) }[/math] is computed from the [math]\displaystyle{ L }[/math] bins of the histogram:

[math]\displaystyle{ \begin{align} \omega_0(t) & =\sum_{i=0}^{t-1} p(i)\\[4pt] \omega_1(t) & =\sum_{i=t}^{L-1} p(i) \end{align} }[/math]

For 2 classes, minimizing the intra-class variance is equivalent to maximizing inter-class variance:[2]

[math]\displaystyle{ \begin{align} \sigma^2_b(t) & =\sigma^2-\sigma^2_w(t)=\omega_0(t)(\mu_0-\mu_T)^2+\omega_1(t)(\mu_1-\mu_T)^2 \\ & =\omega_0(t) \omega_1(t) \left[\mu_0(t)-\mu_1(t)\right]^2 \end{align} }[/math]

which is expressed in terms of class probabilities [math]\displaystyle{ \omega }[/math] and class means [math]\displaystyle{ \mu }[/math], where the class means [math]\displaystyle{ \mu_0(t) }[/math], [math]\displaystyle{ \mu_1(t) }[/math] and [math]\displaystyle{ \mu_T }[/math] are:

[math]\displaystyle{ \begin{align} \mu_0(t) & = \frac{\sum_{i=0}^{t-1} i p(i)}{\omega_0(t)} \\[4pt] \mu_1(t) & = \frac{\sum_{i=t}^{L-1} i p(i)}{\omega_1(t)} \\ \mu_T & = \sum_{i=0}^{L-1} ip(i) \end{align} }[/math]

The following relations can be easily verified:

[math]\displaystyle{ \begin{align} \omega_0\mu_0+\omega_1\mu_1 & = \mu_T \\ \omega_0+\omega_1 & =1 \end{align} }[/math]

The class probabilities and class means can be computed iteratively. This idea yields an effective algorithm.

Algorithm

  1. Compute histogram and probabilities of each intensity level
  2. Set up initial [math]\displaystyle{ \omega_i(0) }[/math] and [math]\displaystyle{ \mu_i(0) }[/math]
  3. Step through all possible thresholds [math]\displaystyle{ t = 1, \ldots }[/math] maximum intensity
    1. Update [math]\displaystyle{ \omega_i }[/math] and [math]\displaystyle{ \mu_i }[/math]
    2. Compute [math]\displaystyle{ \sigma^2_b(t) }[/math]
  4. Desired threshold corresponds to the maximum [math]\displaystyle{ \sigma^2_b(t) }[/math]

MATLAB implementation

histogramCounts is a 256-element histogram of a grayscale image different gray-levels (typical for 8-bit images). level is the threshold for the image (double).

function level = otsu(histogramCounts)
total = sum(histogramCounts); % total number of pixels in the image 
%% OTSU automatic thresholding
top = 256;
sumB = 0;
wB = 0;
maximum = 0.0;
sum1 = dot(0:top-1, histogramCounts);
for ii = 1:top
    wF = total - wB;
    if wB > 0 && wF > 0
        mF = (sum1 - sumB) / wF;
        val = wB * wF * ((sumB / wB) - mF) * ((sumB / wB) - mF);
        if ( val >= maximum )
            level = ii;
            maximum = val;
        end
    end
    wB = wB + histogramCounts(ii);
    sumB = sumB + (ii-1) * histogramCounts(ii);
end
end

Matlab has built-in functions graythresh() and multithresh() in the Image Processing Toolbox which are implemented with Otsu's method and Multi Otsu's method, respectively.

Python implementation

This implementation requires the NumPy library.

import numpy as np

def otsu_intraclass_variance(image, threshold):
	"""
	Otsu’s intra-class variance.
	If all pixels are above or below the threshold, this will throw a warning that can safely be ignored.
	"""
	return np.nansum([
		np.mean(cls) * np.var(image,where=cls)
		#   weight   ·  intra-class variance
		for cls in [image>=threshold,image<threshold]
	])
	# NaNs only arise if the class is empty, in which case the contribution should be zero, which `nansum` accomplishes.

# Random image for demonstration:
image = np.random.randint( 2, 253, size=(50,50) )

otsu_threshold = min(
		range( np.min(image)+1, np.max(image) ),
		key = lambda th: otsu_intraclass_variance(image,th)
	)

Python libraries dedicated to image processing such as OpenCV and Scikit-image propose built-in implementations of the algorithm.

Limitations and variations

Otsu's method performs well when the histogram has a bimodal distribution with a deep and sharp valley between the two peaks.[6]

Like all other global thresholding methods, Otsu's method performs badly in case of heavy noise, small objects size, inhomogeneous lighting and larger intra-class than inter-class variance.[7] In those cases, local adaptations of the Otsu method have been developed.[8]

Moreover, the mathematical grounding of Otsu's method models the histogram of the image as a mixture of two Normal distributions with equal variance and equal size.[9] Otsu's thresholding may however yield satisfying results even when these assumptions are not met, in the same way statistical tests (to which Otsu's method is heavily connected[10]) can perform correctly even when the working assumptions are not fully satisfied. However, several variations of Otsu's methods have been proposed to account for more severe deviations from these assumptions,[9] such as the Kittler-Illingworth method.[11]

A variation for noisy images

A popular local adaptation is the two-dimensional Otsu's method, which performs better for the object segmentation task in noisy images. Here, the intensity value of a given pixel is compared with the average intensity of its immediate neighborhood to improve segmentation results.[8]

At each pixel, the average gray-level value of the neighborhood is calculated. Let the gray level of the given pixel be divided into [math]\displaystyle{ L }[/math] discrete values and the average gray level is also divided into the same [math]\displaystyle{ L }[/math] values. Then a pair is formed: the pixel gray level and the average of the neighborhood [math]\displaystyle{ (i, j) }[/math]. Each pair belongs to one of the [math]\displaystyle{ L\times L }[/math] possible 2-dimensional bins. The total number of occurrences (frequency), [math]\displaystyle{ f_{ij} }[/math], of a pair [math]\displaystyle{ (i, j) }[/math], divided by the total number of pixels in the image [math]\displaystyle{ N }[/math], defines the joint probability mass function in a 2-dimensional histogram:

[math]\displaystyle{ P_{ij} = \frac{f_{ij}} N, \qquad \sum_{i=0}^{L-1}\sum_{j=0}^{L-1} P_{ij}=1 }[/math]

And the 2-dimensional Otsu's method is developed based on the 2-dimensional histogram as follows.

The probabilities of two classes can be denoted as:

[math]\displaystyle{ \begin{align} \omega_0 & = \sum_{i=0}^{s-1} \sum_{j=0}^{t-1} P_{ij} \\ \omega_1 & = \sum_{i=s}^{L-1} \sum_{j=t}^{L-1} P_{ij} \end{align} }[/math]

The intensity mean value vectors of two classes and total mean vector can be expressed as follows:

[math]\displaystyle{ \begin{align} \mu_0 & =[\mu_{0i}, \mu_{0j}]^T = \left[\sum_{i=0}^{s-1} \sum_{j=0}^{t-1} i \frac{P_{ij}}{\omega_0}, \sum_{i=0}^{s-1}\sum_{j=0}^{t-1} j \frac{P_{ij}}{ \omega_0} \right]^T \\ \mu_1 & =[\mu_{1i}, \mu_{1j}]^T = \left[\sum_{i=s}^{L-1}\sum_{j=t}^{L-1} i \frac{P_{ij}}{\omega_1}, \sum_{i=s}^{L-1}\sum_{j=t}^{L-1} j \frac{P_{ij}}{\omega_1} \right]^T \\ \mu_T & =[\mu_{Ti}, \mu_{Tj}]^T = \left[\sum_{i=0}^{L-1} \sum_{j=0}^{L-1} i P_{ij}, \sum_{i=0}^{L-1}\sum_{j=0}^{L-1} j P_{ij}\right]^T \end{align} }[/math]

In most cases the probability off-diagonal will be negligible, so it is easy to verify:

[math]\displaystyle{ \omega_0+\omega_1 \cong 1 }[/math]
[math]\displaystyle{ \omega_0\mu_0+\omega_1\mu_1 \cong \mu_T }[/math]

The inter-class discrete matrix is defined as

[math]\displaystyle{ S_b = \sum_{k=0}^1\omega_k[(\mu_k-\mu_T)(\mu_k-\mu_T)^T] }[/math]

The trace of the discrete matrix can be expressed as

[math]\displaystyle{ \begin{align} & \operatorname{tr}(S_b) \\[4pt] = {} & \omega_0[(\mu_{0i}-\mu_{Ti})^2 + (\mu_{0j}-\mu_{Tj})^2] + \omega_1[(\mu_{1i}-\mu_{Ti})^2 + (\mu_{1j}-\mu_{Tj})^2] \\[4pt] = {} & \frac{(\mu_{Ti}\omega_0-\mu_i)^2 + (\mu_{Tj}\omega_0-\mu_j)^2}{\omega_0(1-\omega_0)} \end{align} }[/math]

where

[math]\displaystyle{ \mu_i = \sum_{i=0}^{s-1}\sum_{j=0}^{t-1}iP_{ij} }[/math]
[math]\displaystyle{ \mu_j = \sum_{i=0}^{s-1}\sum_{j=0}^{t-1}jP_{ij} }[/math]

Similar to one-dimensional Otsu's method, the optimal threshold [math]\displaystyle{ (s,t) }[/math] is obtained by maximizing [math]\displaystyle{ \operatorname{tr}(S_b) }[/math].

Algorithm

The [math]\displaystyle{ s }[/math] and [math]\displaystyle{ t }[/math] is obtained iteratively which is similar with one-dimensional Otsu's method. The values of [math]\displaystyle{ s }[/math] and [math]\displaystyle{ t }[/math] are changed till we obtain the maximum of [math]\displaystyle{ \operatorname{tr}(S_b) }[/math], that is

max,s,t = 0;

for ss: 0 to L-1 do
    for tt: 0 to L-1 do
        evaluate tr(S_b);
        if tr(S_b) > max
            max = tr(S,b);
            s = ss;
            t = tt;
        end if
    end for
end for

return s,t;

Notice that for evaluating [math]\displaystyle{ \operatorname{tr}(S_b) }[/math], we can use a fast recursive dynamic programming algorithm to improve time performance.[12] However, even with the dynamic programming approach, 2d Otsu's method still has large time complexity. Therefore, much research has been done to reduce the computation cost.[13]

If summed area tables are used to build the 3 tables, sum over [math]\displaystyle{ P_{ij} }[/math], sum over [math]\displaystyle{ i * P_{ij} }[/math], and sum over [math]\displaystyle{ j * P_{ij} }[/math], then the runtime complexity is the maximum of (O(N_pixels), O(N_bins*N_bins)). Note that if only coarse resolution is needed in terms of threshold, N_bins can be reduced.

MATLAB implementation

function inputs and output:

hists is a [math]\displaystyle{ 256\times 256 }[/math] 2D-histogram of grayscale value and neighborhood average grayscale value pair.

total is the number of pairs in the given image.it is determined by the number of the bins of 2D-histogram at each direction.

threshold is the threshold obtained.

function threshold = otsu_2D(hists, total)
maximum = 0.0;
threshold = 0;
helperVec = 0:255;
mu_t0 = sum(sum(repmat(helperVec',1,256).*hists));
mu_t1 = sum(sum(repmat(helperVec,256,1).*hists));
p_0 = zeros(256);
mu_i = p_0;
mu_j = p_0;
for ii = 1:256
    for jj = 1:256
        if jj == 1
            if ii == 1
                p_0(1,1) = hists(1,1);
            else
                p_0(ii,1) = p_0(ii-1,1) + hists(ii,1);
                mu_i(ii,1) = mu_i(ii-1,1)+(ii-1)*hists(ii,1);
                mu_j(ii,1) = mu_j(ii-1,1);
            end
        else
            p_0(ii,jj) = p_0(ii,jj-1)+p_0(ii-1,jj)-p_0(ii-1,jj-1)+hists(ii,jj); % THERE IS A BUG HERE. INDICES IN MATLAB MUST BE HIGHER THAN 0. ii-1 is not valid
            mu_i(ii,jj) = mu_i(ii,jj-1)+mu_i(ii-1,jj)-mu_i(ii-1,jj-1)+(ii-1)*hists(ii,jj);
            mu_j(ii,jj) = mu_j(ii,jj-1)+mu_j(ii-1,jj)-mu_j(ii-1,jj-1)+(jj-1)*hists(ii,jj);
        end

        if (p_0(ii,jj) == 0)
            continue;
        end
        if (p_0(ii,jj) == total)
            break;
        end
        tr = ((mu_i(ii,jj)-p_0(ii,jj)*mu_t0)^2 + (mu_j(ii,jj)-p_0(ii,jj)*mu_t1)^2)/(p_0(ii,jj)*(1-p_0(ii,jj)));

        if ( tr >= maximum )
            threshold = ii;
            maximum = tr;
        end
    end
end
end

A variation for unbalanced images

When the levels of gray of the classes of the image can be considered as Normal distributions but with unequal size and/or unequal variances, assumptions for the Otsu algorithm are not met. The Kittler-Illingworth algorithm (also known as Minimum Error thresholding)[11] is a variation of Otsu's method to handle such cases. There are several ways to mathematically describe this algorithm. One of them is to consider that for each threshold being tested, the parameters of the Normal distributions in the resulting binary image are estimated by Maximum likelihood estimation given the data.[9]

While this algorithm could seem superior to Otsu's method, it introduces new parameters to be estimated, and this can result in the algorithm being over-parametrized and thus unstable. In many cases where the assumptions from Otsu's method seem at least partially valid, it may be preferable to favor Otsu's method over the Kittler-Illingworth algorithm, following Occam's razor.[9]

Triclass thresholding tentatively divides histogram of an image into three classes, with the TBD class to be processed at next iterations.

Iterative Triclass Thresholding Based on the Otsu's Method

One limitation of the Otsu’s method is that it cannot segment weak objects as the method searches for a single threshold to separate an image into two classes, namely, foreground and background, in one shot. Because the Otsu’s method looks to segment an image with one threshold, it tends to bias toward the class with the large variance.[14] Iterative triclass thresholding algorithm is a variation of the Otsu’s method to circumvent this limitation.[15] Given an image, at the first iteration, the triclass thresholding algorithm calculates a threshold [math]\displaystyle{ \eta_1 }[/math] using the Otsu’s method. Based on threshold [math]\displaystyle{ \eta_1 }[/math], the algorithm calculates mean [math]\displaystyle{ \mu_{upper}^{[1]} }[/math] of pixels above [math]\displaystyle{ \eta_1 }[/math] and mean [math]\displaystyle{ \mu_{lower}^{[1]} }[/math] of pixels below [math]\displaystyle{ \eta_1 }[/math]. Then the algorithm tentatively separates the image into three classes (hence the name triclass), with the pixels above the upper mean [math]\displaystyle{ \mu_{upper}^{[1]} }[/math] designated as the temporary foreground [math]\displaystyle{ F }[/math] class and pixels below the lower mean [math]\displaystyle{ \mu_{lower}^{[1]} }[/math] designated as the temporary background [math]\displaystyle{ B }[/math] class. Pixels fall between [math]\displaystyle{ [\mu_{lower}^{[1]}, \mu_{upper}^{[1]}] }[/math] are denoted as a to-be-determined (TBD) region. This completes the first iteration of the algorithm. For the second iteration, the Otsu’s method is applied to the TBD region only to obtain a new threshold [math]\displaystyle{ \eta_2 }[/math]. The algorithm then calculates the mean [math]\displaystyle{ \mu_{upper}^{[2]} }[/math] of pixels in the TBD region that are above [math]\displaystyle{ \eta_2 }[/math] and the mean [math]\displaystyle{ \mu_{lower}^{[2]} }[/math] of pixels in the TBD region that are below [math]\displaystyle{ \eta_2 }[/math]. Pixels in the TBD region that are greater than the upper mean [math]\displaystyle{ \mu_{upper}^{[2]} }[/math] are added to the temporary foreground [math]\displaystyle{ F }[/math]. And pixels in the TBD region that are less than the lower mean [math]\displaystyle{ \mu_{lower}^{[2]} }[/math] are added to the temporary background [math]\displaystyle{ B }[/math]. Similarly, a new TBD region is obtained, which contains all the pixels falling between [math]\displaystyle{ [\mu_{lower}^{[2]}, \mu_{upper}^{[2]}] }[/math]. This completes the second iteration. The algorithm then proceeds to the next iteration to process the new TBD region until it meets the stopping criterion. The criterion is that, when the difference between Otsu’s thresholds computed from two consecutive iterations is less than a small number, the iteration shall stop. For the last iteration, pixels above [math]\displaystyle{ \eta_n }[/math] are assigned to the foreground class and pixels below the threshold are assigned to the background class. At the end, all the temporary foreground pixels are combined to constitute the final foreground. All the temporary background pixels are combined to become the final background. In implementation, the algorithm involves no parameter except for the stopping criterion in terminating the iterations. By iteratively applying the Otsu’s method and gradually shrinking the TBD region for segmentation, the algorithm can obtain a result that preserves weak objects better than the standard Otsu’s method does.

References

  1. M. Sezgin; B. Sankur (2004). "Survey over image thresholding techniques and quantitative performance evaluation". Journal of Electronic Imaging 13 (1): 146–165. doi:10.1117/1.1631315. Bibcode2004JEI....13..146S. 
  2. 2.0 2.1 2.2 Nobuyuki Otsu (1979). "A threshold selection method from gray-level histograms". IEEE Transactions on Systems, Man, and Cybernetics 9 (1): 62–66. doi:10.1109/TSMC.1979.4310076. 
  3. Liu, Dongju (2009). "Otsu method and K-means". Ninth International Conference on Hybrid Intelligent Systems IEEE 1: 344–349. 
  4. Liao, Ping-Sung (2001). "A fast algorithm for multilevel thresholding". J. Inf. Sci. Eng. 17 (5): 713–727. doi:10.6688/JISE.2001.17.5.1. https://pdfs.semanticscholar.org/b809/14dbbee9f6b2455742d8117417731e6ecf12.pdf. 
  5. Huang, Deng-Yuan (2009). "Optimal multi-level thresholding using a two-stage Otsu optimization approach". Pattern Recognition Letters 30 (3): 275–284. doi:10.1016/j.patrec.2008.10.003. Bibcode2009PaReL..30..275H. 
  6. Kittler, J.; Illingworth, J. (September 1985). "On threshold selection using clustering criteria". IEEE Transactions on Systems, Man, and Cybernetics SMC-15 (5): 652–655. doi:10.1109/tsmc.1985.6313443. ISSN 0018-9472. http://dx.doi.org/10.1109/tsmc.1985.6313443. 
  7. Lee, Sang Uk and Chung, Seok Yoon and Park, Rae Hong (1990). "A comparative performance study of several global thresholding techniques for segmentation". Computer Vision, Graphics, and Image Processing 52 (2): 171–190. doi:10.1016/0734-189x(90)90053-x. 
  8. 8.0 8.1 Jianzhuang, Liu and Wenqing, Li and Yupeng, Tian (1991). "Automatic thresholding of gray-level pictures using two-dimension Otsu method". Circuits and Systems, 1991. Conference Proceedings, China., 1991 International Conference on: 325–327. 
  9. 9.0 9.1 9.2 9.3 Kurita, T.; Otsu, N.; Abdelmalek, N. (October 1992). "Maximum likelihood thresholding based on population mixture models". Pattern Recognition 25 (10): 1231–1240. doi:10.1016/0031-3203(92)90024-d. ISSN 0031-3203. Bibcode1992PatRe..25.1231K. http://dx.doi.org/10.1016/0031-3203(92)90024-d. 
  10. Jing-Hao Xue; Titterington, D. M. (August 2011). "t-Tests, F-Tests and Otsu's Methods for Image Thresholding". IEEE Transactions on Image Processing 20 (8): 2392–2396. doi:10.1109/tip.2011.2114358. ISSN 1057-7149. PMID 21324779. http://dx.doi.org/10.1109/tip.2011.2114358. 
  11. 11.0 11.1 Kittler, J.; Illingworth, J. (1986-01-01). "Minimum error thresholding" (in en). Pattern Recognition 19 (1): 41–47. doi:10.1016/0031-3203(86)90030-0. ISSN 0031-3203. Bibcode1986PatRe..19...41K. https://dx.doi.org/10.1016/0031-3203%2886%2990030-0. 
  12. Zhang, Jun; Hu, Jinglu (2008). "Image Segmentation Based on 2D Otsu Method with Histogram Analysis". 2008 International Conference on Computer Science and Software Engineering. 6. pp. 105–108. doi:10.1109/CSSE.2008.206. ISBN 978-0-7695-3336-0. 
  13. Zhu, Ningbo and Wang, Gang and Yang, Gaobo and Dai, Weiming (2009). "A fast 2d otsu thresholding algorithm based on improved histogram". Pattern Recognition, 2009. CCPR 2009. Chinese Conference on: 1–5. 
  14. Xu, Xiangyang, Xu, Shengzhou, Jin, Lianghai, and Song, Enmin (2011). "Characteristic analysis of Otsu threshold and its applications". Pattern Recognition Letters 32 (7): 956–61. doi:10.1016/j.patrec.2011.01.021. Bibcode2011PaReL..32..956X. 
  15. Cai, Hongmin, Yang, Zhong, Cao, Xinhua, Xia, Weiming, and Xu, Xiaoyin. (2014). "A new iterative triclass thresholding technique in image segmentation". IEEE Transactions on Image Processing 23 (3): 1038–46. doi:10.1109/TIP.2014.2298981. PMID 24474373. 

External links