简体   繁体   中英

C++ Opencv: Error when printing Mat after assigning values

I declared a Mat and assign values to every element using a for-loop. Then I want to print its values. However, I core dump error happens. My code is as follows:

#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <iostream>
#include <time.h>

using namespace std;
using namespace cv;

int main(int argc, char const *argv[])
{
    int n = 4, i, j;
    srand (time(NULL));
    int n_Channel = 1;
    int mySizes[2] = {2, 4};
    Mat M = Mat::zeros(2, mySizes, CV_32FC(n_Channel));
    cout << M.rows << "," << M.cols << "," << M.channels() << endl;
    cout << M << endl;
    for (i = 0; i < M.rows; ++i)
    {
        for (j = 0; j < M.cols; ++j)
        {
            M.at<Vec3f>(i,j)[0] = rand() % n;
            cout << "i=" << i << ", j=" << j << ", M.at<Vec3f>(i,j)[0]=" << M.at<Vec3f>(i,j)[0] << endl;
        }
    }
    cout << "???????" << endl;
    cout << M << endl;

    return 0;
}

The cout works until it finishes printing the "???????". Then the core dump error happens. The screen message is as follows:

2,4,1
[0, 0, 0, 0;
 0, 0, 0, 0]
i=0, j=0, M.at<Vec3f>(i,j)[0]=3
i=0, j=1, M.at<Vec3f>(i,j)[0]=3
i=0, j=2, M.at<Vec3f>(i,j)[0]=3
i=0, j=3, M.at<Vec3f>(i,j)[0]=1
i=1, j=0, M.at<Vec3f>(i,j)[0]=3
i=1, j=1, M.at<Vec3f>(i,j)[0]=3
i=1, j=2, M.at<Vec3f>(i,j)[0]=0
i=1, j=3, M.at<Vec3f>(i,j)[0]=0
???????
*** Error in `./my_app': malloc(): memory corruption (fast): 0x000000000245dfb0 ***
======= Backtrace: =========

What's wrong with my code? Why does it report double free error?

Thank you for helping me!

The first comment solve my problem. I just copy his comment here:

Change int n_Channel = 1 to const int n_Channel = 1, and then change all M.at to M.at>. Your actual example only has one channel, thus using Vec3f is wrong. Using Vec gives you the possibility to address float images of arbitrary number of channels. But therefore, n_Channel must be const.

Thank you @HansHirse .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM