%color image
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);

%Transform RGB system to YUV system
Y=0.299*R+0.587*G+0.114*B;
U=B-Y;
V=R-Y;
p=4;% loss parameter
        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; ] %linear quantization matrix
         
        QC=p*[17 18 24 47 99 99 99 99;
             18 21 26 66 99 99 99 99;
             24 26 56 99 99 99 99 99;
             47 66 99 99 99 99 99 99;
             99 99 99 99 99 99 99 99; 
             99 99 99 99 99 99 99 99;
             99 99 99 99 99 99 99 99;
             99 99 99 99 99 99 99 99; ] %linear quantization matrix

image=zeros(8,8,3);
        %Y
        YY=Y(331:338, 76:83);  %extract an 8 by 8 pixel block
        Yd=double(YY);
        Yc=Yd-128;
        C=dct(Yc);
        YZ=C*Yc*C';
        YZq=round(YZ./Q);
        YZdq=YZq.*Q; 
        Ydq=C'*YZdq*C;
        Ye=Ydq+128;
        
        %U
        UU=U(331:338, 76:83); %extract an 8 by 8 pixel block
        Ud=double(UU);
        Uc=Ud-128;
        C=dct(Uc);
        UZ=C*Uc*C';
        UZq=round(UZ./QC);
        UZdq=UZq.*QC; 
        Udq=C'*UZdq*C;
        Ue=Udq+128;

        %V
        VV=V(331:338, 76:83); %extract an 8 by 8 pixel block
        Vd=double(VV);
        Vc=Vd-128;
        C=dct(Vc);
        VZ=C*Vc*C';
        VZq=round(VZ./QC);
        VZdq=VZq.*QC; 
        Vdq=C'*VZdq*C;
        Ve=Vdq+128;
        
        %transform into RGB
        B=Ue+Ye;
        R=Ve+Ye;
        G=(Ye-0.299*R-0.114*B)/0.587;
        
        %put the data together 
        image(1:8, 1:8,1)=R;
        image(1:8, 1:8,2)=G;
        image(1:8, 1:8,3)=B;
  
image=uint8(image);
figure(4);imagesc(image)

