00001
00007 #ifndef __PNM_IO_H__
00008 #define __PNM_IO_H__
00009
00010 #include <string>
00011 #include <fstream>
00012 #include <utility>
00013 #ifdef _CRAYMPP
00014 #include <pair.h>
00015 #endif
00016
00017
00023 inline istream& eatcomments(istream& is)
00024 {
00025 char c;
00026 is >> c;
00027 while (c=='#') {
00028 while (is.get()!='\n');
00029 is >> c;
00030 }
00031 is.putback(c);
00032
00033 return is;
00034 }
00035
00036
00044 template <class Array2D>
00045 bool pgm_read(const string& filename, Array2D& image)
00046 {
00047 ifstream file(filename.c_str());
00048 if (!file) return false;
00049
00050 string filetype; file >> filetype >> eatcomments;
00051 if (!(filetype=="P2" || filetype=="P5")) return false;
00052
00053 int width; file >> width >> eatcomments;
00054 int height; file >> height >> eatcomments;
00055 double maxval; file >> maxval;
00056 if (!maxval) return false;
00057
00058 image=Array2D(height,width);
00059
00060 if (filetype=="P2") {
00061 file >> eatcomments;
00062 for (int i=0; i<height; i++) {
00063 for (int j=0; j<width; j++) {
00064 int val;
00065 file >> val;
00066 image[i][j] = val/maxval;
00067 }
00068 file >> eatcomments;
00069 }
00070 }
00071
00072 else if (filetype=="P5") {
00073 file.get();
00074 for (int i=0; i<height; i++) {
00075 for (int j=0; j<width; j++) {
00076 unsigned char val;
00077 file.get(val);
00078 image[i][j] = val/maxval;
00079 }
00080 }
00081 }
00082
00083 return true;
00084 }
00085
00086
00087
00092 inline pair<int,int> pnm_size(const string& filename)
00093 {
00094 ifstream file(filename.c_str());
00095 if (!file) return make_pair(0,0);
00096
00097 string filetype; file >> filetype >> eatcomments;
00098 if (filetype[0]!='P') return make_pair(0,0);
00099
00100 int width; file >> width >> eatcomments;
00101 int height; file >> height >> eatcomments;
00102 return make_pair(width,height);
00103 }
00104
00105 #endif