% Histogram equalisation program: histequal.m

clear,clc,close all, home
% need to be in the following directory
% cd c:\jl\I8_imageprocessing\imageprocessing5\imageproc5mat

% load original lenna image
load lenna256
[N,M]=size(x)
figure(1)
subplot(1,2,1); grayimage(x)
xx = reshape(x,1,N*M);
subplot(1,2,2); hist(xx,50)
pause



% load contrast mapped image

load lenna256unequal.mat
[N,M]=size(x)
figure(2)
subplot(1,2,1); grayimage(x)
xx = reshape(x,1,N*M);
subplot(1,2,2); hist(xx,50)
pause



% Scale image brightness between 0 and Nbins-1
%Nbins=64; % No of bins in histogram
Nbins=64;
x=x-min(min(x));
x=x.*((Nbins-1)/max(max(x)));
%x=round(x);

% Determine histogram equaliser
[i,xi]=hist(x(:),Nbins);
pxi=i./(N*N);
yi=cumsum(pxi);

y=((yi-yi(1)).*((Nbins-1)/(max(yi)-yi(1))));

%%%%%%%%%%%%%%%%%%%%%%%%Temporary bit
%load lenna256.mat
%x=x-min(min(x));
%x=x.*(255/max(max(x)));

%%%%%%%%%%%%%%%%%%%%%%%%
equalx=zeros(size(x));
equalx(:)=interp1((0:length(y)-1),y,x(:));

figure(3)
[N1,M1]=size(equalx)
subplot(1,2,1); grayimage(equalx)
equalxx = reshape(equalx,1,N1*M1);
subplot(1,2,2); hist(equalxx,50)
