Skip to content

Memory Access violation when saving a png image #6198

@mpp

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);
    }
...

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