33 #define imRef(im, x, y) (im->access[y][x])
36 #define imPtr(im, x, y) &(im->access[y][x])
40 typedef unsigned char uchar;
41 typedef struct { uchar r, g, b; } rgb;
43 inline bool operator==(
const rgb &a,
const rgb &b) {
44 return ((a.r == b.r) && (a.g == b.g) && (a.b == b.b));
48 template <
class T>
class image {
52 image(
const int width,
const int height,
const bool init =
false);
58 void init(
const T &val);
61 image<T> *copy()
const;
64 int width()
const {
return w; }
65 int height()
const {
return h; }
77 template <
class T> image<T>::image(
const int width,
const int height,
const bool init) {
84 for (
int i = 0; i < h; i++)
85 access[i] = data + (i * w);
89 memset(data, 0, w * h *
sizeof(T));
92 template <
class T> image<T>::~image() {
97 template <
class T>
void image<T>::init(
const T &val) {
98 T *ptr = imPtr(
this, 0, 0);
99 T *end = imPtr(
this, w-1, h-1);
105 template <
class T> image<T> *image<T>::copy()
const {
106 image<T> *im =
new image<T>(w, h,
false);
107 memcpy(im->data, data, w * h *
sizeof(T));
113 void pnm_read(std::ifstream &file,
char *buf) {
119 file.getline(doc, BUF_SIZE);
124 file.width(BUF_SIZE);
129 image<uchar> *loadPGM(
const char *name) {
133 std::ifstream file(name, std::ios::in | std::ios::binary);
135 if (strncmp(buf,
"P5", 2)) {
136 std::cout <<
"ERROR: Could not read file " << name << std::endl;
141 int width = atoi(buf);
143 int height = atoi(buf);
146 if (atoi(buf) > UCHAR_MAX) {
147 std::cout <<
"ERROR: Could not read file " << name << std::endl;
152 image<uchar> *im =
new image<uchar>(width, height);
153 file.read((
char *)imPtr(im, 0, 0), width * height *
sizeof(uchar));
158 void savePGM(image<uchar> *im,
const char *name) {
159 int width = im->width();
160 int height = im->height();
161 std::ofstream file(name, std::ios::out | std::ios::binary);
163 file <<
"P5\n" << width <<
" " << height <<
"\n" << UCHAR_MAX <<
"\n";
164 file.write((
char *)imPtr(im, 0, 0), width * height *
sizeof(uchar));