[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
PGM function
From: |
John W. Eaton |
Subject: |
PGM function |
Date: |
Wed, 20 May 1998 23:47:05 -0500 (CDT) |
On 20-May-1998, Dave Jansing <address@hidden> wrote:
| Here is the function to read PGM files. It is crude and simple, but works
| great. It can easily be modified to read in PPM and PBM.
Thanks. Here's how I would write this function to make it a bit
cleaner and much faster. The big win is replacing the for loops in
your version with a call to resize and transposing. That speeds it up
by a factor of about 100 for the 219 by 255 pixel image I used for
testing.
jwe
## The following function reads in PGM (8-bit
## unsigned) data and places it into a matrix of
## NxM size.
##
## Author: David Jansing
## Date: April 14, 1998
## For use with Octave
function [image_data, max_val] = read_pgm (filename)
if (nargin == 1 && isstr (filename))
[fid, msg] = fopen (filename, "r");
if (fid < 0)
error ("read_pgm: %s: %s", filename, msg);
endif
str = fgetl (fid);
if (isstr (str) && strcmp (str, "P5"))
## Skip comments and extract number of columns and rows.
while (1)
str = fgetl (fid);
if (! isstr (str))
error ("read_pgm: failed to read header information");
endif
if (str(1:1) != "#")
break;
endif
endwhile
S_A = split (str, " ");
M = str2num (S_A(1,:));
N = str2num (S_A(2,:));
expected_size = M * N;
## Get number of intensity values (typically 255).
str = fgetl (fid);
if (isstr (str))
max_val = str2num (str);
[raw_data, num_pixels] = fread (fid, expected_size, "uchar", 0);
if (num_pixels != expected_size)
error ("read_pgm: expected %d pixels, read %d", num_pixels,
expected_size);
endif
image_data = reshape (raw_data, M, N)';
else
error ("read_pgm: error reading intensity values");
endif
else
error ("read_pgm: failed to read portable grey map magic number")
endif
else
usage ("read_pgm (filename)");
endif
endfunction
- PGM function, Dave Jansing, 1998/05/20
- PGM function,
John W. Eaton <=