2011-07-23 92 views
3

我正在使用OpenCV 2.3製作簡單的網絡攝像頭程序,並被運行時錯誤卡住了。任何想法將不勝感激。運行在cvCopyImage/cvResize時崩潰

編譯通行證,但運行後,我得到以下錯誤(在cvCopyImage/cvResize在下面的代碼中的'讀'功能)。

錯誤:

OpenCV Error: Bad argument (Unknown array type) in cvarrToMat, file /usr/local/src/OpenCV/OpenCV-2.3.0/modules/core/src/matrix.cpp, line 641 
terminate called after throwing an instance of 'cv::Exception' 
    what(): /usr/local/src/OpenCV/OpenCV-2.3.0/modules/core/src/matrix.cpp:641: error: (-5) Unknown array type in function cvarrToMat 

代碼摘錄:

#include <iostream> 
#include "opencv2/highgui/highgui.hpp" 
#include "opencv2/core/core.hpp" 
#include "opencv2/imgproc/imgproc.hpp" 

using namespace std; 
using namespace cv; 

Mat* SampleClassA::dispImg = NULL; 

int read() 
{ 
    Mat* sharedImg; 
    sharedImg = getFrame(); 
    if (sharedImg) 
    { 
     if (dispImg == NULL) 
     { 
      SampleClassA::dispImg = sharedImg; 
     } 
    cvCopyImage(sharedImg, SampleClassA::dispImg); // Crashes here. 
    cvResize(sharedImg, SampleClassA::classifyImg); // Can crash here too when cvCopyImage is commented out. 
    } 
    sleep(100); 
    return 1; 
} 

Mat* getFrame() 
//IplImage* ReadRealTime::getFrame() 
{ 
    if (!capture.isOpened()) // Actual capturing part is omitted here. 
    { 
     return NULL; 
    } 
    Mat frame; 
    capture >> frame; 
    return &frame; 
} 
</code> 

我的猜測是有一些錯誤無論/無論是在我用墊,或指針的方式。對於OpenCV和C/C++指針,我仍然是新手(我在另一個問題Can't save an image captured from webcam (imwrite compile error with OpenCV 2.3)中提出了一個有見地的評論,指出可能的「懸掛指針」,但是這次是相同的?)。

回答

4

問題是,您正在返回一個指向堆棧分配變量的指針,該指針在函數結束時會自動銷燬。

// ... 
    Mat frame; 
    capture >> frame; 
    return &frame; 
} // frame destroyed is at the end of the function yet you return a pointer to it! 

您需要在堆上分配框架,使其將生活在過去的函數的末尾:

// ... 
    Mat* frame = new Mat(); // Maybe this needs parameters 
    capture >> *frame; 
    return frame; 
} 

記住,您需要在稍後或您對delete框架應用程序會泄漏內存。