grfmt_pam.cpp 22.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                            License Agreement
//                 For Open Source Computer Vision Library
//                         (3-clause BSD License)
//
//  Copyright (C) 2000-2016, Intel Corporation, all rights reserved.
//  Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
//  Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
//  Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
//  Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved.
//  Copyright (C) 2015-2016, Itseez Inc., all rights reserved.
//  Third party copyrights are property of their respective owners.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation
//      and/or other materials provided with the distribution.
//
//    * Neither the names of the copyright holders nor the names of the contributors
//      may be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
//  This software is provided by the copyright holders and contributors "as is" and
//  any express or implied warranties, including, but not limited to, the implied
//  warranties of merchantability and fitness for a particular purpose are disclaimed.
//  In no event shall copyright holders or contributors be liable for any direct,
//  indirect, incidental, special, exemplary, or consequential damages
//  (including, but not limited to, procurement of substitute goods or services;
//  loss of use, data, or profits; or business interruption) however caused
//  and on any theory of liability, whether in contract, strict liability,
//  or tort (including negligence or otherwise) arising in any way out of
//  the use of this software, even if advised of the possibility of such damage.
//
//M*/

49 50 51 52
#include "precomp.hpp"


#ifdef HAVE_IMGCODEC_PXM
53 54 55 56 57 58

#include <cerrno>

#include "utils.hpp"
#include "grfmt_pam.hpp"

