%This compares histogram equalization on a color image of a toucan using RGB and YIQ.
%Histograms of each color component of the original, RGB equalized, and YIQ eaualized.
clear;load toucan.mat;[M,N,O]=size(X);X=round(X*255)+1;%To make pixel values integers.
figure,imagesc(X/256),axis off,title('Original toucan image')
%Perform histogram equalization on RGB representation of toucan image:
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;
%Histograms for original toucan image:
figure,subplot(311),hist(X1(:),255),axis tight,title('Histogram of red in original image')
subplot(312),hist(X2(:),255),axis tight,title('Histogram of green in original image')
subplot(313),hist(X3(:),255),axis tight,title('Histogram of blue in original image')
Y(:,:,1)=reshape(Y1,M,N);Y(:,:,2)=reshape(Y2,M,N);Y(:,:,3)=reshape(Y3,M,N);
Y=(Y-min(min(min(Y))))/(max(max(max(Y)))-min(min(min(Y))));
figure,imagesc(Y),axis off,title('RGB-equalized image')
%Histograms for histogram-equalized RGB image:
Y1=Y(:,:,1);Y2=Y(:,:,2);Y3=Y(:,:,3);
figure,subplot(311),hist(Y1(:)*255,255),axis tight,title('Histogram of red in RGB-equalized')
subplot(312),hist(Y2(:)*255,255),axis tight,title('Histogram of green in RGB-equalized')
subplot(313),hist(Y3(:)*255,255),axis tight,title('Histogram of blue in RGB-equalized')
%Transform from RGB to YIQ representation:
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 Y component only of YIQ representation:
Z1=Z(:,:,1);PZ1=hist(Z1(:),0.5+[0:255]);FZ1=[0 cumsum(PZ1)];ZZ1=round(FZ1(round(Z1(:))))+1;
ZZ2(:,:,1)=reshape(ZZ1,M,N)/max(max(ZZ1))*255;
%Transform from YIQ representation back to YIQ:
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);
W1=W(:,:,1);W2=W(:,:,2);W3=W(:,:,3);
W=(W-min(min(min(W))))/(max(max(max(W)))-min(min(min(W))));
figure,imagesc(W),axis off,title('YIQ-equalized image')
W1=W(:,:,1);W2=W(:,:,2);W3=W(:,:,3);
figure,subplot(311),hist(W1(:)*255,255),axis tight,title('Histogram of red in YIQ-equalized')
subplot(312),hist(W2(:)*255,255),axis tight,title('Histogram of green in YIQ-equalized')
subplot(313),hist(W3(:)*255,255),axis tight,title('Histogram of blue in YIQ-equalized')


