0

I have 2 images: A 1024x1024 image, and a 1022x1023 crop of it:

enter image description here

enter image description here

the following code

int main(int argc, char** argv )
{
    std::cout<<"running Lenna..\n";
    cv::Mat mat = imread("lena1022_1023.bmp", cv::IMREAD_GRAYSCALE );


    mat.convertTo(mat, CV_64FC1, 1.0 / 255.0);
    int A=mat.rows; int B=mat.cols;
    double arr2D[A][B];
    
    //convert mat to 2D vec
    std::vector<double> arr;
    arr.assign((double*)mat.data, (double*)mat.data + mat.total());
    std::vector<std::vector<double>> vec2D;
    for (int i = 0; i < mat.rows; i++) {
        auto first = arr.begin() + (mat.rows * i);
        auto last = arr.begin() + (mat.rows * i) + mat.rows;
        std::vector<double> vec0(first, last);
        vec2D.push_back(vec0);
    }

    for(int i=0; i<A; i++)
    { 
        for(int j=0; j<B; j++)
        {
            arr2D[i][j] = vec2D[i][j];
        } 
    }

    cv::Mat final1(A,B, CV_64FC1, arr2D);
    std::cout<<"final1: "<<final1.rows<<", "<<final1.cols<<"\n";

    return 0;
}

It works for the 1022x1023 image, but if I use imread on lena1024.bmp which is a 1024x1024 image, then I get a segfault error:

Segmentation fault (core dumped)

Why is this?

EDIT

I replaced double arr2D[A][B]; with

double** arr2D = new double*[A];
for(int i = 0; i < A; i++)
    arr2D[i] = new double[B];

I also outputted final1 at the end with

final1.convertTo(final1, CV_8UC3, 255.0);
cv::imwrite("lena1024-final.bmp", final1);

The result is: enter image description here

It should look like the original input image. How can I fix this?

Machavity
  • 30,841
  • 27
  • 92
  • 100
user5739619
  • 1,748
  • 5
  • 26
  • 40
  • I believe your bug is here: `double arr2D[A][B];` VLAs have a limited space because they are allocated on the stack. The default of some compilers is 8MB. [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jul 02 '20 at 01:55
  • I replaced it with a dynamic array as mentioned in the `EDIT`. The resulting image doesn't match the original one – user5739619 Jul 02 '20 at 16:36

0 Answers0