(* Písmeno e. *)
B={{1,1,1,1,1,1,1,1},{1,1,0,0,0,0,1,1},{1,0,1,1,1,1,0,1},{1,0,1,1,1,1,0,1},{1,0,0,0,0,0,0,1},{1,0,1,1,1,1,1,1},{1,0,1,1,1,1,0,1},{1,1,0,0,0,0,1,1}}*255-128;

(* Kus okapu. *)
B={{50,58,65,85,116,129,129,136},{53,60,67,87,117,128,126,132},{49,50,65,101,133,147,141,133},{62,60,75,108,141,153,145,135},{58,57,70,101,133,145,143,137},{56,61,80,109,136,149,155,158},{45,63,94,125,141,144,147,152},{55,79,115,144,150,143,138,139}}-128;

(* Vykreslení. *)
MatrixPlot[(B+128)/255,ColorFunctionScaling->False,ColorFunction->GrayLevel]

(* Diskrétní kosínová transformace. *)
w={Sqrt[0.5],1,1,1,1,1,1,1};
d=Table[Sum[((w[[k]] w[[l]])/4) Cos[((π (k-1) (2i-1))/16)] Cos[((π (l-1) (2j-1))/16)] B[[i,j]],{i,1,8},{j,1,8}],{k,1,8},{l,1,8}];
MatrixPlot[d,ColorFunctionScaling->False,ColorFunction->(ColorData["TemperatureMap"][#/2048+ 0.5]&)]

(* Sestrojení kvantizační matice. *)
q=100;
Q50={{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}};
Q=If[q>50,
Table[Max[1,Round[2(1-q/100)Q50[[i,j]]]],{i,1,8},{j,1,8}],
Table[Min[255,Round[(50/q)Q50[[i,j]]]],{i,1,8},{j,1,8}]
];
MatrixForm[Q]
(* DCT koeficienty po kvantizaci. *)
MatrixForm[Round[d/Q]]
(* Rekonstrukce obrázku. *)
d2=Round[d/Q]*Q;
(* d2=Round[d/Q]*Q*Table[(-1)^(i),{i,0,7},{j,0,7}]; *)(* flip *)
B2=Table[Sum[((w[[k]] w[[l]])/4) Cos[((π (k-1) (2i-1))/16)] Cos[((π (l-1) (2j-1))/16)] d2[[k,l]],{k,1,8},{l,1,8}],{i,1,8},{j,1,8}];
MatrixPlot[(B+128)/255,ColorFunctionScaling->False,ColorFunction->GrayLevel,PlotLabel->"Originál"]
MatrixPlot[Clip[Round[B2]+128,{0,255}]/255,ColorFunctionScaling->False,ColorFunction->GrayLevel,PlotLabel->"Rekonstruovaný obrázek"]

(* DCT báze maticového prostoru. *)
Table[
MatrixPlot[
Table[((w[[k]] w[[l]])/4) Cos[((π (k-1) (2i-1))/16)] Cos[((π (l-1) (2j-1))/16)],{i,1,8},{j,1,8}],
ColorFunctionScaling->False,ColorFunction->(ColorData["TemperatureMap"][# 2 /((Cos[(π/16)])^2) + 0.5]&)
],
{k,1,8},{l,1,8}
]

(* Progresivní kódování. *)
zz={{1,1},{1,2},{2,1},{3,1},{2,2},{1,3},{1,4},{2,3},{3,2},{4,1},{5,1},{4,2},{3,3},{2,4},{1,5},{1,6},{2,5},{3,4},{4,3},{5,2},{6,1},{7,1},{6,2},{5,3},{4,4},{3,5},{2,6},{1,7},{1,8},{2,7},{3,6},{4,5},{5,4},{6,3},{7,2},{8,1},{8,2},{7,3},{6,4},{5,5},{4,6},{3,7},{2,8},{3,8},{4,7},{5,6},{6,5},{7,4},{8,3},{8,4},{7,5},{6,6},{5,7},{4,8},{5,8},{6,7},{7,6},{8,5},{8,6},{7,7},{6,8},{7,8},{8,7},{8,8}};
{k,l}=Transpose[zz];
list=Accumulate[Table[Table[((w[[k[[n]]]] w[[l[[n]]]])/4) Cos[((π (k[[n]]-1) (2i-1))/16)] Cos[((π (l[[n]]-1) (2j-1))/16)] d2[[k[[n]],l[[n]]]],{i,1,8},{j,1,8}],{n,1,64}]];
{Animator[Dynamic[x],{1,64,1},3],
Dynamic[MatrixPlot[Clip[Round[list[[x]]]+128,{0,255}]/255,ColorFunctionScaling->False,ColorFunction->GrayLevel]]}