Summary:
Histogram balancing example
Clear all;
Close all;
CLC;
I = [1 5 255 255 100 200 255 200;
17 254 255 100 10 9;
37 10 100 100 2 9 6;
36 10 10 9 2 8 2;
21 8 8 9 3 4 2;
10 7 8 8 3 2 1;
11 8 8 7 2 2 1;
23 9 8 7 2 2 0]
% Iw.imread('fig36.bmp ');
% I = rgb2gray (I );
% Figure (3)
% Imshow (I );
[M, N] = size (I)
I1 = max (I); % calculate the maximum value of each column
IMAX = max (I1) % to find the maximum value
I3 = min (I); % calculates the minimum value of each column
Imin = min (I3) % to obtain the minimum value
K (IMAX-Imin) = 4;
HS (IMAX-Imin) = 5;
P = 0
For P = Imin: Imax-1
For j = 1: N
For I = 1: m
If I (I, j) = P
K (p + 1) = K (p + 1) + 1;
End
End
End
P = p + 1;
% Plot the histogram of the original image
Figure (1)
Bar (P, K (p); Hold on;
% Calculate the probability of each pixel value of the original image
HS (p) = K (P)/(m * n );
Sum (HS );
End
% Calculate the cumulative gray distribution of each pixel in the image HP
HP (IMAX-Imin) = 0;
HP (1) = HS (1 );
For x = 2 :( IMAX-Imin)
HP (x) = HS (x) + sum (HP (x-1 ));
If HS (x) = 0
HP (x) = 0;
End
End
HP (1, 255) = 1
% Calculate the gray value of the new image
For y = 1 :( IMAX-Imin)
G (y) = 255 * HP (y );
% Plot the histogram of the balanced image
Figure (2)
Bar (Y, g (y); Hold on;
End
The above error: the code is corrected:
Clear all;
Close all;
CLC;
% I = [1 5 255 255 100 200 255 200;
% 1 7 254 255 100 10 10 9;
% 3 7 10 100 100 2 9 6;
% 3 6 10 10 9 2 8 2;
% 2 1 8 8 9 3 4 2;
% 1 0 7 8 8 3 2 1;
% 1 1 8 8 7 2 2 1;
% 2 3 9 8 7 2 2 0]
I =imread('fig36.bmp ');
% I = rgb2gray (I );
Figure (4)
Imshow (I );
[M, N] = size (I)
I1 = max (I); % calculate the maximum value of each column
IMAX = max (I1) % to find the maximum value
I3 = min (I); % calculates the minimum value of each column
Imin = min (I3) % to obtain the minimum value
K = zeros (1,256 );
HS = zeros (1,256 );
For P = 1:256
K (p) = length (find (I = (p-1 )));
% Calculate the probability of each pixel value of the original image
HS (p) = K (P)/(m * n );
Sum (HS );
P = p + 1;
End
% Plot the histogram of the original image
Figure (1)
Bar (0: 255, HS); Hold on;
Title ('original image histograms ');
Xlabel ('grayscale value ');
Ylabel ('probability of occurrence ');
% Calculate the cumulative gray distribution of each pixel in the image HP
HP = zeros (1,256 );
HP (1) = HS (1 );
For x = 2: 256
HP (x) = HS (x) + sum (HP (x-1 ));
End
% Calculate the gray value of the new image
For Y = 1:256
G (y) = round (256 * HP (y ));
Newgp (y) = sum (HS (find (G = y )));
End
G
Newgp
% Plot the histogram of the balanced image
Figure (2)
Bar (0: 255, newgp );
Title ('histogram after equalization ');
Xlabel ('grayscale value ');
Ylabel ('probability of occurrence ');
Newi = I; % fill in the new gray value of each pixel
For I = 1:256
Newi (find (I = (I-1) = g (I );
End
Figure (3)
Imshow (newi );