x=imread('iceland.jpg');
xd=double(x); % Note that we have converted the default MATLAB
              % data type uint8, or unsigned integers, to double 
              % precision reals before we do the computation (pg 506)
r=xd(:,:,1);g=xd(:,:,2);b=xd(:,:,3);
Y = 0.299*r + 0.587*g + 0.114*b;
U = b - Y;
V = r - Y;
% figure(1);imagesc(uint8(xgray));colormap(gray)

[row,column]= size(r)
% Defining the DCT Matrix C
n=8;
for i = 1:n
    for j =1:n
        C(i,j)=cos((i-1)*(2*j-1)*pi/(2*n));
    end
end
C=sqrt(2/n)*C;
C(1,:)=C (1,:)/sqrt(2);
xout = zeros(row,column); % Defining a zero matrix of 256 by 256 for all the 8 by 8 blocks to go in one at a time

p=4;

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];
% Grabbing an 8 by 8 block from the image and applying DCT
% Doing i-1*8 +1 results in skipping an 8 by 8 block
N = 8;
for a = 1:N:row
    for z = 1:N:column
        
        X = Y(a:a+N-1,z:z+N-1);
        
        
        

        xc = X -128; % center
        y = C*xc*C';
        
        yq = round(y./Q);
    
        % Reconstruct x:

        ydq=yq.*Q;
        xdq = C'*ydq*C;
        xe=xdq+128;
        xout(a:a+N-1,z:z+N-1,1)= xe;
        
    end 
end

for a = 1:N:row
    for z = 1:N:column
        
        X = U(a:a+N-1,z:z+N-1);
       
        

        xc = X -128; % center
        y = C*xc*C';
        % p=16;
        % Q = p*8./hilb(8);
        yq = round(y./Q);
       

        % A crude way to compress the image

        
 

        % Reconstruct x:

        ydq=yq.*Q;
        xdq = C'*ydq*C;
        xe=xdq+128;
        xout(a:a+N-1,z:z+N-1,2)= xe;
        
        
    end   
end

for a = 1:N:row
    for z = 1:N:column
        
        X = V(a:a+N-1,z:z+N-1);
        
        

        xc = X -128; % center
        y = C*xc*C';
        % p=16;
        % Q = p*8./hilb(8);
        yq = round(y./Q);
       

        % A crude way to compress the image

 

        % Reconstruct x:

        ydq=yq.*Q;
        xdq = C'*ydq*C;
        xe=xdq+128;
        xout(a:a+N-1,z:z+N-1,3)= xe;
        
    end 
end
Y=xout(:,:,1);
U=xout(:,:,2);
V=xout(:,:,3);

r = V + Y;
b = U + Y;
g = (Y - 0.299*r - 0.114*b)/(0.587);
xout(:,:,1)= r;
xout(:,:,2)= g;
xout(:,:,3)= b;

figure(4);imagesc(uint8(xout),[0 255])