简体   繁体   中英

opencv cv::mat allocation

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

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

Ie 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);

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