IsaacS
IsaacS

Reputation: 3611

Crash during running at cvCopyImage/cvResize

I'm making simple webcam program using OpenCV 2.3 and got stuck by the runtime error. Any idea will be appreciated.

Compile passes but upon running, I get the following error (at cvCopyImage/cvResize in 'read' function in the code below).

error:

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

code excerpt:

#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>

My guess is there's something wrong either/both in the way I use Mat, or pointer. I'm still new both to OpenCV and C/C++ pointer (I've got an insightful comment in another question Can't save an image captured from webcam (imwrite compile error with OpenCV 2.3) to point out possible "dangling pointer", but is this time the same?).

Upvotes: 3

Views: 5237

Answers (1)

user786653
user786653

Reputation: 30450

The problem is that you are returning a pointer to a stack allocated variable, which is automatically destroyed at the end of the function.

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

You need to allocate the frame on the heap so that it will live on past the end of the function:

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

Remember that you need to delete the frame at a later point or your application will leak memory.

Upvotes: 4

Related Questions