%This simple example shows why edge detection in color images should be peformed
%on the Y component of the YIQ representation, and not on the RGB representation.
%Next 3 lines:Create 64X64 checkerboard of 8X8 squares:
clear;X1(1:2:8,1:2:8,1)=1;X1(1:2:8,2:2:8,2)=1;X1(2:2:8,1:2:8,3)=1;%red,green,blue squares, respectively.
X1(2:2:8,2:2:8,1)=0;X1(2:2:8,2:2:8,2)=0;X1(2:2:8,2:2:8,3)=0;%black squares (don't actually need this line).
%Create 8X8 squares from 1X1 squares:
X(:,:,1)=kron(X1(:,:,1),ones(8,8));X(:,:,2)=kron(X1(:,:,2),ones(8,8));X(:,:,3)=kron(X1(:,:,3),ones(8,8));
figure,imagesc(X),axis off,title('Original checkerboard image')

%Now perform Sobel edge detection on each of the RGB components:
H=[1 2 1;0 0 0;-1 -2 -1];%PSF's for edge detection: H and H'
YH1=conv2(X(:,:,1),H);YV1=conv2(X(:,:,1),H');Y1=sqrt(YH1.*YH1+YV1.*YV1);%Gradient for red edges.
YH2=conv2(X(:,:,2),H);YV2=conv2(X(:,:,2),H');Y2=sqrt(YH2.*YH2+YV2.*YV2);%Gradient for green edges.
YH3=conv2(X(:,:,3),H);YV3=conv2(X(:,:,3),H');Y3=sqrt(YH3.*YH3+YV3.*YV3);%Gradient for blue edges.
Y1(abs(Y1)>0.1)=1;Y1(abs(Y1)<0.1)=0;Y(:,:,1)=Y1;%Threshold for red edges.
Y2(abs(Y2)>0.1)=1;Y2(abs(Y2)<0.1)=0;Y(:,:,2)=Y2;%Threshold for green edges.
Y3(abs(Y3)>0.1)=1;Y3(abs(Y3)<0.1)=0;Y(:,:,3)=Y3;%Threshold blue edges.
figure,imagesc(Y1),colormap(gray),axis off,title('Red color edge detection')
figure,imagesc(Y2),colormap(gray),axis off,title('Green color edge detection')
figure,imagesc(Y3),colormap(gray),axis off,title('Blue color edge detection')

%Now transform from RGB (X) to YIQ (Z) color 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);

%Now perform Sobel edge detection on only the Y component of YIQ representation:
ZH=conv2(Z(:,:,1),H,'same');ZV=conv2(Z(:,:,1),H','same');ZE=sqrt(ZH.*ZH+ZV.*ZV);
ZE(abs(ZE)>0.1)=1;ZE(abs(ZE)<0.1)=0;%Threshold for Y edges.
figure,imagesc(ZE),colormap(gray),axis off,title('Edge detection using YIQ')


