12,821,494 members (26,298 online)
alternative version

#### Stats

107.2K views
50 bookmarked
Posted 20 Jul 2009

# Famous Otsu Thresholding in C#

, 20 Jul 2009 CPOL
 Rate this:
This article explains the basics of the famous Otsu's automatic thresholding method with an implementation in C#.

## Introduction

Thresholding is a very basic operation in image processing. And, a good algorithm always begins with a good basis! Otsu thresholding is a simple yet effective global automatic thresholding method for binarizing grayscale images such as foregrounds and backgrounds.

## Background

In image processing, Otsu’s thresholding method (1979) is used for automatic binarization level decision, based on the shape of the histogram. The algorithm assumes that the image is composed of two basic classes: Foreground and Background. It then computes an optimal threshold value that minimizes the weighted within class variances of these two classes. It is mathematically proven that minimizing the within class variance is same as maximizing the between class variance.

Otsu threshold is used in many applications from medical imaging to low level computer vision. It has many advantages and assumptions.

• Speed: Because Otsu threshold operates on histograms (which are integer or float arrays of length 256), it’s quite fast.
• Ease of coding: Approximately 80 lines of very easy stuff.

• Assumption of uniform illumination.
• Histogram should be bimodal (hence the image).
• It doesn’t use any object structure or spatial coherence.
• The non-local version assumes uniform statistics.

## Mathematical Formulation

Where q1 and q2 represent the estimate of class probabilities defined as:

and

and sigmas are the individual class variances defined as:

and

and the class means:

and

Here, P represents the image histogram. The problem of minimizing within class variance can be expressed as a maximization problem of the between class variance. It can be written as a difference of total variance and within class variance:

=

Finally, this expression can safely be maximized and the solution is t that is maximizing .

## Algorithm

Now, let's take a look at Otsu's thresholding from a more algorithmic point of view. Here are the steps of the algorithm:

For each potential threshold T, we:

1. Separate the pixels into two clusters according to the threshold.
2. Find the mean of each cluster.
3. Square the difference between the means.
4. Multiply by the number of pixels in one cluster times the number in the other.

If we incorporate a little math into that simple step-wise algorithm, such an explanation evolves:

1. Compute histogram and probabilities of each intensity level.
2. Set up initial qi(0) and μi(0).
3. Step through all possible thresholds maximum intensity.
4. Update qi and μi.
5. Compute .
6. Desired threshold corresponds to the maximum.

## Another Perception

Since Otsu operates over the histograms, it's very wise to analyze the image histogram and decision of threshold level. I think this simple image will be enough to summarize the story (the threshold value is marked by the red arrow):

## Using the Code

It's pretty simple to use the code. Otsu Thresholding works on grayscale images. So firstly, we have to convert our image into a gray scale one. After that, we can obtain our Otsu threshold value by solving for maximal t. Finally, we threshold our image using this t value. In short, the usage looks like this:

```Bitmap temp = (Bitmap)org.Clone();
ot.Convert2GrayScaleFast(temp);
int otsuThreshold= ot.getOtsuThreshold((Bitmap)temp);
ot.threshold(temp,otsuThreshold);
textBox1.Text = otsuThreshold.ToString();
pictureBox1.Image = temp;```

If we look inside the `getOtsuThreshold` function, it looks like this:

```public int getOtsuThreshold(Bitmap bmp)
{
byte t=0;
float[] vet=new float[256];
int[] hist=new int[256];
vet.Initialize();

float p1,p2,p12;
int k;

BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
unsafe
{
byte* p = (byte*)(void*)bmData.Scan0.ToPointer();

getHistogram(p,bmp.Width,bmp.Height,bmData.Stride, hist);

for (k = 1; k != 255; k++)
{
p1 = Px(0, k, hist);
p2 = Px(k + 1, 255, hist);
p12 = p1 * p2;
if (p12 == 0)
p12 = 1;
float diff=(Mx(0, k, hist) * p2) - (Mx(k + 1, 255, hist) * p1);
vet[k] = (float)diff * diff / p12;

}
}
bmp.UnlockBits(bmData);

t = (byte)findMax(vet, 256);

return t;
}```

For more information on how to efficiently process images in C#, please refer to my older articles such as "Image Processing Basics in C#".

## Points of Interest

Otsu thresholding doesn't claim to be the best automatic thresholding ever, but there are many applicable uses in computer vision and medical imaging. It's a first step to get non-parametrized, adaptive algorithms. Addition to that, there may be faster implementations available (such as recursive algorithms).

Also, Otsu threshold can be extended to a multi-level thresholding which could result in segmentation. Such research is present in the literature. This may be a further article. Please check:

