Use the otsu algorithm for image threshold

Source: Internet
Author: User

When performing a threshold operation on a grayscale image, you must first determine the threshold. There are many methods to determine the threshold. The otsu algorithm is a better algorithm.

Otsu algorithms are also called the most inter-Class Variance algorithms. The threshold value set by the threshold operation divides all pixels in the image into two categories: foreground and background. Otsu assumes that the optimal threshold value is the maximum value for inter-class methods between the two classes.

The Inter-Class Variance algorithm is:

M = w1 * w2 * [U1-U2] ^ 2

W1 and w2 are the proportions of two categories, namely, the number of pixels. U1 and u2 are the mean values of the two categories respectively.

For detailed algorithm description, see Wikipedia: otsu algorithm

Otsu algorithm written in python:

The getGray function obtains the histogram of the grayscale image. The img Of The grayscale image is a single channel.

[Python]
Def getGray (img ):
NumGray = [0 for I in range (pow (2, img. depth)]
For h in range (img. height ):
For w in range (img. width ):
NumGray [int (img [h, w])] + = 1
Return numGray
 
Def getThres (gray ):
MaxV = 0
BestTh = 0
W = [0 for I in range (len (gray)]
Px = [0 for I in range (len (gray)]
W [0] = gray [0]
Px [0] = 0
For m in range (1, len (gray )):
W [m] = w [M-1] + gray [m]
Px [m] = px [M-1] + gray [m] * m
For th in range (len (gray )):
W1 = w [th]
W2 = w [len (gray)-1]-w1
If (w1 * w2 = 0 ):
Continue
U1 = px [th]/w1
U2 = (px [len (gray)-1]-px [th])/w2
V = w1 * w2 * (U1-U2) * (U1-U2)
If v> maxV:
MaxV = v
BestTh = th
Return bestTh

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.