
# komprese obrazku

close all

pkg load signal

quant_factor=5; # faktor=10 je 50% komprese pro jpeg

jpeg=[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];
jpeg=jpeg/10;


jpeg=ones(8)*2;

obr=double(imread('fiat3.jpg'));

figure(1);

imshow(obr,[]);

vel=size(obr)

n1=vel(1)/8 
n2=vel(2)/8

#n1=n2=20;

CT=dctmtx(8);
iCT=CT';

CTleft=CT; 
CTright=CT;
iCTleft=iCT; 
iCTright=iCT;

for i=2:n1;
 CTleft=blkdiag(CTleft,CT);
 iCTleft=blkdiag(iCTleft,iCT);
endfor

for i=2:n2;
 CTright=blkdiag(CTright,CT);
 iCTright=blkdiag(iCTright,iCT);
endfor

#size(CTleft)
#size(CTright)
#size(iCTleft)
#size(iCTright)

jpeg_big=repmat(jpeg*quant_factor,n1,n2);

obrshift=obr-128;

trans=CTleft*obrshift*iCTright;

trans_q=round(trans./jpeg_big);

trans_decode=trans_q.*jpeg_big;

obr2=iCTleft*trans_decode*CTright+128;



obr2=obr2.*(obr2>0);
obr2(find(obr2>255))=255;



figure(2)
imshow(obr2,[]);

imwrite(obr2/255,"out.jpg");

""
"maximum a minimum kvantizovane matice"

max(max(trans_q))
min(min(trans_q))

""
"pocet pixelu, nenul. v obrazku a nenul v kvantizovane matici"
vel(1)*vel(2)
length(find(obr!=0))
length(find(trans_q!=0))


# kodovani

stream=trans_q(:);

[coding,val]=runlength(stream);

pocet_nul=length(find(val==0))


""
"pocet dvojic generovaneho kodu"

length(coding)-pocet_nul

"delka bitove repre. amplitud"

round(sum(ceil(log2(abs(val)+1)))/8)






