1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "precomp.hpp"
45 #include "grfmt_pxm.hpp"
51 ///////////////////////// P?M reader //////////////////////////////
53 static int ReadNumber(RLByteStream& strm, int maxdigits = 0)
59 code = strm.getByte();
61 while (!isdigit(code))
67 code = strm.getByte();
69 while (code != '\n' && code != '\r');
70 code = strm.getByte();
72 else if (isspace(code))
75 code = strm.getByte();
80 CV_Error_(CV_StsError, ("PXM: Unexpected code in ReadNumber(): 0x%x (%d)", code, code));
82 code = strm.getByte();
89 val = val*10 + (code - '0');
90 CV_Assert(val <= INT_MAX && "PXM: ReadNumber(): result is too large");
92 if (maxdigits != 0 && digits >= maxdigits) break;
93 code = strm.getByte();
95 while (isdigit(code));
101 PxMDecoder::PxMDecoder()
104 m_buf_supported = true;
108 PxMDecoder::~PxMDecoder()
113 size_t PxMDecoder::signatureLength() const
118 bool PxMDecoder::checkSignature( const string& signature ) const
120 return signature.size() >= 3 && signature[0] == 'P' &&
121 '1' <= signature[1] && signature[1] <= '6' &&
122 isspace(signature[2]);
125 ImageDecoder PxMDecoder::newDecoder() const
127 return new PxMDecoder;
130 void PxMDecoder::close()
136 bool PxMDecoder::readHeader()
142 if( !m_strm.open(m_buf) )
145 else if( !m_strm.open( m_filename ))
150 int code = m_strm.getByte();
152 throw RBS_BAD_HEADER;
154 code = m_strm.getByte();
157 case '1': case '4': m_bpp = 1; break;
158 case '2': case '5': m_bpp = 8; break;
159 case '3': case '6': m_bpp = 24; break;
160 default: throw RBS_BAD_HEADER;
163 m_binary = code >= '4';
164 m_type = m_bpp > 8 ? CV_8UC3 : CV_8UC1;
166 m_width = ReadNumber(m_strm);
167 m_height = ReadNumber(m_strm);
169 m_maxval = m_bpp == 1 ? 1 : ReadNumber(m_strm);
170 if( m_maxval > 65535 )
171 throw RBS_BAD_HEADER;
173 //if( m_maxval > 255 ) m_binary = false; nonsense
175 m_type = CV_MAKETYPE(CV_16U, CV_MAT_CN(m_type));
177 if( m_width > 0 && m_height > 0 && m_maxval > 0 && m_maxval < (1 << 16))
179 m_offset = m_strm.getPos();
183 catch (const cv::Exception&)
189 std::cerr << "PXM::readHeader(): unknown C++ exception" << std::endl << std::flush;
196 m_width = m_height = -1;
203 bool PxMDecoder::readData( Mat& img )
205 int color = img.channels() > 1;
206 uchar* data = img.data;
207 int step = (int)img.step;
208 PaletteEntry palette[256];
210 const int bit_depth = CV_ELEM_SIZE1(m_type)*8;
211 const int src_pitch = (m_width*m_bpp*(bit_depth/8) + 7) / 8;
213 int nch = CV_MAT_CN(m_type);
214 int width3 = m_width*nch;
216 if( m_offset < 0 || !m_strm.isOpened())
219 uchar gray_palette[256] = {0};
221 // create LUT for converting colors
224 CV_Assert(m_maxval < 256);
226 for (int i = 0; i <= m_maxval; i++)
227 gray_palette[i] = (uchar)((i*255/m_maxval)^(m_bpp == 1 ? 255 : 0));
229 FillGrayPalette( palette, m_bpp==1 ? 1 : 8 , m_bpp == 1 );
234 m_strm.setPos( m_offset );
238 ////////////////////////// 1 BPP /////////////////////////
240 CV_Assert(CV_MAT_DEPTH(m_type) == CV_8U);
243 AutoBuffer<uchar> _src(m_width);
246 for (int y = 0; y < m_height; y++, data += step)
248 for (int x = 0; x < m_width; x++)
249 src[x] = ReadNumber(m_strm, 1) != 0;
252 FillColorRow8( data, src, m_width, palette );
254 FillGrayRow8( data, src, m_width, gray_palette );
259 AutoBuffer<uchar> _src(src_pitch);
262 for (int y = 0; y < m_height; y++, data += step)
264 m_strm.getBytes( src, src_pitch );
267 FillColorRow1( data, src, m_width, palette );
269 FillGrayRow1( data, src, m_width, gray_palette );
275 ////////////////////////// 8 BPP /////////////////////////
279 AutoBuffer<uchar> _src(std::max<size_t>(width3*2, src_pitch));
282 for (int y = 0; y < m_height; y++, data += step)
286 for (int x = 0; x < width3; x++)
288 int code = ReadNumber( m_strm, INT_MAX );
289 if( (unsigned)code > (unsigned)m_maxval ) code = m_maxval;
291 src[x] = gray_palette[code];
293 ((ushort *)src)[x] = (ushort)code;
298 m_strm.getBytes( src, src_pitch );
299 if( bit_depth == 16 && !isBigEndian() )
301 for (int x = 0; x < width3; x++)
303 uchar v = src[x * 2];
304 src[x * 2] = src[x * 2 + 1];
310 if( img.depth() == CV_8U && bit_depth == 16 )
312 for (int x = 0; x < width3; x++)
314 int v = ((ushort *)src)[x];
315 src[x] = (uchar)(v >> 8);
319 if( m_bpp == 8 ) // image has one channel
323 if( img.depth() == CV_8U ) {
324 uchar *d = data, *s = src, *end = src + m_width;
325 for( ; s < end; d += 3, s++)
326 d[0] = d[1] = d[2] = *s;
328 ushort *d = (ushort *)data, *s = (ushort *)src, *end = ((ushort *)src) + m_width;
329 for( ; s < end; s++, d += 3)
330 d[0] = d[1] = d[2] = *s;
334 memcpy( data, src, m_width*(bit_depth/8) );
340 if( img.depth() == CV_8U )
341 icvCvt_RGB2BGR_8u_C3R( src, 0, data, 0, cvSize(m_width,1) );
343 icvCvt_RGB2BGR_16u_C3R( (ushort *)src, 0, (ushort *)data, 0, cvSize(m_width,1) );
345 else if( img.depth() == CV_8U )
346 icvCvt_BGR2Gray_8u_C3C1R( src, 0, data, 0, cvSize(m_width,1), 2 );
348 icvCvt_BGRA2Gray_16u_CnC1R( (ushort *)src, 0, (ushort *)data, 0, cvSize(m_width,1), 3, 2 );
355 CV_Error(CV_StsError, "m_bpp is not supported");
358 catch (const cv::Exception&)
364 std::cerr << "PXM::readData(): unknown exception" << std::endl << std::flush;
372 //////////////////////////////////////////////////////////////////////////////////////////
374 PxMEncoder::PxMEncoder()
376 m_description = "Portable image format (*.pbm;*.pgm;*.ppm;*.pxm;*.pnm)";
377 m_buf_supported = true;
381 PxMEncoder::~PxMEncoder()
386 ImageEncoder PxMEncoder::newEncoder() const
388 return new PxMEncoder;
392 bool PxMEncoder::isFormatSupported( int depth ) const
394 return depth == CV_8U || depth == CV_16U;
398 bool PxMEncoder::write( const Mat& img, const vector<int>& params )
400 bool isBinary = true;
402 int width = img.cols, height = img.rows;
403 int _channels = img.channels(), depth = (int)img.elemSize1()*8;
404 int channels = _channels > 1 ? 3 : 1;
405 int fileStep = width*(int)img.elemSize();
408 for( size_t i = 0; i < params.size(); i += 2 )
409 if( params[i] == CV_IMWRITE_PXM_BINARY )
410 isBinary = params[i+1] != 0;
416 if( !strm.open(*m_buf) )
418 int t = CV_MAKETYPE(img.depth(), channels);
419 m_buf->reserve( alignSize(256 + (isBinary ? fileStep*height :
420 ((t == CV_8UC1 ? 4 : t == CV_8UC3 ? 4*3+2 :
421 t == CV_16UC1 ? 6 : 6*3+2)*width+1)*height), 256));
423 else if( !strm.open(m_filename) )
427 int bufferSize = 128; // buffer that should fit a header
430 lineLength = width * (int)img.elemSize();
432 lineLength = (6 * channels + (channels > 1 ? 2 : 0)) * width + 32;
434 if( bufferSize < lineLength )
435 bufferSize = lineLength;
437 AutoBuffer<char> _buffer(bufferSize);
438 char* buffer = _buffer;
441 sprintf( buffer, "P%c\n# Generated by OpenCV %s\n%d %d\n%d\n",
442 '2' + (channels > 1 ? 1 : 0) + (isBinary ? 3 : 0),
444 width, height, (1 << depth) - 1 );
446 strm.putBytes( buffer, (int)strlen(buffer) );
448 for( y = 0; y < height; y++ )
450 uchar* data = img.data + img.step*y;
456 icvCvt_BGR2RGB_8u_C3R( (uchar*)data, 0,
457 (uchar*)buffer, 0, cvSize(width,1) );
459 icvCvt_BGR2RGB_16u_C3R( (ushort*)data, 0,
460 (ushort*)buffer, 0, cvSize(width,1) );
463 // swap endianness if necessary
464 if( depth == 16 && !isBigEndian() )
467 memcpy( buffer, data, fileStep );
468 for( x = 0; x < width*channels*2; x += 2 )
471 buffer[x] = buffer[x + 1];
475 strm.putBytes( (channels > 1 || depth > 8) ? buffer : (char*)data, fileStep );
485 for( x = 0; x < width*channels; x += channels )
487 sprintf( ptr, "% 4d", data[x + 2] );
489 sprintf( ptr, "% 4d", data[x + 1] );
491 sprintf( ptr, "% 4d", data[x] );
499 for( x = 0; x < width*channels; x += channels )
501 sprintf( ptr, "% 6d", ((ushort *)data)[x + 2] );
503 sprintf( ptr, "% 6d", ((ushort *)data)[x + 1] );
505 sprintf( ptr, "% 6d", ((ushort *)data)[x] );
516 for( x = 0; x < width; x++ )
518 sprintf( ptr, "% 4d", data[x] );
524 for( x = 0; x < width; x++ )
526 sprintf( ptr, "% 6d", ((ushort *)data)[x] );
534 strm.putBytes( buffer, (int)(ptr - buffer) );