
X = imread('ParakeetBlackNWhite.jpg');

%figure(1);
%imagesc(X);colormap(gray);

[S,T] = size(X);
Z = zeros(S,T);


m=8;n=8;n=m;
C = zeros(n,n);

         for i=2:n
             for j=1:n
                 C(i,j)=sqrt(2/n)*cos((i-1)*(j-1/2)*pi/n);
             end
         end
         C(1,1:n)=ones(1,n)/sqrt(n);

         
p = 4;
%Use this Q for linear quantization
Q = p*8./hilb(8);
        
%This one is the JPEG-suggested matrix
%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];
         


for a=1:8:S
    for b=1:8:T

        Xd = X(a:a+7,b:b+7);
        Xd = double(Xd);
        Xc = Xd - 128;

        

%          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(n);

        Y = C*Xc*C';


        %the loss

        Yq = round(Y./Q);

        %recovering

        Ydq = Yq.*Q;
        Xdq = C'*Ydq*C;
        Xe = Xdq+128;
        Xf = uint8(Xe);
        
        for c=0:7
            for d=0:7
                %Z(a+c,b+d)=Xf(c,d);!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                Z(a+c,b+d)=Xf(1+c,1+d);
                
            end
        end
        
        %81,81
        %377 121
        
        if a==81 && b==81

        figure(2)
        imagesc(Xf);colormap(gray);
        
        end
        
        %369 , 121
        if a==105 && b==601
            
%         figure(4)
%         imagesc(Xd , [0 255]);colormap(gray);

        figure(3)
        imagesc(Xf , [0 255]);colormap(gray);
        
        end
        
        

    end
    
end

figure(1);
imagesc(Z);colormap(gray);
%imwrite(Xd,'ParakeetQ1S1.jpg');
