12

I am writing an OpenCV project using g++ and opencv 2.4.6

I have some code like this:

try 
{
    H = findHomography( obj, scene, CV_RANSAC );
}
catch (Exception &e)
{
    if (showOutput)
        cout<< "Error throwed when finding homography"<<endl;
    errorCount++;
    if (errorCount >=10)
    {
        errorCount = 0;
        selected_temp = -99;
        foundBB = false;
        bb_x1 = 0;
        bb_x2 = 0;
        bb_y1 = 0;
        bb_y2 = 0;
    }
    return -1;
}

Error will be thrown when the findHomography failed to find things. The error message includes:

OpenCV Error: Assertion failed (npoints >= 0 && points2.checkVector(2) 
== npoints && points1.type() == points2.type()) in findHomography, 
file /Users/dji-mini/Downloads/opencv- 2.4.6/modules/calib3d/src/fundam.cpp, 
line 1074
OpenCV Error: Assertion failed (count >= 4) in cvFindHomography, 
file /Users/dji-mini/Downloads/opencv-2.4.6/modules/calib3d/src/fundam.cpp, line 235

Since I know under what conditions the message would appear, I want to suppress these error messages. But I don't know how to do it.

In old version of OpenCV, there seems to have a "cvSetErrMode", which, according to other articles, is depreciated in OpenCV 2.X. So what function can I use to suppress OpenCV error messages?

Aurelius
  • 11,111
  • 3
  • 52
  • 69
PaulYang
  • 330
  • 3
  • 9

1 Answers1

18

cv::error() is called on every occurrence of an assertion failure. The default behavior is to print the assertion statement to std::cerr.

You can use the undocumented cv::redirectError() function to set a custom error-handling callback. This will override the default behavior of cv::error(). You first need to define a custom error-handling function:

int handleError( int status, const char* func_name,
            const char* err_msg, const char* file_name,
            int line, void* userdata )
{
    //Do nothing -- will suppress console output
    return 0;   //Return value is not used
}

And then set the callback before the code which throw:

    cv::redirectError(handleError);

try {
    // Etc...

If at any point you wish to restore the default behavior, you can do so:

cv::redirectError(nullptr);    //Restore default behavior; pass NULL if no C++11
Aurelius
  • 11,111
  • 3
  • 52
  • 69
  • Thank you very much! It works very well. How did you find this function? – PaulYang Jul 11 '13 at 01:18
  • 3
    The function is documented now [here](http://opencv.jp/opencv-2.2_org/c/core_utility_and_system_functions_and_macros.html#redirecterror) and available as `cvRedirectError`. See also the related code of `error()` [here](https://github.com/Itseez/opencv/blob/master/modules/core/src/system.cpp). It will just call this instead of printing it to stderr, but it will still throw the exception. – Albert Oct 21 '13 at 09:21