Reputation: 866
Hello I have a basic question about opencv. If I try to allocate memory with the cv::Mat class I could do the following:
cv::Mat sumimg(rows,cols,CV_32F,0);
float* sumimgrowptr = sumimg.ptr<float>(0);
but then I get a bad pointer (Null) back. In the internet some person use this:
cv::Mat* ptrsumimg = new cv::Mat(rows,cols,CV_32F,0);
float* sumimgrowptr = ptrsumimg->ptr<float>(0);
and also here I get a Null pointer back ! but If I finally do this :
cv::Mat sumimg;
sumimg.create(rows,cols,CV_32F);
sumimg.setTo(0);
float* sumimgrowptr = sumimg.ptr<float>(0);
then everything is fine ! so I wannted to know what is wrong in what I am doing ?
Upvotes: 3
Views: 28466
Reputation: 20058
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) );
Upvotes: 25
Reputation: 3980
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);
Upvotes: 2