Homework 2


function v = quant(in,L,type)
% B = QUANT(A,L,T)
% quantizes A to L levels and returns the new values in B, using quantization
% method T, taking values 'uniform' or 'contrast'.

[m,n] = size(in);

if isa(in,'uint8')
   dataType = 'uint8';
   inL = 256;
else
   error('data type not supported now');
end

if nargin<3
   type = 'uniform';	% default quantization method
end
type = lower(type);	% work in lowercase

% convert to double so we can do math on it
u = double(in);

if strcmp(type,'contrast')
   % Contrast quantization
   alpha = 1;
   beta = 1/3;

   c = u.*(100/255);	% scale luminance from [0,100]
   % c = alpha*u^beta
   c = c.^beta;
   c = c.*alpha;

   A = alpha * 100^beta; % calculate the dynamic range of c

   % now do uniform quantization on c
   q = A/L;
   v = floor(c./q);
   v = v.*q;	% scale back to original dynamic range
else
   % Uniform quantization
   q = inL/L;
   v = floor(u./q);
   v = v.*q; 	% scale it back up to the dynamic range of the input
end

if strcmp(type,'contrast')
   % transform contrast back to luminance using
   % u = (c/alpha)^(1/beta)
   v = v./alpha;
   v = v.^(1/beta);

   % now scale luminance back to [0,255]
   v = v.*(255/100);
end

% calculate MSE
% (actually, it's the average least-squares error estimate of MSE
mse = sum(sum((u-v).^2)) / (m*n)

% convert back to the original datatype
if strcmp(dataType,'uint8')
   v = uint8(v);	% this seems to introduce a little noise due to roundoff error
end

% save it to imagefile for viewing
imwrite(v,'_test.png','png');


Back