pgmRead.m 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. % IM = pgmRead( FILENAME )
  2. %
  3. % Load a pgm image into a MatLab matrix.
  4. % This format is accessible from the XV image browsing utility.
  5. % Only works for 8bit gray images (raw or ascii)
  6. % Hany Farid, Spring '96. Modified by Eero Simoncelli, 6/96.
  7. function im = pgmRead( fname );
  8. [fid,msg] = fopen( fname, 'r' );
  9. if (fid == -1)
  10. error(msg);
  11. end
  12. %%% First line contains ID string:
  13. %%% "P1" = ascii bitmap, "P2" = ascii greymap,
  14. %%% "P3" = ascii pixmap, "P4" = raw bitmap,
  15. %%% "P5" = raw greymap, "P6" = raw pixmap
  16. TheLine = fgetl(fid);
  17. format = TheLine;
  18. if ~((format(1:2) == 'P2') | (format(1:2) == 'P5'))
  19. error('PGM file must be of type P2 or P5');
  20. end
  21. %%% Any number of comment lines
  22. TheLine = fgetl(fid);
  23. while TheLine(1) == '#'
  24. TheLine = fgetl(fid);
  25. end
  26. %%% dimensions
  27. sz = sscanf(TheLine,'%d',2);
  28. xdim = sz(1);
  29. ydim = sz(2);
  30. sz = xdim * ydim;
  31. %%% Maximum pixel value
  32. TheLine = fgetl(fid);
  33. maxval = sscanf(TheLine, '%d',1);
  34. %%im = zeros(dim,1);
  35. if (format(2) == '2')
  36. [im,count] = fscanf(fid,'%d',sz);
  37. else
  38. [im,count] = fread(fid,sz,'uchar');
  39. end
  40. fclose(fid);
  41. if (count == sz)
  42. im = reshape( im, xdim, ydim )';
  43. else
  44. fprintf(1,'Warning: File ended early!');
  45. im = reshape( [im ; zeros(sz-count,1)], xdim, ydim)';
  46. end