Skip to content

Memory Access violation when saving a png image #6198

Closed

Description

@mpp

Hi I'm using opencv 3 (x86) in windows 10 , I tried also to compile the 3.1 version but I have the same problem.
I'm getting an exception when saving a png image with 4 channels.
Here is the code (is the example in the docs):

#include <vector>
#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void createAlphaMat(Mat &mat)
 {
    for (int i = 0; i < mat.rows; ++i) {
        for (int j = 0; j < mat.cols; ++j) {
            Vec4b& rgba = mat.at<Vec4b>(i, j);
            rgba[0] = UCHAR_MAX;
            rgba[1] = saturate_cast<uchar>((float(mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX);
            rgba[2] = saturate_cast<uchar>((float(mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX);
            rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
        }
    }
}

int main(int argv, char **argc)
{
    // Create mat with alpha channel
    Mat mat(480, 640, CV_8UC4);
    createAlphaMat(mat);

    vector<int> compression_params;
    compression_params.push_back(16);
    compression_params.push_back(9);

    try {
        imwrite("alpha.png", mat, compression_params);
    }
    catch (runtime_error& ex) {
        fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
        return 1;
    }
    fprintf(stdout, "Saved PNG file with alpha data.\n");
    return 0;
}

I get a memory access violation and the debugger stops in grfmt_png.cpp at line 380, around here:

...
bool isBilevel = false;

for( size_t i = 0; i < params.size(); i += 2 )
{
    if( params[i] == CV_IMWRITE_PNG_COMPRESSION )
    {
        compression_level = params[i+1];
        compression_level = MIN(MAX(compression_level, 0), Z_BEST_COMPRESSION);
    }
...

Activity

  1. Dikay900 commented on Mar 2, 2016

    @Dikay900
    Contributor
    try {
            imwrite("alpha.png", mat);
        }
        catch (runtime_error& ex) {
            fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
            return 1;
        }
    

    You do not use the compression_params variable.
    Are you using the compression params or is the exception thrown with the actual code you provided?

  2. mpp commented on Mar 2, 2016

    @mpp
    Author

    Sorry, my fault: somehow when copied the code I dropped that variable. I updated the code.

  3. mshabunin commented on Mar 2, 2016

    @mshabunin
    Contributor

    Works for me in Ubuntu for both 3.1.0 and latest master with this example code.

    Please try to make clean builds of OpenCV and your sample application. Try to check latest master branch version.

  4. mpp commented on Mar 2, 2016

    @mpp
    Author

    It's what i did with opencv 3.1

    The strange thing is that the exception is not always thrown (3 times out of 4) so I hacked the problem with a try catch inside a loop. But this should not be the final solution...

  5. mpp commented on Mar 3, 2016

    @mpp
    Author

    This is the code:

    string destinationNamePath = "";
    int count = 0;
    while (count < 1000)
    {
        count++;
    
        destinationNamePath = generateUniqueFileName(pngDestinationPath);
    
        // If the file already exists then I may cannot overwrite it
        if (!System.IO.File.Exists(destinationNamePath))
        {
            // Return false if an exception is thrown
            if (ImageProcessingWrap.ImageProcessing.MakeTransparent(sourceNamePath, destinationNamePath)) break;
        }
    }
    
    return destinationNamePath;
    

    And this is the result:
    image

    The png generated with the exception are corrupted.

    Is there a better solution in your opinion?

    Thanks

  6. alalek commented on Mar 3, 2016

    @alalek
    Member

    Please add information about MSVS version and output of "std::cout << cv::getBuildInformation().c_str() << std::endl;"

  7. mpp commented on Mar 3, 2016

    @mpp
    Author

    I have Visual Studio 2013

    The output is:

    General configuration for OpenCV 3.1.0-dev =====================================
      Version control:               3.1.0-195-gcb01201
    
      Platform:
        Timestamp:                   2016-03-02T13:10:34Z
        Host:                        Windows 10.0.10586 AMD64
        CMake:                       3.4.3
        CMake generator:             Visual Studio 12 2013
        CMake build tool:            C:/Program Files (x86)/MSBuild/12.0/bin/MSBuild.exe
        MSVC:                        1800
    
      C/C++:
        Built as dynamic libs?:      YES
        C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/cl.exe  (ver 18.0.40629.0)
        C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast  -fsigned-char /wd4251 /wd4324 /wd4275 /wd4589 /MP8  /MD /O2 /Ob2 /D NDEBUG  /Zi
        C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast  -fsigned-char /wd4251 /wd4324 /wd4275 /wd4589 /MP8  /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
        C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/cl.exe
        C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast  -fsigned-char   /MP8  /MD /O2 /Ob2 /D NDEBUG  /Zi
        C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast  -fsigned-char   /MP8  /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
        Linker flags (Release):      /machine:X86  /INCREMENTAL:NO  /debug
        Linker flags (Debug):        /machine:X86  /debug /INCREMENTAL
        Precompiled headers:         YES
        Extra dependencies:          comctl32 gdi32 ole32 setupapi ws2_32 vfw32 vtkRenderingOpenGL vtkImagingHybrid vtkIOImage vtkCommonDataModel vtkCommonMath vtkCommonCore vtksys vtkCommonMisc vtkCommonSystem vtkCommonTransforms vtkCommonExecutionModel vtkDICOMParser vtkIOCore vtkzlib vtkmetaio vtkjpeg vtkpng vtktiff vtkImagingCore vtkRenderingCore vtkCommonColor vtkFiltersExtraction vtkFiltersCore vtkFiltersGeneral vtkCommonComputationalGeometry vtkFiltersStatistics vtkImagingFourier vtkalglib vtkFiltersGeometry vtkFiltersSources vtkInteractionStyle vtkRenderingLOD vtkFiltersModeling vtkIOPLY vtkIOGeometry vtkjsoncpp vtkFiltersTexture vtkRenderingFreeType vtkfreetype vtkftgl vtkIOExport vtkRenderingAnnotation vtkImagingColor vtkRenderingContext2D vtkRenderingGL2PS vtkRenderingContextOpenGL vtkgl2ps vtkRenderingLabel
        3rdparty dependencies:       zlib libjpeg libwebp libpng libtiff libjasper IlmImf
    
      OpenCV modules:
        To be built:                 core flann imgproc ml photo video viz imgcodecs shape videoio highgui ts features2d
        Disabled:                    calib3d objdetect superres world
        Disabled by dependency:      stitching videostab
        Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev java python2 python3
    
      Windows RT support:            NO
    
      GUI:
        QT:                          NO
        Win32 UI:                    YES
        OpenGL support:              NO
        VTK support:                 YES (ver 6.2.0)
    
      Media I/O:
        ZLib:                        build (ver 1.2.8)
        JPEG:                        build (ver 90)
        WEBP:                        build (ver 0.3.1)
        PNG:                         build (ver 1.6.19)
        TIFF:                        build (ver 42 - 4.0.2)
        JPEG 2000:                   build (ver 1.900.1)
        OpenEXR:                     build (ver 1.7.1)
        GDAL:                        NO
    
      Video I/O:
        Video for Windows:           YES
        DC1394 1.x:                  NO
        DC1394 2.x:                  NO
        FFMPEG:                      YES (prebuilt binaries)
          codec:                     YES (ver 56.41.100)
          format:                    YES (ver 56.36.101)
          util:                      YES (ver 54.27.100)
          swscale:                   YES (ver 3.1.101)
          resample:                  NO
          gentoo-style:              YES
        GStreamer:                   NO
        OpenNI:                      NO
        OpenNI PrimeSensor Modules:  NO
        OpenNI2:                     NO
        PvAPI:                       NO
        GigEVisionSDK:               NO
        DirectShow:                  YES
        Media Foundation:            NO
        XIMEA:                       NO
        Intel PerC:                  NO
    
      Parallel framework:            Concurrency
    
      Other third-party libraries:
        Use IPP:                     9.0.1 [9.0.1]
             at:                     C:/Users/michele.marostica/Documents/Workspace/opencv/3rdparty/ippicv/unpack/ippicv_win
        Use IPP Async:               NO
        Use Eigen:                   NO
        Use Cuda:                    NO
        Use OpenCL:                  YES
        Use custom HAL:              NO
    
      OpenCL:                        <Dynamic loading of OpenCL library>
        Include path:                C:/Users/michele.marostica/Documents/Workspace/opencv/3rdparty/include/opencl/1.2
        Use AMDFFT:                  NO
        Use AMDBLAS:                 NO
    
      Python 2:
        Interpreter:                 C:/Python27/python.exe (ver 2.7.11)
    
      Python 3:
        Interpreter:                 NO
    
      Python (for build):            C:/Python27/python.exe
    
      Java:
        ant:                         NO
        JNI:                         C:/Program Files (x86)/Java/jdk1.7.0_71/include C:/Program Files (x86)/Java/jdk1.7.0_71/include/win32 C:/Program Files (x86)/Java/jdk1.7.0_71/include
        Java wrappers:               NO
        Java tests:                  NO
    
      Matlab:                        Matlab not found or implicitly disabled
    
      Tests and samples:
        Tests:                       NO
        Performance tests:           YES
        C/C++ Examples:              NO
    
      Install path:                  C:/Users/michele.marostica/Documents/Workspace/opencv/build/install
    
      cvconfig.h is in:              C:/Users/michele.marostica/Documents/Workspace/opencv/build
    -----------------------------------------------------------------
    
  8. alalek commented on Mar 3, 2016

    @alalek
    Member

    Thanks for update!
    Do you use "Debug" or "Release" build?

  9. mpp commented on Mar 3, 2016

    @mpp
    Author

    I use both and get the exception in both configurations!
    Thanks for your help

  10. alalek commented on Mar 3, 2016

    @alalek
    Member

    Unfortunately I can't reproduce problem with sample above.

    I used MSVS 2013 Express (x86 / Debug) and wrote 1000 images:

    General configuration for OpenCV 3.1.0-dev =====================================
      Version control:               3.1.0-208-g88a33a4
    
      Platform:
        Timestamp:                   2016-03-03T12:42:05Z
        Host:                        Windows 6.1 AMD64
        CMake:                       2.8.12.2
        CMake generator:             Visual Studio 12
        CMake build tool:            C:/PROGRA~2/MSBuild/12.0/Bin/MSBuild.exe
        MSVC:                        1800
    
      C/C++:
        Built as dynamic libs?:      YES
        C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/cl.exe  (ver 18.0.21005.1)
        C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast
        C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast
        C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/cl.exe
        C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast    /MP4  /
        C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:SSE2 /Oi /fp:fast    /MP4  /
        Linker flags (Release):      /machine:X86   /INCREMENTAL:NO  /debug
        Linker flags (Debug):        /machine:X86   /debug /INCREMENTAL
        Precompiled headers:         YES
        Extra dependencies:          comctl32 gdi32 ole32 setupapi ws2_32 vfw32
        3rdparty dependencies:       zlib libjpeg libwebp libpng libtiff libjasper IlmImf
    
      OpenCV modules:
        To be built:                 core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d java stitching videostab python2
        Disabled:                    world
        Disabled by dependency:      -
        Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev python3 viz
    
      Windows RT support:            NO
    
      GUI:
        QT:                          NO
        Win32 UI:                    YES
        OpenGL support:              NO
        VTK support:                 NO
    
      Media I/O:
        ZLib:                        build (ver 1.2.8)
        JPEG:                        build (ver 90)
        WEBP:                        build (ver 0.3.1)
        PNG:                         build (ver 1.6.19)
        TIFF:                        build (ver 42 - 4.0.2)
        JPEG 2000:                   build (ver 1.900.1)
        OpenEXR:                     build (ver 1.7.1)
        GDAL:                        NO
    
      Video I/O:
        Video for Windows:           YES
        DC1394 1.x:                  NO
        DC1394 2.x:                  NO
        FFMPEG:                      YES (prebuilt binaries)
          codec:                     YES (ver 56.41.100)
          format:                    YES (ver 56.36.101)
          util:                      YES (ver 54.27.100)
          swscale:                   YES (ver 3.1.101)
          resample:                  NO
          gentoo-style:              YES
        GStreamer:                   NO
        OpenNI:                      NO
        OpenNI PrimeSensor Modules:  NO
        OpenNI2:                     NO
        PvAPI:                       NO
        GigEVisionSDK:               NO
        DirectShow:                  YES
        Media Foundation:            NO
        XIMEA:                       NO
        Intel PerC:                  NO
    
      Parallel framework:            Concurrency
    
      Other third-party libraries:
        Use IPP:                     9.0.1 [9.0.1]
             at:                     C:/project/opencv/3rdparty/ippicv/unpack/ippicv_win
        Use IPP Async:               NO
        Use Eigen:                   NO
        Use Cuda:                    NO
        Use OpenCL:                  YES
        Use custom HAL:              NO
    
      OpenCL:                        <Dynamic loading of OpenCL library>
        Include path:                C:/project/opencv/3rdparty/include/opencl/1.2 C:/Program Files (x86)/AMD/clAmdFft/include C:/Program Files (x86)/AMD/clAmdBlas/include
        Use AMDFFT:                  YES
        Use AMDBLAS:                 YES
    
      Python 2:
        Interpreter:                 c:/python27/python.exe (ver 2.7.5)
        Libraries:                   C:/Python27/Libs/python27.lib (ver 2.7.5)
        numpy:                       c:/python27/lib/site-packages/numpy/core/include (ver 1.9.2)
        packages path:               c:/python27/Lib/site-packages
    
      Python 3:
        Interpreter:                 NO
    
      Python (for build):            c:/python27/python.exe
    
      Java:
        ant:                         C:/Program Files (x86)/apache-ant/bin/ant.bat (ver 1.9.2)
        JNI:                         C:/Program Files (x86)/Java/jdk1.6.0_45/include C:/Program Files (x86)/Java/jdk1.6.0_45/include/win32 C:/Program Files (x86)/Java/jdk1.6.0_45/include
        Java wrappers:               YES
        Java tests:                  YES
    
      Matlab:                        Matlab not found or implicitly disabled
    
      Documentation:
        Doxygen:                     c:/utils/doxygen/doxygen.exe (ver 1.8.9.1)
        PlantUML:                    NO
    
      Tests and samples:
        Tests:                       YES
        Performance tests:           YES
        C/C++ Examples:              NO
    
      Install path:                  C:/project/opencv-build-vc12-x86/install
    
      cvconfig.h is in:              C:/project/opencv-build-vc12-x86
    -----------------------------------------------------------------
    

    So we can't debug this problem on our side.

    You can try to add some "debug code" before and after imwrite call and into the "catch" block (and into PngEncoder::write function):

    printf("sz=%d\n", (int)params.size());
    for (size_t i = 0; i < params.size(); i++)
        printf("%d: %d\n", (int)i, params[i]);
    
  11. PkLab commented on Dec 16, 2016

    @PkLab
    Contributor

    might be this same as #5227 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions