在cvCopyImage / cvResize运行期间崩溃

时间:2011-07-23 08:49:42

标签: c++ pointers opencv stack runtime-error

我正在使用OpenCV 2.3制作简单的网络摄像头程序,并因运行时错误而陷入困境。任何想法都将不胜感激。

编译传递但在运行时,我收到以下错误(在下面的代码中的'read'函数中的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>

我猜我在使用Mat或指针的方式中都存在错误。我仍然是OpenCV和C / C ++指针的新手(我在另一个问题Can't save an image captured from webcam (imwrite compile error with OpenCV 2.3)中得到了深刻的评论,指出可能的“悬空指针”,但这次是否相同?)。

1 个答案:

答案 0 :(得分: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框架,否则您的应用程序将泄漏内存。