loadsave.cpp 29.4 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
/*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.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, 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:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of Intel Corporation may not 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 the Intel Corporation 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*/

//
S
Suleyman TURKMEN 已提交
43
//  Loading and saving images.
44 45 46 47
//

#include "precomp.hpp"
#include "grfmts.hpp"
48 49
#include "utils.hpp"
#include "exif.hpp"
50 51
#undef min
#undef max
52
#include <iostream>
53
#include <fstream>
54 55
#include <cerrno>
#include <opencv2/core/utils/logger.hpp>
56 57
#include <opencv2/core/utils/configuration.private.hpp>

58 59 60 61

/****************************************************************************************\
*                                      Image Codecs                                      *
\****************************************************************************************/
62 63 64

namespace cv {

65 66 67 68
static const size_t CV_IO_MAX_IMAGE_PARAMS = cv::utils::getConfigurationParameterSizeT("OPENCV_IO_MAX_IMAGE_PARAMS", 50);
static const size_t CV_IO_MAX_IMAGE_WIDTH = utils::getConfigurationParameterSizeT("OPENCV_IO_MAX_IMAGE_WIDTH", 1 << 20);
static const size_t CV_IO_MAX_IMAGE_HEIGHT = utils::getConfigurationParameterSizeT("OPENCV_IO_MAX_IMAGE_HEIGHT", 1 << 20);
static const size_t CV_IO_MAX_IMAGE_PIXELS = utils::getConfigurationParameterSizeT("OPENCV_IO_MAX_IMAGE_PIXELS", 1 << 30);
69 70 71 72

static Size validateInputImageSize(const Size& size)
{
    CV_Assert(size.width > 0);
73
    CV_Assert(static_cast<size_t>(size.width) <= CV_IO_MAX_IMAGE_WIDTH);
74
    CV_Assert(size.height > 0);
75
    CV_Assert(static_cast<size_t>(size.height) <= CV_IO_MAX_IMAGE_HEIGHT);
76 77 78 79 80 81
    uint64 pixels = (uint64)size.width * (uint64)size.height;
    CV_Assert(pixels <= CV_IO_MAX_IMAGE_PIXELS);
    return size;
}


82 83 84 85 86 87 88 89 90 91 92 93 94
namespace {

class ByteStreamBuffer: public std::streambuf
{
public:
    ByteStreamBuffer(char* base, size_t length)
    {
        setg(base, base, base + length);
    }

protected:
    virtual pos_type seekoff( off_type offset,
                              std::ios_base::seekdir dir,
95
                              std::ios_base::openmode ) CV_OVERRIDE
96
    {
B
Brian Armstrong 已提交
97
        char* whence = eback();
98 99
        if (dir == std::ios_base::cur)
        {
B
Brian Armstrong 已提交
100
            whence = gptr();
101 102 103
        }
        else if (dir == std::ios_base::end)
        {
B
Brian Armstrong 已提交
104
            whence = egptr();
105
        }
B
Brian Armstrong 已提交
106
        char* to = whence + offset;
107 108

        // check limits
B
Brian Armstrong 已提交
109
        if (to >= eback() && to <= egptr())
110
        {
B
Brian Armstrong 已提交
111
            setg(eback(), to, egptr());
112 113 114 115 116 117 118 119 120
            return gptr() - eback();
        }

        return -1;
    }
};

}

121 122 123 124 125
/**
 * @struct ImageCodecInitializer
 *
 * Container which stores the registered codecs to be used by OpenCV
*/
126 127
struct ImageCodecInitializer
{
128 129 130
    /**
     * Default Constructor for the ImageCodeInitializer
    */
131 132
    ImageCodecInitializer()
    {
133
        /// BMP Support
R
Roman Donchenko 已提交
134 135
        decoders.push_back( makePtr<BmpDecoder>() );
        encoders.push_back( makePtr<BmpEncoder>() );
136

137
    #ifdef HAVE_IMGCODEC_HDR
138 139
        decoders.push_back( makePtr<HdrDecoder>() );
        encoders.push_back( makePtr<HdrEncoder>() );
140
    #endif
141
    #ifdef HAVE_JPEG
R
Roman Donchenko 已提交
142 143
        decoders.push_back( makePtr<JpegDecoder>() );
        encoders.push_back( makePtr<JpegEncoder>() );
144 145
    #endif
    #ifdef HAVE_WEBP
R
Roman Donchenko 已提交
146 147
        decoders.push_back( makePtr<WebPDecoder>() );
        encoders.push_back( makePtr<WebPEncoder>() );
148
    #endif
149
    #ifdef HAVE_IMGCODEC_SUNRASTER
R
Roman Donchenko 已提交
150 151
        decoders.push_back( makePtr<SunRasterDecoder>() );
        encoders.push_back( makePtr<SunRasterEncoder>() );
152 153
    #endif
    #ifdef HAVE_IMGCODEC_PXM
R
Roman Donchenko 已提交
154
        decoders.push_back( makePtr<PxMDecoder>() );
155 156 157 158
        encoders.push_back( makePtr<PxMEncoder>(PXM_TYPE_AUTO) );
        encoders.push_back( makePtr<PxMEncoder>(PXM_TYPE_PBM) );
        encoders.push_back( makePtr<PxMEncoder>(PXM_TYPE_PGM) );
        encoders.push_back( makePtr<PxMEncoder>(PXM_TYPE_PPM) );
159 160 161
        decoders.push_back( makePtr<PAMDecoder>() );
        encoders.push_back( makePtr<PAMEncoder>() );
    #endif
P
pasbi 已提交
162 163 164 165
    #ifdef HAVE_IMGCODEC_PFM
        decoders.push_back( makePtr<PFMDecoder>() );
        encoders.push_back( makePtr<PFMEncoder>() );
    #endif
166
    #ifdef HAVE_TIFF
R
Roman Donchenko 已提交
167 168
        decoders.push_back( makePtr<TiffDecoder>() );
        encoders.push_back( makePtr<TiffEncoder>() );
169
    #endif
170
    #ifdef HAVE_PNG
R
Roman Donchenko 已提交
171 172
        decoders.push_back( makePtr<PngDecoder>() );
        encoders.push_back( makePtr<PngEncoder>() );
173
    #endif
174 175 176
    #ifdef HAVE_GDCM
        decoders.push_back( makePtr<DICOMDecoder>() );
    #endif
177
    #ifdef HAVE_JASPER
R
Roman Donchenko 已提交
178 179
        decoders.push_back( makePtr<Jpeg2KDecoder>() );
        encoders.push_back( makePtr<Jpeg2KEncoder>() );
180
    #endif
181
    #ifdef HAVE_OPENJPEG
182 183
        decoders.push_back( makePtr<Jpeg2KJP2OpjDecoder>() );
        decoders.push_back( makePtr<Jpeg2KJ2KOpjDecoder>() );
184 185
        encoders.push_back( makePtr<Jpeg2KOpjEncoder>() );
    #endif
186
    #ifdef HAVE_OPENEXR
R
Roman Donchenko 已提交
187 188
        decoders.push_back( makePtr<ExrDecoder>() );
        encoders.push_back( makePtr<ExrEncoder>() );
189
    #endif
190 191 192 193 194

    #ifdef HAVE_GDAL
        /// Attach the GDAL Decoder
        decoders.push_back( makePtr<GdalDecoder>() );
    #endif/*HAVE_GDAL*/
195 196
    }

197 198
    std::vector<ImageDecoder> decoders;
    std::vector<ImageEncoder> encoders;
199 200
};

201 202 203 204 205 206 207 208 209 210 211 212 213
static
ImageCodecInitializer& getCodecs()
{
#ifdef CV_CXX11
    static ImageCodecInitializer g_codecs;
    return g_codecs;
#else
    // C++98 doesn't guarantee correctness of multi-threaded initialization of static global variables
    // (memory leak here is not critical, use C++11 to avoid that)
    static ImageCodecInitializer* g_codecs = new ImageCodecInitializer();
    return *g_codecs;
#endif
}
214

215 216 217 218 219 220 221 222 223
/**
 * Find the decoders
 *
 * @param[in] filename File to search
 *
 * @return Image decoder to parse image file.
*/
static ImageDecoder findDecoder( const String& filename ) {

224
    size_t i, maxlen = 0;
225 226

    /// iterate through list of registered codecs
227
    ImageCodecInitializer& codecs = getCodecs();
228
    for( i = 0; i < codecs.decoders.size(); i++ )
229
    {
230
        size_t len = codecs.decoders[i]->signatureLength();
231 232 233
        maxlen = std::max(maxlen, len);
    }

234
    /// Open the file
235
    FILE* f= fopen( filename.c_str(), "rb" );
236 237

    /// in the event of a failure, return an empty image decoder
N
nickjackolson 已提交
238 239
    if( !f ) {
        CV_LOG_WARNING(NULL, "imread_('" << filename << "'): can't open/read file: check file path/integrity");
240
        return ImageDecoder();
N
nickjackolson 已提交
241
    }
242 243

    // read the file signature
244
    String signature(maxlen, ' ');
245
    maxlen = fread( (void*)signature.c_str(), 1, maxlen, f );
246 247 248
    fclose(f);
    signature = signature.substr(0, maxlen);

249
    /// compare signature against all decoders
250
    for( i = 0; i < codecs.decoders.size(); i++ )
251
    {
252 253
        if( codecs.decoders[i]->checkSignature(signature) )
            return codecs.decoders[i]->newDecoder();
254 255
    }

256
    /// If no decoder was found, return base type
257 258 259
    return ImageDecoder();
}

260
static ImageDecoder findDecoder( const Mat& buf )
261 262 263 264 265 266
{
    size_t i, maxlen = 0;

    if( buf.rows*buf.cols < 1 || !buf.isContinuous() )
        return ImageDecoder();

267
    ImageCodecInitializer& codecs = getCodecs();
268
    for( i = 0; i < codecs.decoders.size(); i++ )
269
    {
270
        size_t len = codecs.decoders[i]->signatureLength();
271 272 273
        maxlen = std::max(maxlen, len);
    }

274
    String signature(maxlen, ' ');
275 276
    size_t bufSize = buf.rows*buf.cols*buf.elemSize();
    maxlen = std::min(maxlen, bufSize);
277
    memcpy( (void*)signature.c_str(), buf.data, maxlen );
278

279
    for( i = 0; i < codecs.decoders.size(); i++ )
280
    {
281 282
        if( codecs.decoders[i]->checkSignature(signature) )
            return codecs.decoders[i]->newDecoder();
283 284 285 286 287
    }

    return ImageDecoder();
}

288
static ImageEncoder findEncoder( const String& _ext )
289 290 291 292 293 294 295 296
{
    if( _ext.size() <= 1 )
        return ImageEncoder();

    const char* ext = strrchr( _ext.c_str(), '.' );
    if( !ext )
        return ImageEncoder();
    int len = 0;
J
Julien Nabet 已提交
297
    for( ext++; len < 128 && isalnum(ext[len]); len++ )
298 299
        ;

300
    ImageCodecInitializer& codecs = getCodecs();
301
    for( size_t i = 0; i < codecs.encoders.size(); i++ )
302
    {
303
        String description = codecs.encoders[i]->getDescription();
304 305 306 307 308 309 310 311
        const char* descr = strchr( description.c_str(), '(' );

        while( descr )
        {
            descr = strchr( descr + 1, '.' );
            if( !descr )
                break;
            int j = 0;
J
Julien Nabet 已提交
312
            for( descr++; j < len && isalnum(descr[j]) ; j++ )
313 314 315 316 317 318 319
            {
                int c1 = tolower(ext[j]);
                int c2 = tolower(descr[j]);
                if( c1 != c2 )
                    break;
            }
            if( j == len && !isalnum(descr[j]))
320
                return codecs.encoders[i]->newEncoder();
321 322 323 324 325 326 327
            descr += j;
        }
    }

    return ImageEncoder();
}

328

329
static void ExifTransform(int orientation, Mat& img)
A
Arkadiusz Raj 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
{
    switch( orientation )
    {
        case    IMAGE_ORIENTATION_TL: //0th row == visual top, 0th column == visual left-hand side
            //do nothing, the image already has proper orientation
            break;
        case    IMAGE_ORIENTATION_TR: //0th row == visual top, 0th column == visual right-hand side
            flip(img, img, 1); //flip horizontally
            break;
        case    IMAGE_ORIENTATION_BR: //0th row == visual bottom, 0th column == visual right-hand side
            flip(img, img, -1);//flip both horizontally and vertically
            break;
        case    IMAGE_ORIENTATION_BL: //0th row == visual bottom, 0th column == visual left-hand side
            flip(img, img, 0); //flip vertically
            break;
        case    IMAGE_ORIENTATION_LT: //0th row == visual left-hand side, 0th column == visual top
            transpose(img, img);
            break;
        case    IMAGE_ORIENTATION_RT: //0th row == visual right-hand side, 0th column == visual top
            transpose(img, img);
            flip(img, img, 1); //flip horizontally
            break;
        case    IMAGE_ORIENTATION_RB: //0th row == visual right-hand side, 0th column == visual bottom
            transpose(img, img);
            flip(img, img, -1); //flip both horizontally and vertically
            break;
        case    IMAGE_ORIENTATION_LB: //0th row == visual left-hand side, 0th column == visual bottom
            transpose(img, img);
            flip(img, img, 0); //flip vertically
            break;
        default:
            //by default the image read has normal (JPEG_ORIENTATION_TL) orientation
            break;
    }
}
365

366
static void ApplyExifOrientation(ExifEntry_t orientationTag, Mat& img)
367 368 369
{
    int orientation = IMAGE_ORIENTATION_TL;

370
    if (orientationTag.tag != INVALID_TAG)
371
    {
372 373
        orientation = orientationTag.field_u16; //orientation is unsigned short, so check field_u16
        ExifTransform(orientation, img);
374 375 376
    }
}

377 378 379 380 381 382 383 384
/**
 * Read an image into memory and return the information
 *
 * @param[in] filename File to load
 * @param[in] flags Flags
 * @param[in] mat Reference to C++ Mat object (If LOAD_MAT)
 *
*/
385 386
static bool
imread_( const String& filename, int flags, Mat& mat )
387
{
388 389 390 391
    /// Search for the relevant decoder to handle the imagery
    ImageDecoder decoder;

#ifdef HAVE_GDAL
M
Maksim Shabunin 已提交
392
    if(flags != IMREAD_UNCHANGED && (flags & IMREAD_LOAD_GDAL) == IMREAD_LOAD_GDAL ){
393 394 395
        decoder = GdalDecoder().newDecoder();
    }else{
#endif
396
        decoder = findDecoder( filename );
397 398 399 400 401 402
#ifdef HAVE_GDAL
    }
#endif

    /// if no decoder was found, return nothing.
    if( !decoder ){
403
        return 0;
404 405
    }

406 407 408
    int scale_denom = 1;
    if( flags > IMREAD_LOAD_GDAL )
    {
409 410 411 412 413 414
        if( flags & IMREAD_REDUCED_GRAYSCALE_2 )
            scale_denom = 2;
        else if( flags & IMREAD_REDUCED_GRAYSCALE_4 )
            scale_denom = 4;
        else if( flags & IMREAD_REDUCED_GRAYSCALE_8 )
            scale_denom = 8;
415 416
    }

S
Suleyman TURKMEN 已提交
417 418 419
    /// set the scale_denom in the driver
    decoder->setScale( scale_denom );

420
    /// set the filename in the driver
421
    decoder->setSource( filename );
422

A
Alexander Alekhin 已提交
423
    try
424 425 426 427 428
    {
        // read the header to make sure it succeeds
        if( !decoder->readHeader() )
            return 0;
    }
A
Alexander Alekhin 已提交
429
    catch (const cv::Exception& e)
430 431
    {
        std::cerr << "imread_('" << filename << "'): can't read header: " << e.what() << std::endl << std::flush;
432
        return 0;
433
    }
A
Alexander Alekhin 已提交
434
    catch (...)
435 436 437 438 439
    {
        std::cerr << "imread_('" << filename << "'): can't read header: unknown exception" << std::endl << std::flush;
        return 0;
    }

440 441

    // established the required input image size
442
    Size size = validateInputImageSize(Size(decoder->width(), decoder->height()));
443

444
    // grab the decoded type
445
    int type = decoder->type();
446
    if( (flags & IMREAD_LOAD_GDAL) != IMREAD_LOAD_GDAL && flags != IMREAD_UNCHANGED )
447
    {
S
Suleyman TURKMEN 已提交
448
        if( (flags & IMREAD_ANYDEPTH) == 0 )
449 450
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

S
Suleyman TURKMEN 已提交
451 452
        if( (flags & IMREAD_COLOR) != 0 ||
           ((flags & IMREAD_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
453 454 455 456 457
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

458
    mat.create( size.height, size.width, type );
459

460
    // read the image data
461
    bool success = false;
A
Alexander Alekhin 已提交
462
    try
463
    {
464
        if (decoder->readData(mat))
465 466
            success = true;
    }
A
Alexander Alekhin 已提交
467
    catch (const cv::Exception& e)
468 469 470
    {
        std::cerr << "imread_('" << filename << "'): can't read data: " << e.what() << std::endl << std::flush;
    }
A
Alexander Alekhin 已提交
471
    catch (...)
472 473 474 475
    {
        std::cerr << "imread_('" << filename << "'): can't read data: unknown exception" << std::endl << std::flush;
    }
    if (!success)
476
    {
477 478
        mat.release();
        return false;
479 480
    }

481
    if( decoder->setScale( scale_denom ) > 1 ) // if decoder is JpegDecoder then decoder->setScale always returns 1
S
Suleyman TURKMEN 已提交
482
    {
483
        resize( mat, mat, Size( size.width / scale_denom, size.height / scale_denom ), 0, 0, INTER_LINEAR_EXACT);
S
Suleyman TURKMEN 已提交
484 485
    }

486
    /// optionally rotate the data if EXIF orientation flag says so
487
    if (!mat.empty() && (flags & IMREAD_IGNORE_ORIENTATION) == 0 && flags != IMREAD_UNCHANGED )
488
    {
489
        ApplyExifOrientation(decoder->getExifTag(ORIENTATION), mat);
490 491
    }

492
    return true;
493 494
}

495 496

static bool
497
imreadmulti_(const String& filename, int flags, std::vector<Mat>& mats, int start, int count)
498 499 500 501
{
    /// Search for the relevant decoder to handle the imagery
    ImageDecoder decoder;

502 503
    CV_CheckGE(start, 0, "Start index cannont be < 0");

504
#ifdef HAVE_GDAL
505
    if (flags != IMREAD_UNCHANGED && (flags & IMREAD_LOAD_GDAL) == IMREAD_LOAD_GDAL) {
506 507
        decoder = GdalDecoder().newDecoder();
    }
508
    else {
509 510 511 512 513 514 515
#endif
        decoder = findDecoder(filename);
#ifdef HAVE_GDAL
    }
#endif

    /// if no decoder was found, return nothing.
516
    if (!decoder) {
517 518 519
        return 0;
    }

520 521 522 523
    if (count < 0) {
        count = std::numeric_limits<int>::max();
    }

524 525 526 527
    /// set the filename in the driver
    decoder->setSource(filename);

    // read the header to make sure it succeeds
A
Alexander Alekhin 已提交
528
    try
529 530
    {
        // read the header to make sure it succeeds
531
        if (!decoder->readHeader())
532 533
            return 0;
    }
A
Alexander Alekhin 已提交
534
    catch (const cv::Exception& e)
535 536
    {
        std::cerr << "imreadmulti_('" << filename << "'): can't read header: " << e.what() << std::endl << std::flush;
537
        return 0;
538
    }
A
Alexander Alekhin 已提交
539
    catch (...)
540 541 542 543
    {
        std::cerr << "imreadmulti_('" << filename << "'): can't read header: unknown exception" << std::endl << std::flush;
        return 0;
    }
544

545 546 547 548 549 550 551 552 553 554 555 556
    int current = start;

    while (current > 0)
    {
        if (!decoder->nextPage())
        {
            return false;
        }
        --current;
    }

    while (current < count)
557 558 559
    {
        // grab the decoded type
        int type = decoder->type();
560
        if ((flags & IMREAD_LOAD_GDAL) != IMREAD_LOAD_GDAL && flags != IMREAD_UNCHANGED)
561
        {
S
Suleyman TURKMEN 已提交
562
            if ((flags & IMREAD_ANYDEPTH) == 0)
563 564 565
                type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

            if ((flags & CV_LOAD_IMAGE_COLOR) != 0 ||
S
Suleyman TURKMEN 已提交
566
                ((flags & IMREAD_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1))
567 568 569 570 571
                type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
            else
                type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
        }

572 573 574
        // established the required input image size
        Size size = validateInputImageSize(Size(decoder->width(), decoder->height()));

575
        // read the image data
576 577
        Mat mat(size.height, size.width, type);
        bool success = false;
A
Alexander Alekhin 已提交
578
        try
579
        {
580 581 582
            if (decoder->readData(mat))
                success = true;
        }
A
Alexander Alekhin 已提交
583
        catch (const cv::Exception& e)
584 585 586
        {
            std::cerr << "imreadmulti_('" << filename << "'): can't read data: " << e.what() << std::endl << std::flush;
        }
A
Alexander Alekhin 已提交
587
        catch (...)
588 589 590 591
        {
            std::cerr << "imreadmulti_('" << filename << "'): can't read data: unknown exception" << std::endl << std::flush;
        }
        if (!success)
592
            break;
593 594

        // optionally rotate the data if EXIF' orientation flag says so
595
        if ((flags & IMREAD_IGNORE_ORIENTATION) == 0 && flags != IMREAD_UNCHANGED)
596
        {
597
            ApplyExifOrientation(decoder->getExifTag(ORIENTATION), mat);
598 599 600 601 602 603 604
        }

        mats.push_back(mat);
        if (!decoder->nextPage())
        {
            break;
        }
605
        ++current;
606 607 608 609 610
    }

    return !mats.empty();
}

611 612 613 614 615 616 617 618
/**
 * Read an image
 *
 *  This function merely calls the actual implementation above and returns itself.
 *
 * @param[in] filename File to load
 * @param[in] flags Flags you wish to set.
*/
619
Mat imread( const String& filename, int flags )
620
{
621 622
    CV_TRACE_FUNCTION();

623
    /// create the basic container
624
    Mat img;
625 626

    /// load the data
627
    imread_( filename, flags, img );
628 629

    /// return a reference to the data
630 631 632
    return img;
}

633 634 635 636 637 638 639 640 641 642 643 644
/**
* Read a multi-page image
*
*  This function merely calls the actual implementation above and returns itself.
*
* @param[in] filename File to load
* @param[in] mats Reference to C++ vector<Mat> object to hold the images
* @param[in] flags Flags you wish to set.
*
*/
bool imreadmulti(const String& filename, std::vector<Mat>& mats, int flags)
{
645 646
    CV_TRACE_FUNCTION();

647
    return imreadmulti_(filename, flags, mats, 0, -1);
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 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

bool imreadmulti(const String& filename, std::vector<Mat>& mats, int start, int count, int flags)
{
    CV_TRACE_FUNCTION();

    return imreadmulti_(filename, flags, mats, start, count);
}

static
size_t imcount_(const String& filename, int flags)
{
    /// Search for the relevant decoder to handle the imagery
    ImageDecoder decoder;

#ifdef HAVE_GDAL
    if (flags != IMREAD_UNCHANGED && (flags & IMREAD_LOAD_GDAL) == IMREAD_LOAD_GDAL) {
        decoder = GdalDecoder().newDecoder();
    }
    else {
#else
        CV_UNUSED(flags);
#endif
        decoder = findDecoder(filename);
#ifdef HAVE_GDAL
    }
#endif

    /// if no decoder was found, return nothing.
    if (!decoder) {
        return 0;
    }

    /// set the filename in the driver
    decoder->setSource(filename);

    // read the header to make sure it succeeds
    try
    {
        // read the header to make sure it succeeds
        if (!decoder->readHeader())
            return 0;
    }
    catch (const cv::Exception& e)
    {
        std::cerr << "imcount_('" << filename << "'): can't read header: " << e.what() << std::endl << std::flush;
        return 0;
    }
    catch (...)
    {
        std::cerr << "imcount_('" << filename << "'): can't read header: unknown exception" << std::endl << std::flush;
        return 0;
    }

    size_t result = 1;


    while (decoder->nextPage())
    {
        ++result;
    }

    return result;
}

size_t imcount(const String& filename, int flags)
{
    CV_TRACE_FUNCTION();

    return imcount_(filename, flags);
}


722
static bool imwrite_( const String& filename, const std::vector<Mat>& img_vec,
723
                      const std::vector<int>& params, bool flipv )
724
{
725 726
    bool isMultiImg = img_vec.size() > 1;
    std::vector<Mat> write_vec;
727 728

    ImageEncoder encoder = findEncoder( filename );
R
Roman Donchenko 已提交
729
    if( !encoder )
730
        CV_Error( Error::StsError, "could not find a writer for the specified extension" );
731

732
    for (size_t page = 0; page < img_vec.size(); page++)
733
    {
734
        Mat image = img_vec[page];
735 736
        CV_Assert(!image.empty());

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        CV_Assert( image.channels() == 1 || image.channels() == 3 || image.channels() == 4 );

        Mat temp;
        if( !encoder->isFormatSupported(image.depth()) )
        {
            CV_Assert( encoder->isFormatSupported(CV_8U) );
            image.convertTo( temp, CV_8U );
            image = temp;
        }

        if( flipv )
        {
            flip(image, temp, 0);
            image = temp;
        }

        write_vec.push_back(image);
754 755 756
    }

    encoder->setDestination( filename );
757
    CV_Assert(params.size() <= CV_IO_MAX_IMAGE_PARAMS*2);
758 759 760 761 762 763 764
    bool code = false;
    try
    {
        if (!isMultiImg)
            code = encoder->write( write_vec[0], params );
        else
            code = encoder->writemulti( write_vec, params ); //to be implemented
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

        if (!code)
        {
            FILE* f = fopen( filename.c_str(), "wb" );
            if ( !f )
            {
                if (errno == EACCES)
                {
                    CV_LOG_WARNING(NULL, "imwrite_('" << filename << "'): can't open file for writing: permission denied");
                }
            }
            else
            {
                fclose(f);
                remove(filename.c_str());
            }
        }
782 783 784 785 786 787 788 789 790
    }
    catch (const cv::Exception& e)
    {
        std::cerr << "imwrite_('" << filename << "'): can't write data: " << e.what() << std::endl << std::flush;
    }
    catch (...)
    {
        std::cerr << "imwrite_('" << filename << "'): can't write data: unknown exception" << std::endl << std::flush;
    }
791 792 793 794 795

    //    CV_Assert( code );
    return code;
}

796
bool imwrite( const String& filename, InputArray _img,
797
              const std::vector<int>& params )
798
{
799
    CV_TRACE_FUNCTION();
800 801 802

    CV_Assert(!_img.empty());

803
    std::vector<Mat> img_vec;
804
    if (_img.isMatVector() || _img.isUMatVector())
805
        _img.getMatVector(img_vec);
806
    else
807
        img_vec.push_back(_img.getMat());
808

809
    CV_Assert(!img_vec.empty());
810
    return imwrite_(filename, img_vec, params, false);
811 812
}

813 814
static bool
imdecode_( const Mat& buf, int flags, Mat& mat )
815
{
816 817 818 819 820
    CV_Assert(!buf.empty());
    CV_Assert(buf.isContinuous());
    CV_Assert(buf.checkVector(1, CV_8U) > 0);
    Mat buf_row = buf.reshape(1, 1);  // decoders expects single row, avoid issues with vector columns

821
    String filename;
822

823
    ImageDecoder decoder = findDecoder(buf_row);
R
Roman Donchenko 已提交
824
    if( !decoder )
825 826
        return 0;

827 828 829 830 831 832 833 834 835 836 837 838 839 840
    int scale_denom = 1;
    if( flags > IMREAD_LOAD_GDAL )
    {
        if( flags & IMREAD_REDUCED_GRAYSCALE_2 )
            scale_denom = 2;
        else if( flags & IMREAD_REDUCED_GRAYSCALE_4 )
            scale_denom = 4;
        else if( flags & IMREAD_REDUCED_GRAYSCALE_8 )
            scale_denom = 8;
    }

    /// set the scale_denom in the driver
    decoder->setScale( scale_denom );

841
    if( !decoder->setSource(buf_row) )
842
    {
R
Roy Reapor 已提交
843
        filename = tempfile();
844
        FILE* f = fopen( filename.c_str(), "wb" );
845 846
        if( !f )
            return 0;
847 848
        size_t bufSize = buf_row.total()*buf.elemSize();
        if (fwrite(buf_row.ptr(), 1, bufSize, f) != bufSize)
849 850
        {
            fclose( f );
851
            CV_Error( Error::StsError, "failed to write image data to temporary file" );
852 853 854
        }
        if( fclose(f) != 0 )
        {
855
            CV_Error( Error::StsError, "failed to write image data to temporary file" );
856
        }
857 858 859
        decoder->setSource(filename);
    }

860
    bool success = false;
A
Alexander Alekhin 已提交
861
    try
862 863 864 865
    {
        if (decoder->readHeader())
            success = true;
    }
A
Alexander Alekhin 已提交
866
    catch (const cv::Exception& e)
867 868 869
    {
        std::cerr << "imdecode_('" << filename << "'): can't read header: " << e.what() << std::endl << std::flush;
    }
A
Alexander Alekhin 已提交
870
    catch (...)
871 872 873 874
    {
        std::cerr << "imdecode_('" << filename << "'): can't read header: unknown exception" << std::endl << std::flush;
    }
    if (!success)
875
    {
876
        decoder.release();
877
        if (!filename.empty())
878
        {
879
            if (0 != remove(filename.c_str()))
880
            {
881
                std::cerr << "unable to remove temporary file:" << filename << std::endl << std::flush;
882 883
            }
        }
884 885 886
        return 0;
    }

887 888
    // established the required input image size
    Size size = validateInputImageSize(Size(decoder->width(), decoder->height()));
889 890

    int type = decoder->type();
891
    if( (flags & IMREAD_LOAD_GDAL) != IMREAD_LOAD_GDAL && flags != IMREAD_UNCHANGED )
892
    {
S
Suleyman TURKMEN 已提交
893
        if( (flags & IMREAD_ANYDEPTH) == 0 )
894 895
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

S
Suleyman TURKMEN 已提交
896 897
        if( (flags & IMREAD_COLOR) != 0 ||
           ((flags & IMREAD_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
898 899 900 901 902
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

903
    mat.create( size.height, size.width, type );
904

905
    success = false;
A
Alexander Alekhin 已提交
906
    try
907
    {
908
        if (decoder->readData(mat))
909 910
            success = true;
    }
A
Alexander Alekhin 已提交
911
    catch (const cv::Exception& e)
912 913 914
    {
        std::cerr << "imdecode_('" << filename << "'): can't read data: " << e.what() << std::endl << std::flush;
    }
A
Alexander Alekhin 已提交
915
    catch (...)
916 917 918
    {
        std::cerr << "imdecode_('" << filename << "'): can't read data: unknown exception" << std::endl << std::flush;
    }
919

920
    if (!filename.empty())
921
    {
922
        if (0 != remove(filename.c_str()))
923
        {
924
            std::cerr << "unable to remove temporary file:" << filename << std::endl << std::flush;
925 926
        }
    }
927

928
    if (!success)
929
    {
930 931
        mat.release();
        return false;
932 933
    }

934 935
    if( decoder->setScale( scale_denom ) > 1 ) // if decoder is JpegDecoder then decoder->setScale always returns 1
    {
936
        resize(mat, mat, Size( size.width / scale_denom, size.height / scale_denom ), 0, 0, INTER_LINEAR_EXACT);
937 938
    }

939
    /// optionally rotate the data if EXIF' orientation flag says so
940
    if (!mat.empty() && (flags & IMREAD_IGNORE_ORIENTATION) == 0 && flags != IMREAD_UNCHANGED)
941
    {
942
        ApplyExifOrientation(decoder->getExifTag(ORIENTATION), mat);
943 944
    }

945
    return true;
946 947 948
}


949
Mat imdecode( InputArray _buf, int flags )
950
{
951 952
    CV_TRACE_FUNCTION();

953
    Mat buf = _buf.getMat(), img;
954
    imdecode_( buf, flags, img );
955

956 957
    return img;
}
958

959 960
Mat imdecode( InputArray _buf, int flags, Mat* dst )
{
961 962
    CV_TRACE_FUNCTION();

963 964
    Mat buf = _buf.getMat(), img;
    dst = dst ? dst : &img;
965
    imdecode_( buf, flags, *dst );
966

967 968
    return *dst;
}
969

970
bool imencode( const String& ext, InputArray _image,
971
               std::vector<uchar>& buf, const std::vector<int>& params )
972
{
973 974
    CV_TRACE_FUNCTION();

975
    Mat image = _image.getMat();
976
    CV_Assert(!image.empty());
977 978 979 980 981

    int channels = image.channels();
    CV_Assert( channels == 1 || channels == 3 || channels == 4 );

    ImageEncoder encoder = findEncoder( ext );
R
Roman Donchenko 已提交
982
    if( !encoder )
983
        CV_Error( Error::StsError, "could not find encoder for the specified extension" );
984 985 986 987

    if( !encoder->isFormatSupported(image.depth()) )
    {
        CV_Assert( encoder->isFormatSupported(CV_8U) );
988
        Mat temp;
989
        image.convertTo(temp, CV_8U);
990
        image = temp;
991 992 993 994 995 996
    }

    bool code;
    if( encoder->setDestination(buf) )
    {
        code = encoder->write(image, params);
997
        encoder->throwOnEror();
998 999 1000 1001
        CV_Assert( code );
    }
    else
    {
1002
        String filename = tempfile();
1003 1004
        code = encoder->setDestination(filename);
        CV_Assert( code );
1005

1006
        code = encoder->write(image, params);
1007
        encoder->throwOnEror();
1008
        CV_Assert( code );
1009

1010
        FILE* f = fopen( filename.c_str(), "rb" );
1011 1012 1013 1014 1015 1016 1017
        CV_Assert(f != 0);
        fseek( f, 0, SEEK_END );
        long pos = ftell(f);
        buf.resize((size_t)pos);
        fseek( f, 0, SEEK_SET );
        buf.resize(fread( &buf[0], 1, buf.size(), f ));
        fclose(f);
1018
        remove(filename.c_str());
1019 1020 1021 1022
    }
    return code;
}

1023
bool haveImageReader( const String& filename )
1024
{
1025
    ImageDecoder decoder = cv::findDecoder(filename);
1026 1027 1028
    return !decoder.empty();
}

1029
bool haveImageWriter( const String& filename )
1030 1031 1032 1033 1034 1035 1036 1037
{
    cv::ImageEncoder encoder = cv::findEncoder(filename);
    return !encoder.empty();
}

}

/* End of file. */