%% quantdequant.m
% quantize and dequantize an image
% show resultant image and compute distortion
% needs energy.m

% S. Allen Broughton - 29 Sep 10

%% load picture
load mandrill

%% quantize-dequantize
b = 2;   % bits per pixel
r = 2^b; % number of quantization levels
M = max(max(X));
m = min(min(X));
h = (M-m)/r;
qX = ceil((X-m)/h)-1;
dqqX = m+h*(qX+0.5);

%% show original 
figure(1)
colormap(gray)
imagesc(X)

%% show final
figure(2)
colormap(gray)
imagesc(dqqX)

%% compute percentage distortion
diff = X-dqqX;
mD = 100*energy(diff)/energy(X)

