2012-07-06 184 views
2

您好,我有一個關於opencv的基本問題。如果我嘗試與CV分配內存::墊類,我可以做到以下幾點:opencv cv :: mat allocation

cv::Mat sumimg(rows,cols,CV_32F,0); 
float* sumimgrowptr = sumimg.ptr<float>(0); 

但後來我得到一個壞的指針(NULL)回來。在互聯網有人使用這個:

cv::Mat* ptrsumimg = new cv::Mat(rows,cols,CV_32F,0); 
float* sumimgrowptr = ptrsumimg->ptr<float>(0); 

而且在這裏我得到一個空指針回來!但如果我終於這樣做:

  cv::Mat sumimg; 
      sumimg.create(rows,cols,CV_32F); 
      sumimg.setTo(0); 
      float* sumimgrowptr = sumimg.ptr<float>(0); 

然後一切都很好!所以我想知道我在做什麼錯了?

回答

19

的主要問題是這裏

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

OpenCV爲矩陣提供了多個構造函數。其中兩個聲明如下:

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

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

現在,如果你聲明的墊子如下:

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

你彩車的矩陣,分配和初始化與5.0。被調用的構造函數是第一個。

但這裏

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

你送什麼是0,這在C++是一種有效的指針地址。所以編譯器調用預分配數據的構造函數。它不分配任何東西,並且當你想訪問它的數據指針時,這也就不足爲奇了,就是0或NULL。

一個解決辦法是指定該第四個參數是一個浮動:

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

但是,最好是避免這種情況,通過使用CV ::標量()來初始化:

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

我相信當你做cv::Mat sumimg(rows,cols,CV_32F,0);cv::Mat* ptrsumimg = new cv::Mat(rows,cols,CV_32F,0);時你打電話給構造函數Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP)

參見文檔:http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat

即你是不是創造了矩陣的任何值,與你是不是在矩陣中的值分配任何空間手段,因爲您將收到一個NULL指針時做

ptrsumimg->ptr<float>(0);

+0

鏈接對我無效,但我找到了這個:http://docs.opencv.org/modules/core/doc/basic_structures.html#Mat – Pascal 2015-10-12 07:06:20