This has also been implemented in the past, but now I look back, it was really bad to write at that time, so now I decided to use MATLAB to rewrite it. And the method at that time is not very good.
The method used here is in Feature Extraction and image processing 3.3.4.
The following code is used:
Function main img1_imread('lena.jpg '); imshow (IMG); IMG = double (IMG); [m n] = size (IMG); hist = zeros (1,256); for I = 1: M for j = 1: N hist (IMG (I, j) + 1) = Hist (IMG (I, j) + 1) + 1; % calculate the histogram end P = Hist/(m * n); % histogram probability distribution ut = sum ). * P (); % The average brightness of the image, in fact, is 1 larger than the real average, so 1 sigma_2 = zeros (1,256) is subtracted ); for k = 1:256 sigma_2 (K) = (UT * w (K, P)-U (k, p) ^ 2/(w (K, P) * (1-W (k, p); % inter-Class Variance end [TMP Index] = max (sigma_2); % calculate the index of the inter-Class Variance = index-1; % here the index is 1-256, and the actual gray scale of the image is 0-255, so reduce 1 imgn = img> index; figure; imshow (imgn); function Re = W (K, p) % cumulative moment Re = sum (P (1: K) of the First K brightness levels; end function Re = U (K, P) % level 1 Cumulative moment Re = sum (1: K) of the First K brightness levels of the histogram ). * P (1: K); end
Effect:
Source image
After binarization