% Script for 11.2 computer problem 6
% relevant picture files:
%   p6base.png
%   p6quant1.png
%   p6quant2.png
%   p6quant4.png

image = imread('codyPic.jpg');
imgray = rgbim2luminance(image);

x=1900;
y=482;

im8x8 = imgray(x:(x+7),y:(y+7),:);
C=dctMat(8);
Qy=[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];
        
Qc=[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];

figure;imagesc(image(x:(x+7),y:(y+7),:));colormap default; % p6base.png

im8x8dct(:,:,1)=twoDimDCT(im8x8(:,:,1),C);
im8x8dct(:,:,2)=twoDimDCT(im8x8(:,:,2),C);
im8x8dct(:,:,3)=twoDimDCT(im8x8(:,:,3),C);

im8x8q1(:,:,1)=round(im8x8dct(:,:,1)./Qy);
im8x8q1(:,:,2)=round(im8x8dct(:,:,2)./Qc);
im8x8q1(:,:,3)=round(im8x8dct(:,:,3)./Qc);
im8x8q1

im8x8dq1(:,:,1)=im8x8q1(:,:,1).*Qy;
im8x8dq1(:,:,2)=im8x8q1(:,:,2).*Qc;
im8x8dq1(:,:,3)=im8x8q1(:,:,3).*Qc;

im8x8r1(:,:,1) = invertTwoDimDCT(im8x8dq1(:,:,1),C);
im8x8r1(:,:,2) = invertTwoDimDCT(im8x8dq1(:,:,2),C);
im8x8r1(:,:,3) = invertTwoDimDCT(im8x8dq1(:,:,3),C);
im8x8r1 = lum2rgb(im8x8r1);
im8x8ru1=uint8(im8x8r1);
figure;colormap default;imagesc(im8x8ru1); % p6quant1.png

Qy=Qy.*2;
Qc=Qc.*2;

im8x8q2(:,:,1)=round(im8x8dct(:,:,1)./Qy);
im8x8q2(:,:,2)=round(im8x8dct(:,:,2)./Qc);
im8x8q2(:,:,3)=round(im8x8dct(:,:,3)./Qc);
im8x8q2

im8x8dq2(:,:,1)=im8x8q2(:,:,1).*Qy;
im8x8dq2(:,:,2)=im8x8q2(:,:,2).*Qc;
im8x8dq2(:,:,3)=im8x8q2(:,:,3).*Qc;

im8x8r2(:,:,1) = invertTwoDimDCT(im8x8dq2(:,:,1),C);
im8x8r2(:,:,2) = invertTwoDimDCT(im8x8dq2(:,:,2),C);
im8x8r2(:,:,3) = invertTwoDimDCT(im8x8dq2(:,:,3),C);
im8x8r2 = lum2rgb(im8x8r2);
im8x8ru2=uint8(im8x8r2);
figure;colormap default;imagesc(im8x8ru2); % p6quant2.png

Qy=Qy.*2;
Qc=Qc.*2;

im8x8q4(:,:,1)=round(im8x8dct(:,:,1)./Qy);
im8x8q4(:,:,2)=round(im8x8dct(:,:,2)./Qc);
im8x8q4(:,:,3)=round(im8x8dct(:,:,3)./Qc);
im8x8q4

im8x8dq4(:,:,1)=im8x8q4(:,:,1).*Qy;
im8x8dq4(:,:,2)=im8x8q4(:,:,2).*Qc;
im8x8dq4(:,:,3)=im8x8q4(:,:,3).*Qc;

im8x8r4(:,:,1) = invertTwoDimDCT(im8x8dq4(:,:,1),C);
im8x8r4(:,:,2) = invertTwoDimDCT(im8x8dq4(:,:,2),C);
im8x8r4(:,:,3) = invertTwoDimDCT(im8x8dq4(:,:,3),C);
im8x8r4 = lum2rgb(im8x8r4);
im8x8ru4=uint8(im8x8r4);
figure;colormap default;imagesc(im8x8ru4); % p6quant4.png