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