• Version 1.0.

## Reference

• 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.

## Share

 CEO Gravi Information Technologies and Consultancy Ltd Turkey
Currently, also an MSc. student in Technical University of Munich, I develop practical application in computer vision for more than 5 years. I design real-time solutions to industrial and practical vision problems, both 3D and 2D. Very interested in developing algorithms in C relating math and vision.

"Great minds never die, they just tend to infinity..."

## You may also be interested in...

 First Prev Next
 exception Member 67915728-Nov-16 11:10 Member 679157 28-Nov-16 11:10
 THANKS A TON SIR!!!!!! Member 1185678712-Sep-15 7:39 Member 11856787 12-Sep-15 7:39
 OTSU pol8712-Jan-15 6:46 pol87 12-Jan-15 6:46
 Re: OTSU Tolga Birdal12-Jan-15 6:50 Tolga Birdal 12-Jan-15 6:50
 Multi level threshold St3althX29-Jun-14 1:01 St3althX 29-Jun-14 1:01
 Re: Multi level threshold Tolga Birdal29-Jun-14 3:04 Tolga Birdal 29-Jun-14 3:04
 Excellent Post - Example Code Worked Great Erik Turner4-Mar-14 16:41 Erik Turner 4-Mar-14 16:41
 I was looking for a way to quickly reduce full color images to a 1 bpp image. I spent a bit of time optimizing the code for my application and I've posted the optimized version below in case someone else needs a faster version:``` // function is used to compute the q values in the equation private static Int64 Px2(int init, int end, int[] hist) { var sum = 0; for (int i = init; i <= end; i++) { sum += hist[i]; } return sum; } // function is used to compute the mean values in the equation (mu) private static Int64 Mx2(int init, int end, int[] hist2) { var sum = 0; for (int i = init; i <= end; i++) { sum += hist2[i]; } return sum; } // Get OTSU threshold from histogram (assumes 256 items in histogram) public static int GetOtsuThresholdFast(int[] hist) { // Set up second order histogram var hist2 = new int[256]; for (int idx = 0; idx <= 255; idx++) { hist2[idx] = idx * hist[idx]; } // Set up first order probabilities Int64 p1 = hist[0]; Int64 p2 = Px2(1, 255, hist); // Set up second order probabilities Int64 m1 = hist2[0]; Int64 m2 = Mx2(1, 255, hist2); // Calculate variance var vet = new Single[256]; for (int k = 1; k < 255; k++) { p1 += hist[k]; p2 -= hist[k]; m1 += hist2[k]; m2 -= hist2[k]; var p12 = p1 * p2; if (p12 == 0) p12 = 1; var diff = (m1*p2) - (m2*p1); vet[k] = (Single)diff * diff / p12; } // Return index of maximum value return FindMaxIndex(1, 255, vet); } ```
 multicolor Thresholding keyur_patel12-Apr-13 20:59 keyur_patel 12-Apr-13 20:59
 Re: multicolor Thresholding Tolga Birdal29-Jun-14 3:10 Tolga Birdal 29-Jun-14 3:10
 Re: multicolor Thresholding keyur_patel21-Jul-14 22:10 keyur_patel 21-Jul-14 22:10
 Re: multicolor Thresholding Tolga Birdal4-Aug-14 22:50 Tolga Birdal 4-Aug-14 22:50
 Great, kaz_panda4-Dec-12 12:21 kaz_panda 4-Dec-12 12:21
 My vote of 5 tyk371-Sep-12 3:00 tyk37 1-Sep-12 3:00
 Windows Phone app using Otsu threshold asavol24-May-12 9:14 asavol 24-May-12 9:14
 Re: Windows Phone app using Otsu threshold Tolga Birdal24-May-12 10:06 Tolga Birdal 24-May-12 10:06
 thanks...very useful Moovendan M6-Apr-12 10:59 Moovendan M 6-Apr-12 10:59
 My vote of 5 manoj kumar choubey20-Feb-12 20:13 manoj kumar choubey 20-Feb-12 20:13
 My vote of 5 amin jourabloo18-Jul-10 20:26 amin jourabloo 18-Jul-10 20:26
 a problem with your project hassan akaberi8-Apr-10 4:09 hassan akaberi 8-Apr-10 4:09
 Re: a problem with your project Tolga Birdal8-Apr-10 10:04 Tolga Birdal 8-Apr-10 10:04
 Good job Dr.Luiji27-Jul-09 22:00 Dr.Luiji 27-Jul-09 22:00
 Last Visit: 31-Dec-99 19:00     Last Update: 26-Mar-17 16:46 Refresh 1