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


% getpgm - read a graymap file
%
% SYNOPSIS
%	getpgm(filename)
%	[x, maxgray] = getpgm(filename)
%
% DESCRIPTION
% 	getpgm reads a pgm file (in either raw P5 or ascii P2 format)
%      	and returns a matrix suitable for display with the image
%	function. The maxgray return value is the maximum gray value
%	(see pgm(5)).
%
% BUGS
%	Under Octave-1.1.1, only raw P5 format can be read. Some legal
%	graymap files are not handled; in particular, comments within
%	gray values in P2 files will break.

% 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 [image, maxgray] = getpgm(filename)

octave = exist('OCTAVE_VERSION');
if (octave)
  fid = fopen(filename, 'r'); 
  message = sprintf('Can''t open file %s', filename);
else 
  [fid, message] = fopen(filename, 'r');
end

if (fid == -1)
  error(message);
end

frewind(fid); 
if (octave)
  magic = fgets(fid, 2);
else
  magic = fscanf(fid, '%s', 1);
end

if ( ~(strcmp(magic, 'P2') | strcmp(magic, 'P5')) )
  fclose(fid);
  error('pgm magic number (P2 or P5) not found')
end

height = getint(fid); width = getint(fid); maxgray = getint(fid);
if (strcmp(magic, 'P2'))
  image = fscanf(fid, '%d', [height, width])';
else
  image = fread(fid, [height, width], 'uchar')';
end
fclose(fid);