2013-07-10 109 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