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);
xgray=0.2126*r+0.7152*g+0.0722*b;
figure(1);imagesc(uint8(xgray));colormap(gray)

[row,column]= size(xgray)
% 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=1;
Q = p*8./hilb(8);

% 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 = xgray(a:a+N-1,z:z+N-1);
        

        xc = X -128; % center
        y = C*xc*C';

        yq = round(y./Q)
       

        % A crude way to compress the image

        for i = 1:8
            for j = 9-i:8
                y(i,j)=0;
            end
        end
 

        % Reconstruct x:

        ydq=yq.*Q;
        xdq = C'*ydq*C;
        xe=xdq+128;
        
        xout(a:a+N-1,z:z+N-1)= xe;
        
    end
    
    
end
figure(4);imagesc(uint8(xout),[0 255]);colormap(gray)