如何抑制OpenCV错误消息

How to suppress OpenCV error message

本文关键字:消息 错误 OpenCV 何抑制      更新时间:2023-10-16

我正在使用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;
}

当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错误消息呢?

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