2013-07-10 114 views
7

我使用G ++和OpenCV 2.4.6如何抑制OpenCV的错误信息

我有一些像这样的代码编写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; 
} 

当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 

因为我知道在什么情况下消息会出现,我想抑制这些错误消息。但我不知道该怎么做。

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

回答

13

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 
} 

然后该扔的代码之前设置回调:

cv::redirectError(handleError); 

try { 
    // Etc... 

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

cv::redirectError(nullptr); //Restore default behavior; pass NULL if no C++11 
+0

非常感谢!它工作得很好。你是如何找到这个功能的? – PaulYang

+2

我不得不在源代码中进行一些挖掘。 – Aurelius

+0

现在这个函数被记录[这里](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,但它仍会抛出异常。 – Albert