Debian Codegraph @

cvd_src/image_io/pnm_grok.cxx

raw symbols SCIP
1 /*******************************************************************************
2
3 pnm_grok.cxx Ed Rosten 2003
4
5 This file provides very basic functionality for accessing PNM images. PNM images
6 are either greyscale (PBMs are treated as PGMs of depth 1) or RGB, and either 1
7 or 2 bytes per element.
8
9 Images are dealt with by lines. 1 byte images are delt with as lines of
10 unsigned chars and 2 byte images are dealt with as lines of unsigned shorts.
11 Luma images are stored as an array on luma pixel values and RGB images are
12 dealt with as RGBRGBRGB... packed in to an array. The base class provides the
13 method elements_per_line() which returns the length of the array needed to
14 store a single line of the image.
15
16 The library here provides no image re-encoding. A 2 byte colour image can only
17 be read as a 2 byte colour image. The exception is that a PBM is read as a PGM
18 of depth 1.
19
20 In case of an error, an exception of type err is thrown. The error codes are
21 arranged in to errors to do with the PNM images and things probably resulting
22 from a logic error in the calling program.
23
24 *******************************************************************************/
25
26 #include <ctype.h>
27 #include <iostream>
28 #include <limits>
29
30 #include "cvd_src/config_internal.h"
31 #include <cvd/internal/io/pnm_grok.h>
32 #include <cvd/internal/load_and_save.h>
33
34 /* Compile time, arch specific parameters
35
36 PNMs are big endian, so for them to be loaded quickly (ie using fwrite), the
37 bytes have to be swapped on little endian machines. This is OK for loading
38 since the byte swapping can be done in place, but not OK for saving since the
39 array of data is passed as const, so it can't be swapped in place.
40
41 Short and long PNMs are the same thing. they're 2 byte PNMs (long because
42 they're longer than byte PNMs and short since they fit in to the "short"
43 data type).
44 */
45
46 #if defined CVD_INTERNAL_ARCH_LITTLE_ENDIAN
47 #define SWAP_BYTES
48 #elif defined CVD_INTERNAL_ARCH_BIG_ENDIAN
49
50 #else
51 #error "No endianness specified!"
52 #endif
53
54 #define PBM 0
55 #define PGM 1
56 #define PPM 2
57
58 using namespace std;
59 using namespace CVD::Exceptions::Image_IO;
60
61 namespace CVD
62 {
63 namespace PNM
64 {
65
66 //All possible error codes. These are loosely divided in to data errors (ie
67 //problems with the input image) and programmer errors (runtime errors
68 //which are almost definitely caused by some logic error in the program).
69 enum errors
70 {
71 E_NONE = 0, //Data errors
72 E_NOT_PNM,
73 E_HEOF,
74 E_DEOF,
75 E_BAD_SIZE,
76 E_BAD_MAXVAL,
77 E_PBM_NOT_IMPLEMENTED,
78 E_OUT_OF_MEMORY,
79 E_UNTERMINATED_HEADER,
80 E_PAM_NOT_IMPLEMENTED,
81 E_LAST_DATA_ERROR,
82
83 E_PROGRAMMER_ERROR = 255, //All data errors are sit below this
84
85 //Probably programmer errors:
86 E_NO_LONG_PBM,
87 E_WRITE_PAST_END,
88 E_NOT_2_BYTE,
89 E_NOT_1_BYTE,
90 E_READ_PAST_END,
91
92 E_MAX //All errors sit below this
93 };
94
95 string name_error(errors e)
96 {
97 const char* data_error_names[] = {
98 "None.",
99 "Not a PNM.",
100 "EOF in header.",
101 "EOF in data.",
102 "Bad size specified.",
103 "Invalid colour MAXVAL.",
104 "Binary PBMs are not implemented.",
105 "Out of memory.",
106 "Unterminated header.",
107 "Portable Arbirtary Maps are not implemented.",
108 "Last data error. This should *never* occur."
109 };
110
111 const char* prog_error_names[] = {
112 "Long PBMs are silly.",
113 "Trying to write past end of file.",
114 "This is not a 2 byte PNM.",
115 "This is not a 1 byte PNM.",
116 "Trying to read past the end of the file."
117 };
118
119 const char* invalid = "Not a valid error.";
120
121 string ret;
122
123 if(e < 0 || e >= E_MAX)
124 ret = string("internal error: ") + invalid;
125 else if(e >= E_LAST_DATA_ERROR && e <= E_PROGRAMMER_ERROR)
126 ret = string("internal error: ") + invalid;
127 else if(e < E_LAST_DATA_ERROR)
128 ret = data_error_names[e];
129 else
130 ret = string("internal error: ") + prog_error_names[e - E_PROGRAMMER_ERROR - 1];
131
132 return "Error in PNM image: " + ret;
133 }
134
135 class pnm_in
136 {
137 public:
138 pnm_in(std::istream&);
139 ImageRef size();
140 string datatype();
141
142 template <class C>
143 void get_raw_pixel_lines(C* c, unsigned long nlines);
144
145 private:
146 bool m_is_2_byte;
147 int m_channels;
148 string elemtype;
149 std::istream& i;
150 bool is_text;
151 int type, maxval;
152 long lines_so_far;
153 void read_header();
154 bool can_proc_lines(unsigned long);
155 int xs, ys;
156 };
157
158 bool clean(istream& i)
159 {
160 ////////////////////////////////////////////////////////////////////////////
161 //
162 // Strip leading whitespae and PNM comments from an istream
163 // comments start with a '#' and and with a newline
164
165 unsigned char c;
166
167 for(;;)
168 {
169 i >> c;
170
171 if(i.eof()) //I'm pedantic like that.
172 return 0;
173 else if(c == '#') //Eat a whole line of comment
174 {
175 do
176 {
177 i >> c;
178 if(i.eof()) //I'm still a pedant
179 return 0;
180 } while(c != '\n');
181 }
182 else if(!isspace(c))
183 {
184 i.putback(c);
185 return 1;
186 }
187 }
188 }
189
190 ////////////////////////////////////////////////////////////////////////////////
191 //
192 // base PNM class definitions
193 //
194 ////////////////////////////////////////////////////////////////////////////////
195
196 bool pnm_in::can_proc_lines(unsigned long nl)
197 {
198 //Slightly oddly named. Update the number of processed lines and return
199 //an error condition if the lines can not be processed.
200
201 lines_so_far += nl;
202 if(lines_so_far > ys)
203 return false;
204 else
205 return true;
206 }
207
208 ////////////////////////////////////////////////////////////////////////////////
209 //
210 // Input PNM class definitions
211 //
212 ////////////////////////////////////////////////////////////////////////////////
213
214 pnm_in::pnm_in(std::istream& in)
215 : i(in)
216 {
217 lines_so_far = 0;
218 read_header();
219 }
220
221 void pnm_in::read_header()
222 {
223 //Fix the stream before returning.
224 #define RETURN(X) \
225 do \
226 { \
227 i >> skipws; \
228 if(X == E_NONE) \
229 return; \
230 else \
231 throw Exceptions::Image_IO::MalformedImage(name_error(X)); \
232 } while(0)
233
234 #define CLEAN \
235 do \
236 { \
237 if(!clean(i)) \
238 throw Exceptions::Image_IO::MalformedImage(name_error(E_HEOF)); \
239 } while(0)
240
241 #define GET(X) \
242 do \
243 { \
244 CLEAN; \
245 i >> X; \
246 if(i.eof()) \
247 throw Exceptions::Image_IO::MalformedImage(name_error(E_HEOF)); \
248 } while(0)
249
250 char c1, c2;
251
252 // i >> (int) will eat whitespace before and after the integer. This breaks
253 // reading maxval since it can (and does) eat in to the image.
254 i >> noskipws;
255
256 //Read and check magic number
257
258 i >> c1 >> c2;
259 if(i.eof())
260 RETURN(E_HEOF);
261
262 if(c1 != 'P' || c2 < '1' || c2 > '7')
263 RETURN(E_NOT_PNM);
264
265 if(c2 == '7')
266 RETURN(E_PAM_NOT_IMPLEMENTED);
267
268 if(strchr("123", c2))
269 is_text = true;
270 else
271 is_text = false;
272
273 if(c2 == '1' || c2 == '4')
274 type = PBM;
275 else if(c2 == '2' || c2 == '5')
276 type = PGM;
277 else
278 type = PPM;
279
280 if(type == PGM)
281 m_channels = 1;
282 else
283 m_channels = 3;
284
285 //Read and check image dimensions
286 GET(xs);
287 GET(ys);
288
289 if(xs <= 0 || ys <= 0)
290 RETURN(E_BAD_SIZE);
291
292 //Read if necessasy and set MAXVAL
293 if(type != PBM)
294 {
295 GET(maxval);
296
297 if(maxval <= 0 || maxval > 65535)
298 RETURN(E_BAD_MAXVAL);
299
300 if(maxval <= 255)
301 m_is_2_byte = false;
302 else
303 m_is_2_byte = true;
304 }
305 else
306 {
307 maxval = 255;
308 m_is_2_byte = false;
309 }
310
311 if(type == PBM)
312 elemtype = "bool";
313 else if(type == PGM)
314 {
315 if(m_is_2_byte)
316 elemtype = PNM::type_name<unsigned short>::name();
317 else
318 elemtype = PNM::type_name<byte>::name();
319 }
320 if(type == PPM)
321 {
322 if(m_is_2_byte)
323 elemtype = PNM::type_name<Rgb<unsigned short>>::name();
324 else
325 elemtype = PNM::type_name<Rgb<byte>>::name();
326 }
327
328 //Remove everything to the beginning of the image
329 if(is_text)
330 CLEAN;
331 else
332 {
333 //Binary PNMs have a single byte of whitespace.
334
335 unsigned char tmp;
336 i >> tmp;
337 if(!isspace(tmp))
338 RETURN(E_UNTERMINATED_HEADER);
339 }
340
341 //hee hee hee. This makes the SGI compiler segfault :-)
342 // RETURN(E_NONE);
343 i >> skipws;
344
345 //HACK
346 //cerr << "is_rgb=" << m_is_rgb <<". xsize=" << xs << ". ysize=" << ys << ". is_text=" << is_text << ". type=" << type << ". maxval=" << maxval << endl;
347
348 return;
349 #undef RETURN
350 #undef CLEAN
351 #undef GET
352 }
353
354 //Text reading functions
355 void get_num(istream& i, byte* c)
356 {
357 int j = 0;
358 i >> j; //Ignore EOF: be leniant
359 *c = static_cast<byte>(j & 0xff);
360 }
361
362 void get_num(istream& i, bool* c)
363 {
364 i >> ws;
365 int j = cin.get();
366 //PBMs are inverted
367 *c = (j != '0');
368 }
369
370 void get_num(istream& i, unsigned short* c)
371 {
372 int j = 0;
373 i >> j; //Ignore EOF: be leniant
374 *c = static_cast<unsigned short>(j & 0xffff);
375 }
376
377 template <class C>
378 void get_num(istream& i, Rgb<C>* c)
379 {
380 get_num(i, &(c->red));
381 get_num(i, &(c->green));
382 get_num(i, &(c->blue));
383 }
384
385 //Data reading functions
386 void really_swap(unsigned char* s, size_t n_elem)
387 {
388 #ifdef SWAP_BYTES
389 for(size_t j = 0; j < n_elem; j++)
390 swap(s[2 * j], s[2 * j + 1]);
391 #endif
392 }
393
394 void maybe_swap(unsigned short* s, size_t n)
395 {
396 really_swap((unsigned char*)s, n);
397 }
398 void maybe_swap(Rgb<unsigned short>* s, size_t n)
399 {
400 really_swap((unsigned char*)s, n * 3);
401 }
402
403 void maybe_swap(bool*, size_t)
404 {
405 }
406 void maybe_swap(byte*, size_t)
407 {
408 }
409 void maybe_swap(Rgb<byte>*, size_t)
410 {
411 }
412
413 template <class C>
414 void pnm_in::get_raw_pixel_lines(C* c, unsigned long nlines)
415 {
416 if(datatype() != PNM::type_name<C>::name())
417 throw ReadTypeMismatch(datatype(), PNM::type_name<C>::name());
418
419 //Reading into uchars is sufficiently different from reading in to
420 //ushorts, so it has ben done as 2 functions as opposed to one
421 //tmeplated one.
422
423 unsigned long k, npix;
424 if(!can_proc_lines(nlines))
425 throw Exceptions::Image_IO::MalformedImage(name_error(E_READ_PAST_END));
426
427 //Load a bunch of pixels in to memory without doing internal buffering
428 npix = xs * nlines;
429
430 if(is_text) //Load text PNM data
431 {
432 for(k = 0; k < npix; k++)
433 get_num(i, c++);
434 }
435 else if(type != PBM)
436 {
437 if(type == PBM)
438 throw Exceptions::Image_IO::MalformedImage(name_error(E_PBM_NOT_IMPLEMENTED));
439
440 i.read((char*)c, m_channels * npix * (m_is_2_byte ? 2 : 1));
441 maybe_swap(c, npix);
442 }
443
444 //Don't report errors. The spec says to be really leniant with
445 //respect to errors in text only pnms
446 if(!is_text && i.fail())
447 throw Exceptions::Image_IO::MalformedImage(name_error(E_DEOF));
448 }
449
450 ImageRef pnm_in::size()
451 {
452 return ImageRef(xs, ys);
453 }
454
455 string pnm_in::datatype()
456 {
457 return elemtype;
458 }
459
460 ////////////////////////////////////////////////////////////////////////////////
461 //
462 // Implementation of PNM reader class
463 //
464
465 Reader::~Reader()
466 {
467 }
468
469 Reader::Reader(istream& i)
470 : p(new pnm_in(i))
471 {
472 }
473
474 string Reader::datatype()
475 {
476 return p->datatype();
477 }
478
479 bool Reader::top_row_first()
480 {
481 return true;
482 }
483 string Reader::name()
484 {
485 return "PNM";
486 }
487
488 ImageRef Reader::size()
489 {
490 return p->size();
491 }
492
493 //Mechanically generate the pixel reading calls.
494 #define GEN1(X) \
495 void Reader::get_raw_pixel_line(X* d) { p->get_raw_pixel_lines(d, 1); }
496 #define GEN2(X) \
497 GEN1(X) \
498 GEN1(Rgb<X>)
499 GEN1(bool)
500 GEN2(unsigned char)
501 GEN2(unsigned short)
502
503 #undef GEN1
504 #undef GEN2
505 ////////////////////////////////////////////////////////////////////////////////
506 //
507 // Output PNM class definitions
508 //
509 ////////////////////////////////////////////////////////////////////////////////
510
511 class pnm_writer
512 {
513 public:
514 pnm_writer(std::ostream&, ImageRef size, const std::string& type, const std::map<std::string, Parameter<>>& p);
515 ~pnm_writer();
516
517 //void write_raw_pixel_line(const bool*);
518 template <class C>
519 void write_raw_pixel_line(const C*);
520
521 private:
522 void write_shorts(const unsigned char* data, size_t n_shorts);
523 void write_binary(const unsigned char* data, size_t n);
524 void write_binary(const unsigned short* data, size_t n);
525 void write_binary(const Rgb<unsigned char>* data, size_t n);
526 void write_binary(const Rgb<unsigned short>* data, size_t n);
527
528 template <class P>
529 void sanity_check(const P*);
530
531 bool text;
532 long row;
533 std::ostream& o;
534 ImageRef size;
535 std::string type;
536 vector<unsigned char> rowbuf;
537 };
538
539 void writePNMHeader(ostream& out, int channels, ImageRef size, int maxval, bool text, const std::string& comments)
540 {
541 char m[3] = { 'P', ' ', '\n' };
542 if(channels == 1)
543 m[1] = '2';
544 else
545 m[1] = '3';
546 if(!text)
547 m[1] += 3;
548 out.write(m, 3);
549 bool freshLine = true;
550 for(size_t i = 0; i < comments.length(); i++)
551 {
552 if(freshLine)
553 out << "# ";
554 char c = comments[i];
555 if(c == '\n')
556 {
557 freshLine = true;
558 out << endl;
559 }
560 else
561 {
562 out << c;
563 freshLine = false;
564 }
565 }
566 if(!freshLine)
567 out << endl;
568 out << size.x << " " << size.y << endl
569 << maxval << endl;
570 }
571
572 pnm_writer::pnm_writer(std::ostream& out, ImageRef size_, const std::string& type_, const std::map<std::string, Parameter<>>& p)
573 : text(0)
574 , row(0)
575 , o(out)
576 , size(size_)
577 , type(type_)
578 {
579 if(p.count("pnm.raw"))
580 {
581 try
582 {
583 text = !(p.find("pnm.raw")->second.get<bool>());
584 }
585 catch(const std::bad_cast&)
586 {
587 cerr << "Warning pnm.raw is not a bool.\n";
588 }
589 }
590
591 if(type == "unsigned char")
592 writePNMHeader(out, 1, size, 255, text, "");
593 else if(type == "unsigned short")
594 writePNMHeader(out, 1, size, 65535, text, "");
595 else if(type == "CVD::Rgb<unsigned char>")
596 writePNMHeader(out, 3, size, 255, text, "");
597 else if(type == "CVD::Rgb<unsigned short>")
598 writePNMHeader(out, 3, size, 65535, text, "");
599 else
600 throw UnsupportedImageSubType("PNM", type);
601 }
602
603 pnm_writer::~pnm_writer()
604 {
605 }
606
607 void pnm_writer::write_shorts(const unsigned char* data, size_t n_shorts)
608 {
609 #ifdef SWAP_BYTES
610 rowbuf.resize(n_shorts * sizeof(short));
611 copy(data, data + sizeof(short) * n_shorts, rowbuf.begin());
612
613 for(size_t i = 0; i < rowbuf.size(); i += 2)
614 swap(rowbuf[i], rowbuf[i + 1]);
615
616 o.write((char*)&rowbuf[0], rowbuf.size());
617 //for (size_t i=0; i<n_shorts; i++)
618 //o << data[2*i+1] << data[2*i];
619 #else
620 o.write((const char*)data, n_shorts * sizeof(unsigned short));
621 #endif
622 }
623
624 void pnm_writer::write_binary(const unsigned char* data, size_t n)
625 {
626 o.write(reinterpret_cast<const char*>(data), n);
627 }
628 void pnm_writer::write_binary(const unsigned short* data, size_t n)
629 {
630 write_shorts(reinterpret_cast<const unsigned char*>(data), n);
631 }
632 void pnm_writer::write_binary(const Rgb<unsigned char>* data, size_t n)
633 {
634 o.write(reinterpret_cast<const char*>(data), n * 3);
635 }
636 void pnm_writer::write_binary(const Rgb<unsigned short>* data, size_t n)
637 {
638 write_shorts(reinterpret_cast<const unsigned char*>(data), n * 3);
639 }
640
641 template <class C>
642 void write_text(const C* data, size_t n, ostream& o)
643 {
644 for(size_t i = 0; i < n; i++)
645 o << (int)data[i] << endl;
646 }
647
648 template <class C>
649 void write_text(const Rgb<C>* data, size_t n, ostream& o)
650 {
651 for(size_t i = 0; i < n; i++)
652 o << (int)data[i].red << " " << (int)data[i].green << " " << (int)data[i].blue << endl;
653 }
654
655 template <class C>
656 void pnm_writer::write_raw_pixel_line(const C* data)
657 {
658 if(type != PNM::type_name<C>::name())
659 throw WriteTypeMismatch(type, PNM::type_name<C>::name());
660
661 //Do some sanity checking
662 if(row >= size.y)
663 throw InternalLibraryError("CVD", "Write past end of image.");
664
665 row++;
666
667 if(text)
668 write_text(data, size.x, o);
669 else
670 write_binary(data, size.x);
671 }
672
673 ////////////////////////////////////////////////////////////////////////////////
674 //
675 // Public interface
676 //
677
678 Writer::Writer(std::ostream& out, ImageRef size_, const std::string& type_, const std::map<std::string, Parameter<>>& p)
679 : p(new pnm_writer(out, size_, type_, p))
680 {
681 }
682
683 Writer::~Writer()
684 {
685 }
686
687 //Mechanically generate the pixel writing calls.
688 #define GEN1(X) \
689 void Writer::write_raw_pixel_line(const X* d) { p->write_raw_pixel_line(d); }
690 #define GEN2(X) \
691 GEN1(X) \
692 GEN1(Rgb<X>)
693 //GEN1(bool)
694 GEN2(unsigned char)
695 GEN2(unsigned short)
696
697 #undef GEN1
698 #undef GEN2
699 }
700 }