opencv cv::mat allocation

我们两清 提交于 2019-12-04 16:24:39

The main problem is here

cv::Mat sumimg(rows,cols,CV_32F,0);

OpenCV provides multiple constructors for matrices. Two of them are declares as follows:

cv::Mat(int rows, int cols, int type, SomeType initialValue);

and

cv::Mat(int rows, int cols, int type, char* preAllocatedPointerToData);

Now, if you declare a Mat as follows:

cv::Mat sumimg(rows,cols,CV_32F,5.0);

you get a matrix of floats, allocated and initialized with 5.0. The constructor called is the first one.

But here

cv::Mat sumimg(rows,cols,CV_32F,0);

what you send is a 0, which in C++ is a valid pointer address. So the compiler calls the constructor for the preallocated data. It does not allocate anything, and when you want to access its data pointer, it is, no wonder, 0 or NULL.

A solution is to specify that the fourth parameter is a float:

cv::Mat sumimg(rows,cols,CV_32F,0.0);

But the best is to avoid such situations, by using a cv::Scalar() to init:

cv::Mat sumimg(rows,cols,CV_32F, cv::Scalar::all(0) );

I believe you are calling the constructor Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP) when you do cv::Mat sumimg(rows,cols,CV_32F,0); and cv::Mat* ptrsumimg = new cv::Mat(rows,cols,CV_32F,0);.

See the documentation : http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat

I.e. you are not creating any values for the matrix, with means that you are not allocating any space for the values within the matrix, and because of that you receive a NULL pointer when doing

ptrsumimg->ptr<float>(0);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!