2011-07-23 90 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框架应用程序会泄漏内存。