59
namespace cv {
60

61 62 63 64
/* the PAM related fields */
#define MAX_PAM_HEADER_IDENITFIER_LENGTH 8
#define MAX_PAM_HEADER_VALUE_LENGTH 255

L
luz.paz 已提交
65
/* PAM header fields */
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
typedef enum {
    PAM_HEADER_NONE,
    PAM_HEADER_COMMENT,
    PAM_HEADER_ENDHDR,
    PAM_HEADER_HEIGHT,
    PAM_HEADER_WIDTH,
    PAM_HEADER_DEPTH,
    PAM_HEADER_MAXVAL,
    PAM_HEADER_TUPLTYPE,
} PamHeaderFieldType;

struct pam_header_field {
    PamHeaderFieldType type;
    char identifier[MAX_PAM_HEADER_IDENITFIER_LENGTH+1];
};

const static struct pam_header_field fields[] = {
    {PAM_HEADER_ENDHDR,   "ENDHDR"},
    {PAM_HEADER_HEIGHT,   "HEIGHT"},
    {PAM_HEADER_WIDTH,    "WIDTH"},
    {PAM_HEADER_DEPTH,    "DEPTH"},
    {PAM_HEADER_MAXVAL,   "MAXVAL"},
    {PAM_HEADER_TUPLTYPE, "TUPLTYPE"},
};
#define PAM_FIELDS_NO (sizeof (fields) / sizeof ((fields)[0]))

typedef bool (*cvtFunc) (void *src, void *target, int width, int target_channels,
    int target_depth);

struct channel_layout {
    uint rchan, gchan, bchan, graychan;
};

struct pam_format {
    uint fmt;
    char name[MAX_PAM_HEADER_VALUE_LENGTH+1];
    cvtFunc cvt_func;
    /* the channel layout that should be used when
     * imread_ creates a 3 channel or 1 channel image
     * used when no conversion function is available
     */
    struct channel_layout layout;
};

static bool rgb_convert (void *src, void *target, int width, int target_channels,
    int target_depth);

const static struct pam_format formats[] = {
    {CV_IMWRITE_PAM_FORMAT_NULL, "", NULL, {0, 0, 0, 0} },
    {CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE, "BLACKANDWHITE", NULL, {0, 0, 0, 0} },
    {CV_IMWRITE_PAM_FORMAT_GRAYSCALE, "GRAYSCALE", NULL, {0, 0, 0, 0} },
    {CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA, "GRAYSCALE_ALPHA", NULL, {0, 0, 0, 0} },
    {CV_IMWRITE_PAM_FORMAT_RGB, "RGB", rgb_convert, {0, 1, 2, 0} },
    {CV_IMWRITE_PAM_FORMAT_RGB_ALPHA, "RGB_ALPHA", NULL, {0, 1, 2, 0} },
};
#define PAM_FORMATS_NO (sizeof (fields) / sizeof ((fields)[0]))

/*
 * conversion functions
 */

static bool
rgb_convert (void *src, void *target, int width, int target_channels, int target_depth)
{
    bool ret = false;
    if (target_channels == 3) {
        switch (target_depth) {
            case CV_8U:
                icvCvt_RGB2BGR_8u_C3R( (uchar*) src, 0, (uchar*) target, 0,
135
                    Size(width,1) );
136 137 138 139
                ret = true;
                break;
            case CV_16U:
                icvCvt_RGB2BGR_16u_C3R( (ushort *)src, 0, (ushort *)target, 0,
140
                    Size(width,1) );
141 142 143 144 145 146 147 148 149
                ret = true;
                break;
            default:
                break;
        }
    } else if (target_channels == 1) {
        switch (target_depth) {
            case CV_8U:
                icvCvt_BGR2Gray_8u_C3C1R( (uchar*) src, 0, (uchar*) target, 0,
150
                    Size(width,1), 2 );
151 152 153 154
                ret = true;
                break;
            case CV_16U:
                icvCvt_BGRA2Gray_16u_CnC1R( (ushort *)src, 0, (ushort *)target, 0,
155
                    Size(width,1), 3, 2 );
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
                ret = true;
                break;
            default:
                break;
        }
    }
    return ret;
}

/*
 * copy functions used as a fall back for undefined formats
 * or simpler conversion options
 */

static void
basic_conversion (void *src, const struct channel_layout *layout, int src_sampe_size,
    int src_width, void *target, int target_channels, int target_depth)
{
    switch (target_depth) {
        case CV_8U:
        {
            uchar *d = (uchar *)target, *s = (uchar *)src,
                *end = ((uchar *)src) + src_width;
            switch (target_channels) {
                case 1:
                    for( ; s < end; d += 3, s += src_sampe_size )
                        d[0] = d[1] = d[2] = s[layout->graychan];
                    break;
                case 3:
                    for( ; s < end; d += 3, s += src_sampe_size ) {
                        d[0] = s[layout->bchan];
                        d[1] = s[layout->gchan];
                        d[2] = s[layout->rchan];
                    }
                    break;
                default:
192
                    CV_Error(Error::StsInternal, "");
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            }
            break;
        }
        case CV_16U:
        {
            ushort *d = (ushort *)target, *s = (ushort *)src,
                *end = ((ushort *)src) + src_width;
            switch (target_channels) {
                case 1:
                    for( ; s < end; d += 3, s += src_sampe_size )
                        d[0] = d[1] = d[2] = s[layout->graychan];
                    break;
                case 3:
                    for( ; s < end; d += 3, s += src_sampe_size ) {
                        d[0] = s[layout->bchan];
                        d[1] = s[layout->gchan];
                        d[2] = s[layout->rchan];
                    }
                    break;
                default:
213
                    CV_Error(Error::StsInternal, "");
214 215 216 217
            }
            break;
        }
        default:
218
            CV_Error(Error::StsInternal, "");
219 220 221 222
    }
}


223 224 225 226 227
static
bool ReadPAMHeaderLine(
        cv::RLByteStream& strm,
        CV_OUT PamHeaderFieldType &fieldtype,
        CV_OUT char value[MAX_PAM_HEADER_VALUE_LENGTH+1])
228
{
229 230
    int code;
    char ident[MAX_PAM_HEADER_IDENITFIER_LENGTH+1] = {};
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

    do {
        code = strm.getByte();
    } while ( isspace(code) );

    if (code == '#') {
        /* we are in a comment, eat characters until linebreak */
        do
        {
            code = strm.getByte();
        } while( code != '\n' && code != '\r' );
        fieldtype = PAM_HEADER_COMMENT;
        return true;
    } else if (code == '\n' || code == '\r' ) {
        fieldtype = PAM_HEADER_NONE;
        return true;
    }

249 250 251 252
    int ident_sz = 0;
    for (; ident_sz < MAX_PAM_HEADER_IDENITFIER_LENGTH; ident_sz++)
    {
        if (isspace(code))
253
            break;
254
        ident[ident_sz] = (char)code;
255 256
        code = strm.getByte();
    }
257 258
    CV_DbgAssert(ident_sz <= MAX_PAM_HEADER_IDENITFIER_LENGTH);
    ident[ident_sz] = 0;
259 260 261 262 263

    /* we may have filled the buffer and still have data */
    if (!isspace(code))
        return false;

264 265 266 267 268
    bool ident_found = false;
    for (uint i = 0; i < PAM_FIELDS_NO; i++)
    {
        if (0 == strncmp(fields[i].identifier, ident, std::min(ident_sz, MAX_PAM_HEADER_IDENITFIER_LENGTH) + 1))
        {
269 270
            fieldtype = fields[i].type;
            ident_found = true;
271
            break;
272 273 274 275 276 277
        }
    }

    if (!ident_found)
        return false;

278
    memset(value, 0, sizeof(char) * (MAX_PAM_HEADER_VALUE_LENGTH + 1));
279 280 281 282 283 284
    /* we may have an identifier that has no value */
    if (code == '\n' || code == '\r')
        return true;

    do {
        code = strm.getByte();
285
    } while (isspace(code));
286 287

    /* read identifier value */
288 289 290 291
    int value_sz = 0;
    for (; value_sz < MAX_PAM_HEADER_VALUE_LENGTH; value_sz++)
    {
        if (code == '\n' || code == '\r')
292
            break;
293
        value[value_sz] = (char)code;
294 295
        code = strm.getByte();
    }
296 297 298 299
    CV_DbgAssert(value_sz <= MAX_PAM_HEADER_VALUE_LENGTH);
    value[value_sz] = 0;

    int pos = value_sz;
300 301 302 303 304 305

    /* should be terminated */
    if (code != '\n' && code != '\r')
        return false;

    /* remove trailing white spaces */
306 307
    while (--pos >= 0 && isspace(value[pos]))
        value[pos] = 0;
308 309 310 311

    return true;
}

312
static int ParseInt(const char *str, int len)
313
{
314
    CV_Assert(len > 0);
315

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    int pos = 0;
    bool is_negative = false;
    if (str[0] == '-')
    {
        is_negative = true;
        pos++;
        CV_Assert(isdigit(str[pos]));
    }
    uint64_t number = 0;
    while (pos < len && isdigit(str[pos]))
    {
        char ch = str[pos];
        number = (number * 10) + (uint64_t)((int)ch - (int)'0');
        CV_Assert(number < INT_MAX);
        pos++;
    }
    if (pos < len)
        CV_Assert(str[pos] == 0);
    return (is_negative) ? -(int)number : (int)number;
335 336
}

337

338 339 340 341 342 343 344

PAMDecoder::PAMDecoder()
{
    m_offset = -1;
    m_buf_supported = true;
    bit_mode = false;
    selected_fmt = CV_IMWRITE_PAM_FORMAT_NULL;
345 346 347
    m_maxval = 0;
    m_channels = 0;
    m_sampledepth = 0;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
}


PAMDecoder::~PAMDecoder()
{
    m_strm.close();
}

size_t PAMDecoder::signatureLength() const
{
    return 3;
}

bool PAMDecoder::checkSignature( const String& signature ) const
{
    return signature.size() >= 3 && signature[0] == 'P' &&
           signature[1] == '7' &&
           isspace(signature[2]);
}

ImageDecoder PAMDecoder::newDecoder() const
{
    return makePtr<PAMDecoder>();
}

373
bool PAMDecoder::readHeader()
374 375 376 377
{
    PamHeaderFieldType fieldtype = PAM_HEADER_NONE;
    char value[MAX_PAM_HEADER_VALUE_LENGTH+1];
    int byte;
378

379 380 381 382 383 384 385
    if( !m_buf.empty() )
    {
        if( !m_strm.open(m_buf) )
            return false;
    }
    else if( !m_strm.open( m_filename ))
        return false;
386

A
Alexander Alekhin 已提交
387
    try
388 389 390
    {
        byte = m_strm.getByte();
        if( byte != 'P' )
A
Alexander Alekhin 已提交
391
            throw RBS_BAD_HEADER;
392 393 394

        byte = m_strm.getByte();
        if (byte != '7')
A
Alexander Alekhin 已提交
395
            throw RBS_BAD_HEADER;
396 397 398

        byte = m_strm.getByte();
        if (byte != '\n' && byte != '\r')
A
Alexander Alekhin 已提交
399
            throw RBS_BAD_HEADER;
400

401 402
        bool flds_endhdr = false, flds_height = false, flds_width = false, flds_depth = false, flds_maxval = false;

403 404
        do {
            if (!ReadPAMHeaderLine(m_strm, fieldtype, value))
A
Alexander Alekhin 已提交
405
                throw RBS_BAD_HEADER;
406 407
            switch (fieldtype)
            {
408 409 410 411
                case PAM_HEADER_NONE:
                case PAM_HEADER_COMMENT:
                    continue;
                case PAM_HEADER_ENDHDR:
412
                    flds_endhdr = true;
413 414
                    break;
                case PAM_HEADER_HEIGHT:
415
                    if (flds_height)
A
Alexander Alekhin 已提交
416
                        throw RBS_BAD_HEADER;
417 418
                    m_height = ParseInt(value, MAX_PAM_HEADER_VALUE_LENGTH);
                    flds_height = true;
419 420
                    break;
                case PAM_HEADER_WIDTH:
421
                    if (flds_width)
A
Alexander Alekhin 已提交
422
                        throw RBS_BAD_HEADER;
423 424
                    m_width = ParseInt(value, MAX_PAM_HEADER_VALUE_LENGTH);
                    flds_width = true;
425 426
                    break;
                case PAM_HEADER_DEPTH:
427
                    if (flds_depth)
A
Alexander Alekhin 已提交
428
                        throw RBS_BAD_HEADER;
429 430
                    m_channels = ParseInt(value, MAX_PAM_HEADER_VALUE_LENGTH);
                    flds_depth = true;
431 432
                    break;
                case PAM_HEADER_MAXVAL:
433
                    if (flds_maxval)
A
Alexander Alekhin 已提交
434
                        throw RBS_BAD_HEADER;
435
                    m_maxval = ParseInt(value, MAX_PAM_HEADER_VALUE_LENGTH);
436
                    if ( m_maxval > 65535 )
A
Alexander Alekhin 已提交
437
                        throw RBS_BAD_HEADER;
438
                    m_sampledepth = (m_maxval > 255) ? CV_16U : CV_8U;
439 440
                    if (m_maxval == 1)
                        bit_mode = true;
441
                    flds_maxval = true;
442 443
                    break;
                case PAM_HEADER_TUPLTYPE:
444 445 446 447 448 449
                {
                    bool format_found = false;
                    for (uint i=0; i<PAM_FORMATS_NO; i++)
                    {
                        if (0 == strncmp(formats[i].name, value, MAX_PAM_HEADER_VALUE_LENGTH+1))
                        {
450
                            selected_fmt = formats[i].fmt;
451 452
                            format_found = true;
                            break;
453 454
                        }
                    }
455
                    CV_Assert(format_found);
456
                    break;
457
                }
458
                default:
A
Alexander Alekhin 已提交
459
                    throw RBS_BAD_HEADER;
460 461 462
            }
        } while (fieldtype != PAM_HEADER_ENDHDR);

463 464 465 466
        if (flds_endhdr && flds_height && flds_width && flds_depth && flds_maxval)
        {
            if (selected_fmt == CV_IMWRITE_PAM_FORMAT_NULL)
            {
467 468 469 470 471 472
                if (m_channels == 1 && m_maxval == 1)
                    selected_fmt = CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE;
                else if (m_channels == 1 && m_maxval < 256)
                    selected_fmt = CV_IMWRITE_PAM_FORMAT_GRAYSCALE;
                else if (m_channels == 3 && m_maxval < 256)
                    selected_fmt = CV_IMWRITE_PAM_FORMAT_RGB;
473 474
                else
                    CV_Error(Error::StsError, "Can't determine selected_fmt (IMWRITE_PAM_FORMAT_NULL)");
475
            }
476 477
            CV_CheckDepth(m_sampledepth, m_sampledepth == CV_8U || m_sampledepth == CV_16U, "");
            CV_Check(m_channels, m_channels >= 1 && m_channels <= 4, "Unsupported number of channels");
478 479 480 481 482
            m_type = CV_MAKETYPE(m_sampledepth, m_channels);
            m_offset = m_strm.getPos();

            return true;
        }
483 484 485 486 487 488 489 490

        // failed
        m_offset = -1;
        m_width = m_height = -1;
        m_strm.close();
        return false;
    }
    catch (...)
491
    {
492 493 494 495
        m_offset = -1;
        m_width = m_height = -1;
        m_strm.close();
        throw;
496 497 498 499
    }
}


500
bool PAMDecoder::readData(Mat& img)
501 502
{
    uchar* data = img.ptr();
503
    const int target_channels = img.channels();
504
    size_t imp_stride = img.step;
505 506 507 508
    const int sample_depth = CV_ELEM_SIZE1(m_type);
    const int src_elems_per_row = m_width*m_channels;
    const int src_stride = src_elems_per_row*sample_depth;
    PaletteEntry palette[256] = {};
509
    const struct pam_format *fmt = NULL;
A
Alexander Alekhin 已提交
510
    struct channel_layout layout = { 0, 0, 0, 0 }; // normalized to 1-channel grey format
511 512 513

    /* setting buffer to max data size so scaling up is possible */
    AutoBuffer<uchar> _src(src_elems_per_row * 2);
514
    uchar* src = _src.data();
515 516 517 518 519 520 521 522 523 524 525 526

    if( m_offset < 0 || !m_strm.isOpened())
        return false;

    if (selected_fmt != CV_IMWRITE_PAM_FORMAT_NULL)
        fmt = &formats[selected_fmt];
    else {
        /* default layout handling */
        if (m_channels >= 3) {
            layout.bchan = 0;
            layout.gchan = 1;
            layout.rchan = 2;
A
Alexander Alekhin 已提交
527
        }
528 529 530 531 532 533 534
    }

    {
        m_strm.setPos( m_offset );

        /* the case where data fits the opencv matrix */
        if (m_sampledepth == img.depth() && target_channels == m_channels && !bit_mode) {
L
luz.paz 已提交
535
            /* special case for 16bit images with wrong endianness */
536 537
            if (m_sampledepth == CV_16U && !isBigEndian())
            {
538
                for (int y = 0; y < m_height; y++, data += imp_stride)
539 540
                {
                    m_strm.getBytes( src, src_stride );
541
                    for (int x = 0; x < src_elems_per_row; x++)
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                    {
                        uchar v = src[x * 2];
                        data[x * 2] = src[x * 2 + 1];
                        data[x * 2 + 1] = v;
                    }
                }
            }
            else {
                m_strm.getBytes( data, src_stride * m_height );
            }

        }
        else {
            /* black and white mode */
            if (bit_mode) {
                if( target_channels == 1 )
                {
559
                    uchar gray_palette[2] = {0, 255};
560
                    for (int y = 0; y < m_height; y++, data += imp_stride)
561 562 563 564 565 566 567
                    {
                        m_strm.getBytes( src, src_stride );
                        FillGrayRow1( data, src, m_width, gray_palette );
                    }
                } else if ( target_channels == 3 )
                {
                    FillGrayPalette( palette, 1 , false );
568
                    for (int y = 0; y < m_height; y++, data += imp_stride)
569 570 571 572 573
                    {
                        m_strm.getBytes( src, src_stride );
                        FillColorRow1( data, src, m_width, palette );
                    }
                }
574 575 576 577
                else
                {
                    CV_Error(Error::StsError, cv::format("Unsupported value of target_channels: %d", target_channels));
                }
578
            } else {
579
                for (int y = 0; y < m_height; y++, data += imp_stride)
580 581 582
                {
                    m_strm.getBytes( src, src_stride );

L
luz.paz 已提交
583
                    /* endianness correction */
584 585
                    if( m_sampledepth == CV_16U && !isBigEndian() )
                    {
586
                        for (int x = 0; x < src_elems_per_row; x++)
587 588 589 590 591 592 593 594 595 596
                        {
                            uchar v = src[x * 2];
                            src[x * 2] = src[x * 2 + 1];
                            src[x * 2 + 1] = v;
                        }
                    }

                    /* scale down */
                    if( img.depth() == CV_8U && m_sampledepth == CV_16U )
                    {
597
                        for (int x = 0; x < src_elems_per_row; x++)
598 599 600 601 602 603 604 605 606 607 608 609
                        {
                            int v = ((ushort *)src)[x];
                            src[x] = (uchar)(v >> 8);
                        }
                    }

                    /* if we are only scaling up/down then we can then copy the data */
                    if (target_channels == m_channels) {
                        memcpy (data, src, imp_stride);
                    }
                    /* perform correct conversion based on format */
                    else if (fmt) {
610
                        bool funcout = false;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
                        if (fmt->cvt_func)
                            funcout = fmt->cvt_func (src, data, m_width, target_channels,
                                img.depth());
                        /* fall back to default if there is no conversion function or it
                         * can't handle the specified characteristics
                         */
                        if (!funcout)
                            basic_conversion (src, &fmt->layout, m_channels,
                                m_width, data, target_channels, img.depth());

                    /* default to selecting the first available channels */
                    } else {
                        basic_conversion (src, &layout, m_channels,
                            m_width, data, target_channels, img.depth());
                    }
                }
            }
        }
    }
630
    return true;
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
}


//////////////////////////////////////////////////////////////////////////////////////////

PAMEncoder::PAMEncoder()
{
    m_description = "Portable arbitrary format (*.pam)";
    m_buf_supported = true;
}


PAMEncoder::~PAMEncoder()
{
}


ImageEncoder PAMEncoder::newEncoder() const
{
    return makePtr<PAMEncoder>();
}


bool PAMEncoder::isFormatSupported( int depth ) const
{
    return depth == CV_8U || depth == CV_16U;
}


bool PAMEncoder::write( const Mat& img, const std::vector<int>& params )
{

    WLByteStream strm;

    int width = img.cols, height = img.rows;
    int stride = width*(int)img.elemSize();
    const uchar* data = img.ptr();
    const struct pam_format *fmt = NULL;
    int x, y, tmp, bufsize = 256;

    /* parse save file type */
    for( size_t i = 0; i < params.size(); i += 2 )
        if( params[i] == CV_IMWRITE_PAM_TUPLETYPE ) {
            if ( params[i+1] > CV_IMWRITE_PAM_FORMAT_NULL &&
                 params[i+1] < (int) PAM_FORMATS_NO)
                fmt = &formats[params[i+1]];
        }

    if( m_buf )
    {
        if( !strm.open(*m_buf) )
            return false;
        m_buf->reserve( alignSize(256 + stride*height, 256));
    }
    else if( !strm.open(m_filename) )
        return false;

    tmp = width * (int)img.elemSize();

    if (bufsize < tmp)
        bufsize = tmp;

    AutoBuffer<char> _buffer(bufsize);
694
    char* buffer = _buffer.data();
695 696 697 698 699 700 701 702 703 704

    /* write header */
    tmp = 0;
    tmp += sprintf( buffer, "P7\n");
    tmp += sprintf( buffer + tmp, "WIDTH %d\n", width);
    tmp += sprintf( buffer + tmp, "HEIGHT %d\n", height);
    tmp += sprintf( buffer + tmp, "DEPTH %d\n", img.channels());
    tmp += sprintf( buffer + tmp, "MAXVAL %d\n", (1 << img.elemSize1()*8) - 1);
    if (fmt)
        tmp += sprintf( buffer + tmp, "TUPLTYPE %s\n", fmt->name );
705
    sprintf( buffer + tmp, "ENDHDR\n" );
706 707 708 709 710 711

    strm.putBytes( buffer, (int)strlen(buffer) );
    /* write data */
    if (img.depth() == CV_8U)
        strm.putBytes( data, stride*height );
    else if (img.depth() == CV_16U) {
L
luz.paz 已提交
712
        /* fix endianness */
713 714 715 716 717 718 719 720 721 722 723 724 725 726
        if (!isBigEndian()) {
            for( y = 0; y < height; y++ ) {
                memcpy( buffer, img.ptr(y), stride );
                for( x = 0; x < stride; x += 2 )
                {
                    uchar v = buffer[x];
                    buffer[x] = buffer[x + 1];
                    buffer[x + 1] = v;
                }
                strm.putBytes( buffer, stride );
            }
        } else
            strm.putBytes( data, stride*height );
    } else
727
        CV_Error(Error::StsInternal, "");
728 729 730 731 732 733

    strm.close();
    return true;
}

}
734 735

#endif