x = imread('flower.jpg');
%image is 700 by 940
x=x(1:640, 201:840,:); %crop the image so that its dimentsion is a multiple of 8
x=double(x);
r=x(:,:,1); 
g=x(:,:,2);
b=x(:,:,3);
xgray=0.2126*r+0.7152*g+0.0722*b;
xgray=uint8(xgray);
%figure(1);imagesc(xgray);colormap(gray);
image= zeros(640); % 640 by 640 matrix
for i = 1:8:640
    for j = 1:8:640
        X=xgray(i:i+7, j:j+7); %extract an 8 by 8 pixel block
        Xd=double(X);
        Xc=Xd-128;
        C=dct(Xc);
        Y=C*Xc*C';
        p=4; % loss parameter
        Q=p*8./hilb(8); %linear quantization matrix
        Yq=round(Y./Q);
            
        %to recover the image back
        Ydq=Yq.*Q; 
        Xdq=C'*Ydq*C;
        Xe=Xdq+128;
        Xf=uint8(Xe);
        image(i:i+7, j:j+7)=Xf;
    end
end
figure(1);imagesc(image);colormap(gray);