www.pudn.com > jpegtool_matlab.rar > quant.m


% NAME 
%      	quant - apply quantizing matrix
%
% SYNOPSIS
%	quant
%	quant(X)
%	quant(X, Q)
%	[Y, r] = quant
%	[Y, r] = quant(X)
%	[Y, r] = quant(X, Q)
%
% DESCRIPTION
%	quant cuts an mxn matrix X into NxN matrices and quantizes
%	using the matrix Q. If X is not given, then X=ans. If Q is not 
%	given, then Q=QMAT, or if QMAT is undefined or of size 0, then Q 
%	is chosen to be the 8x8 JPEG luminance matrix. Q becomes the
%	new value for QMAT.
%
%	If the ratio r is requested, then a calculation of the "lossy
%	compression" is performed. This is returned as a percentage, and 
%	measures the amount of savings obtained at the quantizing stage.
%
% BUGS
%	The ratio measures only the savings obtained by removing 
%	"trailing zeros" in the submatrices. This often gives useful 
%	information about the choice of quantizer, but it is not the
%	whole story of compression.

% Copyright (C) 1995-1997 Darrel Hankerson and Greg A. Harris
%
% This file is part of the JPEGtool collection of scripts for Octave
% and Matlab; see http://www.dms.auburn.edu/compression
%
% The JPEGtool collection is free software; you can redistribute it
% and/or modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2, or
% (at your option) any later version.
%
% The collection is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this package; see the file COPYING.  If not, write to the
% Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA.

function [X, ratio] = quant(X, Q)

global QMAT

if (nargin == 0)
  X = ans;
end

if (nargin <= 1)
  Q = [];
  if (exist('QMAT'))
    if (size(QMAT,1))
      Q = QMAT;
    end
  end
  if (~size(Q, 1))
    fprintf(1, 'Using standard 8x8 quantizing matrix\n')
    Q = stdQ; QMAT = Q;
  end
else
  QMAT = Q;
end

N = size(Q, 1);

dim = fix(size(X)/N); m=dim(1); n=dim(2);
X = X(1:N*m,1:N*n);  	%  snip trailing rows and columns from X

%  Now break up X and quantize
ratio = 0;
for ii=1:m	
  rows = N*(ii-1)+1:N*ii;
  for jj=1:n
    cols = N*(jj-1)+1:N*jj;
    X(rows, cols) = round( X(rows, cols) ./ Q );
    if (nargout == 2)
      ratio = ratio + trailnum(X(rows,cols));
    end
  end
end
if (nargout == 2)
  ratio = ratio / (m * n * N^2) * 100;
end