clear all;
i=0;
j=0;
p=6;
Q=p*8./hilb(8);
%Q = p*[16,11,10,16,24,40,51,61; 12,12,14,19,26,58,60,55; 14,13,16,24,40,57,69,56;
    %14,17,22,29,51,87,80,62; 18,22,37,56,68,109,103,77; 24,35,55,64,81,104,113,92;
    %49,64,78,87,103,121,120,101; 72,92,95,98,112,100,103,99];
    
    
X=imread('StormLiam.jpg');
[S,T,R] = size(X);
Xd=double(X);
XF=zeros(S,T,R);

r=Xd(:,:,1);g=Xd(:,:,2);b=Xd(:,:,3);
Y = .299*r+.587*g+.114*b;
U = b-Y;
V = r-Y;

%Run first for Y
xe2Y=zeros(S,T);
for i = 1:8:S;
    for j = 1:8:T;
x=Y(i:i+7,j:j+7); %second number is 81 + (8^n)-1
xc=x-128;
y=dct2(xc);

yq = round(y./Q);

ydq = yq.*Q;
xdq = idct2(ydq);
xe = xdq +128;
xe2Y(i:i+7,j:j+7)=xe;

    end
    
end

%Then for U
xe2U=zeros(S,T);
i=0;
j=0;


for i = 1:8:S;
    for j = 1:8:T;
x=U(i:i+7,j:j+7); %second number is 81 + (8^n)-1
xc=x-128;
y=dct2(xc);

yq = round(y./Q);

ydq = yq.*Q;
xdq = idct2(ydq);
xe = xdq +128;
xe2U(i:i+7,j:j+7)=xe;

    end
    
end



%Then for V
xe2V=zeros(S,T);
i=0;
j=0;

for i = 1:8:S;
    for j = 1:8:T;
x=V(i:i+7,j:j+7); %second number is 81 + (8^n)-1
xc=x-128;
y=dct2(xc);

yq = round(y./Q);

ydq = yq.*Q;
xdq = idct2(ydq);
xe = xdq +128;
xe2V(i:i+7,j:j+7)=xe;

    end
    
end

B = xe2U+xe2Y;
R= xe2V+xe2Y;
G=(xe2Y-.299*R-.114*B)/.587;

XF(:,:,1) = R;
XF(:,:,2) = G;
XF(:,:,3) = B;
figure(1); imagesc(uint8(X));
figure(2); imagesc(uint8(XF));
