Engine
Engine

Reputation: 5432

Getting opencv error in c++

I'm try to get the error of opencv! say I have this program:

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>

int main (){
    cv::Mat frame;
    cv::VideoCapture cap(1); // I don't have a second videoinput device! 
    int key = 0; 

    while(key !=27){
        cap >> frame;
        cv::imshow("frame",frame);
        key = cv::waitKey(10);
    }

    cap.release();
    return 0;
}

when I run this program I get in the console this message :

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in unknown functi
on, file ..\..\..\opencv\modules\highgui\src\window.cpp, line 261

My question is how can I get this message and save it in a string for every error that I get! and if it'S possible escaping the program crash!

thanks in advance!

Upvotes: 14

Views: 31455

Answers (2)

Albert
Albert

Reputation: 68330

It uses C++ exceptions. See here in the doc for more.

try
{
    ... // call OpenCV
}
catch( cv::Exception& e )
{
    const char* err_msg = e.what();
    std::cout << "exception caught: " << err_msg << std::endl;
}

A CV_Assert in the OpenCV code is a macro which calls the OpenCV function error. That function can be seen here. It will always print the error text on stderr unless you don't have the customErrorCallback set. You do that via cvRedirectError, see here.

Upvotes: 28

SRF
SRF

Reputation: 979

You have to check whether OpenCV function calls in your code is successfully executed or not. Then you can understand the exact problem. Here is the modified code.

int main (){
    cv::Mat frame;
    cv::VideoCapture cap(1); // I don't have a second videoinput device! 

    if ( !cap.isOpened() )  // if not success, exit program
    {
         cout << "Cannot open the video cam" << endl;
         return -1;
    }

    int key = 0; 

    while(key !=27){
        bool bSuccess = cap.read(frame); // read a new frame from video

         if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read the frame from video cam" << endl;
            break;
        }
        cv::imshow("frame",frame);
        key = cv::waitKey(10);
    }

    cap.release();
    return 0;
}

Upvotes: -1

Related Questions