0

I am trying this simple code:

int main()

{
    Mat a = Mat::zeros(Size(200,200) , CV_8UC1); Mat b;
    b = a;
    for(int i=0 ; i< a.rows ; i++)
    {
        for(int j = 0 ; j< a.cols ; j++)
        {
            a.at<int>(i,j) =  100;
        }
    }

    namedWindow("one" , WINDOW_AUTOSIZE);
    namedWindow("two" , WINDOW_AUTOSIZE);

    imshow("one", a);
    imshow("two", b);


    waitKey();

    return 0;
}

But I get some strange results about memory map. What is the problem of this code?

Hasani
  • 3,543
  • 14
  • 65
  • 125

2 Answers2

2

The problem in this line.

a.at<int>(i,j) =  100;

You should replace it to:

a.at<uint8_t>(i,j) =  100;

or to:

a.at<uchar>(i,j) =  100;

Because you set your type to CV_8UC1 you have to specify that the elements you want access have 8 bits. Otherwise you will get memory crash.

2

You need to be mindful of how you declare your cv::Mat

Mat a = Mat::zeros(Size(200,200) , CV_8UC1);

This cv::Mat of type CV_8UC1 is using an 8 bit type (unsigned char).

a.at<int>(i,j) =  100;

This function call is passing a template type of int (signed 32-bit integer). You have a type conflict.

The solution would be:

a.at<uchar>(i,j) =  100;
harrynowl
  • 36
  • 2