
%This compares the results of histogram equalization on a 512X512 American flag image
%using (a) RGB color representation and (a) YIQ color representation. Differences:
%RGB has brighter stripes but star field is green! YIQ has duller stripes but blue star field.

clear;load flag.mat;N=0.3*rand(1,1,3);
%Multiply each RGB component by random scale factor between 0 and 0.3 to darken flag:
X(:,:,1)=X(:,:,1)*N(1,1,1);X(:,:,2)=X(:,:,2)*N(1,1,2);X(:,:,3)=X(:,:,3)*N(1,1,3);
X=round(X)+1;%Round darkened flag valuesd to integer values.
figure,imagesc(X/255),axis off,title('Original darkened flag image')

%Perform histogram equalization on each RGB color component.
X1=X(:,:,1);PX1=hist(X1(:),0.5+[0:255]);FX1=[0 cumsum(PX1)];Y1=round(FX1(X1(:)))+1;
X2=X(:,:,2);PX2=hist(X2(:),0.5+[0:255]);FX2=[0 cumsum(PX2)];Y2=round(FX2(X2(:)))+1;
X3=X(:,:,3);PX3=hist(X3(:),0.5+[0:255]);FX3=[0 cumsum(PX3)];Y3=round(FX3(X3(:)))+1;
YY1=reshape(Y1,512,512);YY2=reshape(Y2,512,512);YY3=reshape(Y3,512,512);%reshape to 512X512 images.
YY(:,:,1)=YY1;YY(:,:,2)=YY2;YY(:,:,3)=YY3;%YY1=red;YY2=green;YY3=blue.
%Now linearly scale so 0<YY<1 (required by imagesc for color images):
YY=(YY-min(min(min(YY))))/(max(max(max(YY)))-min(min(min(YY))));
figure,imagesc(YY),axis off,title('Histogram equalization using RGB')

%Transform darkened flag from RGB (X) to YIQ (Z) representation using Eq. (10.4):
A=[.299,.587,.114;.596,-.275,-.321;.212,-.523,.311];B=inv(A);
Z(:,:,1)=A(1,1)*X(:,:,1)+A(1,2)*X(:,:,2)+A(1,3)*X(:,:,3);
Z(:,:,2)=A(2,1)*X(:,:,1)+A(2,2)*X(:,:,2)+A(2,3)*X(:,:,3);
Z(:,:,3)=A(3,1)*X(:,:,1)+A(3,2)*X(:,:,2)+A(3,3)*X(:,:,3);

%Perform histogram equalization on only Y component in YIQ color representation:
Z1=Z(:,:,1);PZ1=hist(Z1(:),0.5+[0:255]);FZ1=[0 cumsum(PZ1)];ZZ1=round(FZ1(round(Z1(:))))+1;
ZZ2=reshape(ZZ1,512,512); %Transform from YIQ (Z) back to RGB (W) for display:
W(:,:,1)=B(1,1)*ZZ2(:,:,1)+B(1,2)*Z(:,:,2)+B(1,3)*Z(:,:,3);
W(:,:,2)=B(2,1)*ZZ2(:,:,1)+B(2,2)*Z(:,:,2)+B(2,3)*Z(:,:,3);
W(:,:,3)=B(3,1)*ZZ2(:,:,1)+B(3,2)*Z(:,:,2)+B(3,3)*Z(:,:,3);
%Now linearly scale so 0<W<1 (required by imagesc for color images):
W=(W-min(min(min(W))))/(max(max(max(W)))-min(min(min(W))));
figure,imagesc(W),axis off,title('Histogram equalization using YIQ')



