Search code examples
opencvc++-cli

cvtColor crashes on conversion


I load a frame from camera with external dll to my OpenCV program. I can see the frame cv::imshow("edges", frame); and everything is ok. frame.channels() gives me 3 channels but when I try to cv::cvtColor(frame, gray, CV_BGR2GRAY); application crashes.

CreateImage(System::Byte *imgData, int height, int width,int show)
{

    frame = cv::Mat(height, width, CV_8UC3, imgData);

    if (show > 0)
        cv::imshow("edges", frame); //I can see myself

    return frame.channels(); //three channels
}

void ConvertAndProcess()
{
    cv::Mat gray;

    cv::cvtColor(frame, gray, CV_BGR2GRAY); //crash...

    //do something
}

I've been digging for some time but no results. What am I doing wrong?


Solution

  • careful !

     frame = cv::Mat(height, width, CV_8UC3, imgData);
    

    this is a 'borrowed' pointer. when imgData leaves scope (at the end of the function), frame.data is invalid.

    that means, that you can't expect frame to be valid in ConvertAndProcess() if you constructed it this way.

    you could clone() it, to achieve a 'deep copy':

     frame = cv::Mat(height, width, CV_8UC3, imgData).clone();