%Reads in color image and performs histogram equalization on each color component.
%Perform for both RGB and YIQ representations.
%clear;X=imread('toucan.jpg');X=double(X);[N,M,D]=size(X);NM=N*M-1;%Know D=3.
clear;load xmastree.mat;[N,M,D]=size(X);NM=N*M-1;%Know D=3.
X=(X-min(min(min(X))))/(max(max(max(X)))-min(min(min(X))));
figure,imagesc(X),axis off,title('Original image')
X=round(X*NM)+1;%Makes program simpler.
%Perform histogram equalization on each RGB component:
X1=X(:,:,1);PX1=hist(X1(:),0.5+[0:NM]);FX1=[0 cumsum(PX1)];Y1=round(FX1(X1(:)));
X2=X(:,:,2);PX2=hist(X2(:),0.5+[0:NM]);FX2=[0 cumsum(PX2)];Y2=round(FX2(X2(:)));
X3=X(:,:,3);PX3=hist(X3(:),0.5+[0:NM]);FX3=[0 cumsum(PX3)];Y3=round(FX3(X3(:)));
Y1=(Y1-min(Y1))/(max(Y1)-min(Y1));Y(:,:,1)=reshape(Y1,N,M);
Y2=(Y2-min(Y2))/(max(Y2)-min(Y2));Y(:,:,2)=reshape(Y2,N,M);
Y3=(Y3-min(Y3))/(max(Y3)-min(Y3));Y(:,:,3)=reshape(Y3,N,M);
figure,imagesc(Y),axis off,title('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:
Z1=Z(:,:,1);PZ1=hist(Z1(:),0.5+[0:NM]);FZ1=[0 cumsum(PZ1)];ZZ1=round(FZ1(round(Z1(:))))+1;
ZZ2(:,:,1)=reshape(ZZ1,N,M);
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);
W(:,:,1)=(W(:,:,1)-min(min(min(W(:,:,1)))))/(max(max(max(W(:,:,1))))-min(min(min(W(:,:,1)))));
W(:,:,2)=(W(:,:,2)-min(min(min(W(:,:,2)))))/(max(max(max(W(:,:,2))))-min(min(min(W(:,:,2)))));
W(:,:,3)=(W(:,:,3)-min(min(min(W(:,:,3)))))/(max(max(max(W(:,:,3))))-min(min(min(W(:,:,3)))));
figure,imagesc(W),axis off,title('YIQ equalized image')


