Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/imgcodecs/src/grfmt_pam.cpp
16337 views
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
8
//
9
//
10
// License Agreement
11
// For Open Source Computer Vision Library
12
// (3-clause BSD License)
13
//
14
// Copyright (C) 2000-2016, Intel Corporation, all rights reserved.
15
// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
16
// Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
17
// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
18
// Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved.
19
// Copyright (C) 2015-2016, Itseez Inc., all rights reserved.
20
// Third party copyrights are property of their respective owners.
21
//
22
// Redistribution and use in source and binary forms, with or without modification,
23
// are permitted provided that the following conditions are met:
24
//
25
// * Redistributions of source code must retain the above copyright notice,
26
// this list of conditions and the following disclaimer.
27
//
28
// * Redistributions in binary form must reproduce the above copyright notice,
29
// this list of conditions and the following disclaimer in the documentation
30
// and/or other materials provided with the distribution.
31
//
32
// * Neither the names of the copyright holders nor the names of the contributors
33
// may be used to endorse or promote products derived from this software
34
// without specific prior written permission.
35
//
36
// This software is provided by the copyright holders and contributors "as is" and
37
// any express or implied warranties, including, but not limited to, the implied
38
// warranties of merchantability and fitness for a particular purpose are disclaimed.
39
// In no event shall copyright holders or contributors be liable for any direct,
40
// indirect, incidental, special, exemplary, or consequential damages
41
// (including, but not limited to, procurement of substitute goods or services;
42
// loss of use, data, or profits; or business interruption) however caused
43
// and on any theory of liability, whether in contract, strict liability,
44
// or tort (including negligence or otherwise) arising in any way out of
45
// the use of this software, even if advised of the possibility of such damage.
46
//
47
//M*/
48
49
#include "precomp.hpp"
50
51
52
#ifdef HAVE_IMGCODEC_PXM
53
54
#include <cerrno>
55
56
#include "utils.hpp"
57
#include "grfmt_pam.hpp"
58
59
using namespace cv;
60
61
/* the PAM related fields */
62
#define MAX_PAM_HEADER_IDENITFIER_LENGTH 8
63
#define MAX_PAM_HEADER_VALUE_LENGTH 255
64
65
/* PAM header fileds */
66
typedef enum {
67
PAM_HEADER_NONE,
68
PAM_HEADER_COMMENT,
69
PAM_HEADER_ENDHDR,
70
PAM_HEADER_HEIGHT,
71
PAM_HEADER_WIDTH,
72
PAM_HEADER_DEPTH,
73
PAM_HEADER_MAXVAL,
74
PAM_HEADER_TUPLTYPE,
75
} PamHeaderFieldType;
76
77
struct pam_header_field {
78
PamHeaderFieldType type;
79
char identifier[MAX_PAM_HEADER_IDENITFIER_LENGTH+1];
80
};
81
82
const static struct pam_header_field fields[] = {
83
{PAM_HEADER_ENDHDR, "ENDHDR"},
84
{PAM_HEADER_HEIGHT, "HEIGHT"},
85
{PAM_HEADER_WIDTH, "WIDTH"},
86
{PAM_HEADER_DEPTH, "DEPTH"},
87
{PAM_HEADER_MAXVAL, "MAXVAL"},
88
{PAM_HEADER_TUPLTYPE, "TUPLTYPE"},
89
};
90
#define PAM_FIELDS_NO (sizeof (fields) / sizeof ((fields)[0]))
91
92
typedef bool (*cvtFunc) (void *src, void *target, int width, int target_channels,
93
int target_depth);
94
95
struct channel_layout {
96
uint rchan, gchan, bchan, graychan;
97
};
98
99
struct pam_format {
100
uint fmt;
101
char name[MAX_PAM_HEADER_VALUE_LENGTH+1];
102
cvtFunc cvt_func;
103
/* the channel layout that should be used when
104
* imread_ creates a 3 channel or 1 channel image
105
* used when no conversion function is available
106
*/
107
struct channel_layout layout;
108
};
109
110
static bool rgb_convert (void *src, void *target, int width, int target_channels,
111
int target_depth);
112
113
const static struct pam_format formats[] = {
114
{CV_IMWRITE_PAM_FORMAT_NULL, "", NULL, {0, 0, 0, 0} },
115
{CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE, "BLACKANDWHITE", NULL, {0, 0, 0, 0} },
116
{CV_IMWRITE_PAM_FORMAT_GRAYSCALE, "GRAYSCALE", NULL, {0, 0, 0, 0} },
117
{CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA, "GRAYSCALE_ALPHA", NULL, {0, 0, 0, 0} },
118
{CV_IMWRITE_PAM_FORMAT_RGB, "RGB", rgb_convert, {0, 1, 2, 0} },
119
{CV_IMWRITE_PAM_FORMAT_RGB_ALPHA, "RGB_ALPHA", NULL, {0, 1, 2, 0} },
120
};
121
#define PAM_FORMATS_NO (sizeof (fields) / sizeof ((fields)[0]))
122
123
/*
124
* conversion functions
125
*/
126
127
static bool
128
rgb_convert (void *src, void *target, int width, int target_channels, int target_depth)
129
{
130
bool ret = false;
131
if (target_channels == 3) {
132
switch (target_depth) {
133
case CV_8U:
134
icvCvt_RGB2BGR_8u_C3R( (uchar*) src, 0, (uchar*) target, 0,
135
cvSize(width,1) );
136
ret = true;
137
break;
138
case CV_16U:
139
icvCvt_RGB2BGR_16u_C3R( (ushort *)src, 0, (ushort *)target, 0,
140
cvSize(width,1) );
141
ret = true;
142
break;
143
default:
144
break;
145
}
146
} else if (target_channels == 1) {
147
switch (target_depth) {
148
case CV_8U:
149
icvCvt_BGR2Gray_8u_C3C1R( (uchar*) src, 0, (uchar*) target, 0,
150
cvSize(width,1), 2 );
151
ret = true;
152
break;
153
case CV_16U:
154
icvCvt_BGRA2Gray_16u_CnC1R( (ushort *)src, 0, (ushort *)target, 0,
155
cvSize(width,1), 3, 2 );
156
ret = true;
157
break;
158
default:
159
break;
160
}
161
}
162
return ret;
163
}
164
165
/*
166
* copy functions used as a fall back for undefined formats
167
* or simpler conversion options
168
*/
169
170
static void
171
basic_conversion (void *src, const struct channel_layout *layout, int src_sampe_size,
172
int src_width, void *target, int target_channels, int target_depth)
173
{
174
switch (target_depth) {
175
case CV_8U:
176
{
177
uchar *d = (uchar *)target, *s = (uchar *)src,
178
*end = ((uchar *)src) + src_width;
179
switch (target_channels) {
180
case 1:
181
for( ; s < end; d += 3, s += src_sampe_size )
182
d[0] = d[1] = d[2] = s[layout->graychan];
183
break;
184
case 3:
185
for( ; s < end; d += 3, s += src_sampe_size ) {
186
d[0] = s[layout->bchan];
187
d[1] = s[layout->gchan];
188
d[2] = s[layout->rchan];
189
}
190
break;
191
default:
192
CV_Error(Error::StsInternal, "");
193
}
194
break;
195
}
196
case CV_16U:
197
{
198
ushort *d = (ushort *)target, *s = (ushort *)src,
199
*end = ((ushort *)src) + src_width;
200
switch (target_channels) {
201
case 1:
202
for( ; s < end; d += 3, s += src_sampe_size )
203
d[0] = d[1] = d[2] = s[layout->graychan];
204
break;
205
case 3:
206
for( ; s < end; d += 3, s += src_sampe_size ) {
207
d[0] = s[layout->bchan];
208
d[1] = s[layout->gchan];
209
d[2] = s[layout->rchan];
210
}
211
break;
212
default:
213
CV_Error(Error::StsInternal, "");
214
}
215
break;
216
}
217
default:
218
CV_Error(Error::StsInternal, "");
219
}
220
}
221
222
223
static bool ReadPAMHeaderLine (cv::RLByteStream& strm,
224
PamHeaderFieldType &fieldtype,
225
char value[MAX_PAM_HEADER_VALUE_LENGTH+1])
226
{
227
int code, pos;
228
bool ident_found = false;
229
uint i;
230
char ident[MAX_PAM_HEADER_IDENITFIER_LENGTH+1] = { 0 };
231
232
do {
233
code = strm.getByte();
234
} while ( isspace(code) );
235
236
if (code == '#') {
237
/* we are in a comment, eat characters until linebreak */
238
do
239
{
240
code = strm.getByte();
241
} while( code != '\n' && code != '\r' );
242
fieldtype = PAM_HEADER_COMMENT;
243
return true;
244
} else if (code == '\n' || code == '\r' ) {
245
fieldtype = PAM_HEADER_NONE;
246
return true;
247
}
248
249
/* nul-ify buffers before writing to them */
250
memset (ident, '\0', sizeof(char) * MAX_PAM_HEADER_IDENITFIER_LENGTH);
251
for (i=0; i<MAX_PAM_HEADER_IDENITFIER_LENGTH; i++) {
252
if (!isspace(code))
253
ident[i] = (char) code;
254
else
255
break;
256
code = strm.getByte();
257
}
258
259
/* we may have filled the buffer and still have data */
260
if (!isspace(code))
261
return false;
262
263
for (i=0; i<PAM_FIELDS_NO; i++) {
264
if (strncmp(fields[i].identifier, ident, MAX_PAM_HEADER_IDENITFIER_LENGTH+1) == 0) {
265
fieldtype = fields[i].type;
266
ident_found = true;
267
}
268
}
269
270
if (!ident_found)
271
return false;
272
273
memset (value, '\0', sizeof(char) * MAX_PAM_HEADER_VALUE_LENGTH);
274
/* we may have an identifier that has no value */
275
if (code == '\n' || code == '\r')
276
return true;
277
278
do {
279
code = strm.getByte();
280
} while ( isspace(code) );
281
282
283
284
/* read identifier value */
285
for (i=0; i<MAX_PAM_HEADER_VALUE_LENGTH; i++) {
286
if (code != '\n' && code != '\r') {
287
value[i] = (char) code;
288
} else if (code != '\n' || code != '\r')
289
break;
290
code = strm.getByte();
291
}
292
pos = i;
293
294
/* should be terminated */
295
if (code != '\n' && code != '\r')
296
return false;
297
298
/* remove trailing white spaces */
299
while (pos >= 0 && isspace(value[pos]))
300
value[pos--] = '\0';
301
302
return true;
303
}
304
305
static bool ParseNumber (char *str, int *retval)
306
{
307
char *endptr;
308
long lval = strtol (str, &endptr, 0);
309
310
if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
311
|| (errno != 0 && lval == 0)) {
312
return false;
313
}
314
if (endptr == str) {
315
return false;
316
}
317
318
*retval = (int) lval;
319
320
return true;
321
}
322
323
namespace cv
324
{
325
326
PAMDecoder::PAMDecoder()
327
{
328
m_offset = -1;
329
m_buf_supported = true;
330
bit_mode = false;
331
selected_fmt = CV_IMWRITE_PAM_FORMAT_NULL;
332
m_maxval = 0;
333
m_channels = 0;
334
m_sampledepth = 0;
335
}
336
337
338
PAMDecoder::~PAMDecoder()
339
{
340
m_strm.close();
341
}
342
343
size_t PAMDecoder::signatureLength() const
344
{
345
return 3;
346
}
347
348
bool PAMDecoder::checkSignature( const String& signature ) const
349
{
350
return signature.size() >= 3 && signature[0] == 'P' &&
351
signature[1] == '7' &&
352
isspace(signature[2]);
353
}
354
355
ImageDecoder PAMDecoder::newDecoder() const
356
{
357
return makePtr<PAMDecoder>();
358
}
359
360
struct parsed_fields
361
{
362
bool endhdr, height, width, depth, maxval;
363
};
364
365
#define HEADER_READ_CORRECT(pf) (pf.endhdr && pf.height && pf.width \
366
&& pf.depth && pf.maxval)
367
368
369
bool PAMDecoder::readHeader()
370
{
371
PamHeaderFieldType fieldtype = PAM_HEADER_NONE;
372
char value[MAX_PAM_HEADER_VALUE_LENGTH+1];
373
int byte;
374
struct parsed_fields flds;
375
if( !m_buf.empty() )
376
{
377
if( !m_strm.open(m_buf) )
378
return false;
379
}
380
else if( !m_strm.open( m_filename ))
381
return false;
382
CV_TRY
383
{
384
byte = m_strm.getByte();
385
if( byte != 'P' )
386
CV_THROW( RBS_BAD_HEADER );
387
388
byte = m_strm.getByte();
389
if (byte != '7')
390
CV_THROW( RBS_BAD_HEADER );
391
392
byte = m_strm.getByte();
393
if (byte != '\n' && byte != '\r')
394
CV_THROW( RBS_BAD_HEADER );
395
396
uint i;
397
memset (&flds, 0x00, sizeof (struct parsed_fields));
398
do {
399
if (!ReadPAMHeaderLine(m_strm, fieldtype, value))
400
CV_THROW( RBS_BAD_HEADER );
401
switch (fieldtype) {
402
case PAM_HEADER_NONE:
403
case PAM_HEADER_COMMENT:
404
continue;
405
case PAM_HEADER_ENDHDR:
406
flds.endhdr = true;
407
break;
408
case PAM_HEADER_HEIGHT:
409
if (flds.height)
410
CV_THROW( RBS_BAD_HEADER );
411
if (!ParseNumber (value, &m_height))
412
CV_THROW( RBS_BAD_HEADER );
413
flds.height = true;
414
break;
415
case PAM_HEADER_WIDTH:
416
if (flds.width)
417
CV_THROW( RBS_BAD_HEADER );
418
if (!ParseNumber (value, &m_width))
419
CV_THROW( RBS_BAD_HEADER );
420
flds.width = true;
421
break;
422
case PAM_HEADER_DEPTH:
423
if (flds.depth)
424
CV_THROW( RBS_BAD_HEADER );
425
if (!ParseNumber (value, &m_channels))
426
CV_THROW( RBS_BAD_HEADER );
427
flds.depth = true;
428
break;
429
case PAM_HEADER_MAXVAL:
430
if (flds.maxval)
431
CV_THROW( RBS_BAD_HEADER );
432
if (!ParseNumber (value, &m_maxval))
433
CV_THROW( RBS_BAD_HEADER );
434
if ( m_maxval > 65535 )
435
CV_THROW( RBS_BAD_HEADER );
436
if ( m_maxval > 255 ) {
437
m_sampledepth = CV_16U;
438
}
439
else
440
m_sampledepth = CV_8U;
441
if (m_maxval == 1)
442
bit_mode = true;
443
flds.maxval = true;
444
break;
445
case PAM_HEADER_TUPLTYPE:
446
for (i=0; i<PAM_FORMATS_NO; i++) {
447
if (strncmp(formats[i].name,
448
value, MAX_PAM_HEADER_VALUE_LENGTH+1) == 0) {
449
selected_fmt = formats[i].fmt;
450
}
451
}
452
break;
453
default:
454
CV_THROW( RBS_BAD_HEADER );
455
}
456
} while (fieldtype != PAM_HEADER_ENDHDR);
457
458
if (HEADER_READ_CORRECT(flds)) {
459
if (selected_fmt == CV_IMWRITE_PAM_FORMAT_NULL) {
460
if (m_channels == 1 && m_maxval == 1)
461
selected_fmt = CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE;
462
else if (m_channels == 1 && m_maxval < 256)
463
selected_fmt = CV_IMWRITE_PAM_FORMAT_GRAYSCALE;
464
else if (m_channels == 3 && m_maxval < 256)
465
selected_fmt = CV_IMWRITE_PAM_FORMAT_RGB;
466
}
467
m_type = CV_MAKETYPE(m_sampledepth, m_channels);
468
m_offset = m_strm.getPos();
469
470
return true;
471
}
472
} CV_CATCH_ALL
473
{
474
}
475
476
m_offset = -1;
477
m_width = m_height = -1;
478
m_strm.close();
479
return false;
480
}
481
482
483
bool PAMDecoder::readData( Mat& img )
484
{
485
uchar* data = img.ptr();
486
int target_channels = img.channels();
487
size_t imp_stride = img.step;
488
int sample_depth = CV_ELEM_SIZE1(m_type);
489
int src_elems_per_row = m_width*m_channels;
490
int src_stride = src_elems_per_row*sample_depth;
491
int x, y;
492
bool res = false, funcout;
493
PaletteEntry palette[256];
494
const struct pam_format *fmt = NULL;
495
struct channel_layout layout = { 0, 0, 0, 0 }; // normalized to 1-channel grey format
496
497
/* setting buffer to max data size so scaling up is possible */
498
AutoBuffer<uchar> _src(src_elems_per_row * 2);
499
uchar* src = _src.data();
500
501
if( m_offset < 0 || !m_strm.isOpened())
502
return false;
503
504
if (selected_fmt != CV_IMWRITE_PAM_FORMAT_NULL)
505
fmt = &formats[selected_fmt];
506
else {
507
/* default layout handling */
508
if (m_channels >= 3) {
509
layout.bchan = 0;
510
layout.gchan = 1;
511
layout.rchan = 2;
512
}
513
}
514
515
CV_TRY
516
{
517
m_strm.setPos( m_offset );
518
519
/* the case where data fits the opencv matrix */
520
if (m_sampledepth == img.depth() && target_channels == m_channels && !bit_mode) {
521
/* special case for 16bit images with wrong endianness */
522
if (m_sampledepth == CV_16U && !isBigEndian())
523
{
524
for (y = 0; y < m_height; y++, data += imp_stride )
525
{
526
m_strm.getBytes( src, src_stride );
527
for( x = 0; x < src_elems_per_row; x++ )
528
{
529
uchar v = src[x * 2];
530
data[x * 2] = src[x * 2 + 1];
531
data[x * 2 + 1] = v;
532
}
533
}
534
}
535
else {
536
m_strm.getBytes( data, src_stride * m_height );
537
}
538
539
}
540
else {
541
/* black and white mode */
542
if (bit_mode) {
543
if( target_channels == 1 )
544
{
545
uchar gray_palette[2] = {0, 255};
546
for( y = 0; y < m_height; y++, data += imp_stride )
547
{
548
m_strm.getBytes( src, src_stride );
549
FillGrayRow1( data, src, m_width, gray_palette );
550
}
551
} else if ( target_channels == 3 )
552
{
553
FillGrayPalette( palette, 1 , false );
554
for( y = 0; y < m_height; y++, data += imp_stride )
555
{
556
m_strm.getBytes( src, src_stride );
557
FillColorRow1( data, src, m_width, palette );
558
}
559
}
560
} else {
561
for (y = 0; y < m_height; y++, data += imp_stride )
562
{
563
m_strm.getBytes( src, src_stride );
564
565
/* endianness correction */
566
if( m_sampledepth == CV_16U && !isBigEndian() )
567
{
568
for( x = 0; x < src_elems_per_row; x++ )
569
{
570
uchar v = src[x * 2];
571
src[x * 2] = src[x * 2 + 1];
572
src[x * 2 + 1] = v;
573
}
574
}
575
576
/* scale down */
577
if( img.depth() == CV_8U && m_sampledepth == CV_16U )
578
{
579
for( x = 0; x < src_elems_per_row; x++ )
580
{
581
int v = ((ushort *)src)[x];
582
src[x] = (uchar)(v >> 8);
583
}
584
}
585
586
/* if we are only scaling up/down then we can then copy the data */
587
if (target_channels == m_channels) {
588
memcpy (data, src, imp_stride);
589
}
590
/* perform correct conversion based on format */
591
else if (fmt) {
592
funcout = false;
593
if (fmt->cvt_func)
594
funcout = fmt->cvt_func (src, data, m_width, target_channels,
595
img.depth());
596
/* fall back to default if there is no conversion function or it
597
* can't handle the specified characteristics
598
*/
599
if (!funcout)
600
basic_conversion (src, &fmt->layout, m_channels,
601
m_width, data, target_channels, img.depth());
602
603
/* default to selecting the first available channels */
604
} else {
605
basic_conversion (src, &layout, m_channels,
606
m_width, data, target_channels, img.depth());
607
}
608
}
609
}
610
}
611
612
res = true;
613
} CV_CATCH_ALL
614
{
615
}
616
617
return res;
618
}
619
620
621
//////////////////////////////////////////////////////////////////////////////////////////
622
623
PAMEncoder::PAMEncoder()
624
{
625
m_description = "Portable arbitrary format (*.pam)";
626
m_buf_supported = true;
627
}
628
629
630
PAMEncoder::~PAMEncoder()
631
{
632
}
633
634
635
ImageEncoder PAMEncoder::newEncoder() const
636
{
637
return makePtr<PAMEncoder>();
638
}
639
640
641
bool PAMEncoder::isFormatSupported( int depth ) const
642
{
643
return depth == CV_8U || depth == CV_16U;
644
}
645
646
647
bool PAMEncoder::write( const Mat& img, const std::vector<int>& params )
648
{
649
650
WLByteStream strm;
651
652
int width = img.cols, height = img.rows;
653
int stride = width*(int)img.elemSize();
654
const uchar* data = img.ptr();
655
const struct pam_format *fmt = NULL;
656
int x, y, tmp, bufsize = 256;
657
658
/* parse save file type */
659
for( size_t i = 0; i < params.size(); i += 2 )
660
if( params[i] == CV_IMWRITE_PAM_TUPLETYPE ) {
661
if ( params[i+1] > CV_IMWRITE_PAM_FORMAT_NULL &&
662
params[i+1] < (int) PAM_FORMATS_NO)
663
fmt = &formats[params[i+1]];
664
}
665
666
if( m_buf )
667
{
668
if( !strm.open(*m_buf) )
669
return false;
670
m_buf->reserve( alignSize(256 + stride*height, 256));
671
}
672
else if( !strm.open(m_filename) )
673
return false;
674
675
tmp = width * (int)img.elemSize();
676
677
if (bufsize < tmp)
678
bufsize = tmp;
679
680
AutoBuffer<char> _buffer(bufsize);
681
char* buffer = _buffer.data();
682
683
/* write header */
684
tmp = 0;
685
tmp += sprintf( buffer, "P7\n");
686
tmp += sprintf( buffer + tmp, "WIDTH %d\n", width);
687
tmp += sprintf( buffer + tmp, "HEIGHT %d\n", height);
688
tmp += sprintf( buffer + tmp, "DEPTH %d\n", img.channels());
689
tmp += sprintf( buffer + tmp, "MAXVAL %d\n", (1 << img.elemSize1()*8) - 1);
690
if (fmt)
691
tmp += sprintf( buffer + tmp, "TUPLTYPE %s\n", fmt->name );
692
sprintf( buffer + tmp, "ENDHDR\n" );
693
694
strm.putBytes( buffer, (int)strlen(buffer) );
695
/* write data */
696
if (img.depth() == CV_8U)
697
strm.putBytes( data, stride*height );
698
else if (img.depth() == CV_16U) {
699
/* fix endianness */
700
if (!isBigEndian()) {
701
for( y = 0; y < height; y++ ) {
702
memcpy( buffer, img.ptr(y), stride );
703
for( x = 0; x < stride; x += 2 )
704
{
705
uchar v = buffer[x];
706
buffer[x] = buffer[x + 1];
707
buffer[x + 1] = v;
708
}
709
strm.putBytes( buffer, stride );
710
}
711
} else
712
strm.putBytes( data, stride*height );
713
} else
714
CV_Error(Error::StsInternal, "");
715
716
strm.close();
717
return true;
718
}
719
720
}
721
722
#endif
723
724