在cvCopyImage/cvResize运行期间崩溃

Crash during running at cvCopyImage/cvResize

本文关键字:崩溃 运行期 cvResize cvCopyImage      更新时间:2023-10-16

我正在使用OpenCV 2.3制作简单的网络摄像头程序,并被运行时错误卡住。如有任何意见,我将不胜感激。

编译通过,但在运行时,我得到以下错误(在cvCopyImage/cvResize在'read'函数在下面的代码)。

错误:

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++指针的新手(我在另一个问题上有一个有见地的评论)不能保存从网络摄像头捕获的图像(用OpenCV 2.3写编译错误)来指出可能的"悬空指针",但这次是一样的吗?

问题是您正在返回指向堆栈分配变量的指针,该变量在函数结束时自动销毁。

  // ...
  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帧,否则您的应用程序将泄漏内存。