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 ?
The main problem is here
OpenCV provides multiple constructors for matrices. Two of them are declares as follows:
and
Now, if you declare a Mat as follows:
you get a matrix of floats, allocated and initialized with 5.0. The constructor called is the first one.
But here
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:
But the best is to avoid such situations, by using a cv::Scalar() to init: