如何抑制OpenCV错误消息

Pau*_*ang 9 c++ opencv g++

我正在使用g ++和opencv 2.4.6编写OpenCV项目

我有一些像这样的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

当findHomography无法找到时,将抛出错误.错误消息包括:

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
Run Code Online (Sandbox Code Playgroud)

由于我知道消息将在什么条件下出现,我想要抑制这些错误消息.但我不知道该怎么做.

在旧版本的OpenCV中,似乎有一个"cvSetErrMode",根据其他文章,它在OpenCV 2.X中被折旧.那么我可以使用什么功能来抑制OpenCV错误消息呢?

Aur*_*ius 16

cv::error()在每次出现断言失败时调用.默认行为是将断言语句打印到std::cerr.

您可以使用未记录的cv::redirectError()函数来设置自定义错误处理回调.这将覆盖默认行为cv::error().首先需要定义自定义错误处理函数:

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
}
Run Code Online (Sandbox Code Playgroud)

然后在抛出的代码之前设置回调:

    cv::redirectError(handleError);

try {
    // Etc...
Run Code Online (Sandbox Code Playgroud)

如果您希望在任何时候恢复默认行为,您可以这样做:

cv::redirectError(nullptr);    //Restore default behavior; pass NULL if no C++11
Run Code Online (Sandbox Code Playgroud)

  • 我不得不在源代码中进行一些挖掘. (2认同)
  • 该函数现在[此处](http://opencv.jp/opencv-2.2_org/c/core_utility_and_system_functions_and_macros.html#redirecterror)记录,可用作`cvRedirectError`.另请参阅`error()`[here](https://github.com/Itseez/opencv/blob/master/modules/core/src/system.cpp)的相关代码.它只是调用它而不是将它打印到stderr,但它仍然会抛出异常. (2认同)