OpenCV:断言失败

时间:2018-09-04 04:41:23

标签: c++ opencv

当我尝试使用adaptiveThreshold()函数时,出现此类错误。可能出了什么问题?

这是我的代码:

int main()
{
    try 
    {
        cv::Mat img = cv::imread("rubikscube.png");
        cv::Mat thres_final;
        cv::Mat adap_thres_final;

        cv::threshold(img, thres_final, 0, 255, CV_THRESH_BINARY);
        cv::adaptiveThreshold(img, adap_thres_final, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, 11, 2);

        cv::namedWindow("Source");
        cv::imshow("Source", img);

        cv::namedWindow("Threshold");
        cv::imshow("Threshold", thres_final);

        cv::namedWindow("Adaptive Threshold");
        cv::imshow("Adaptive Threshold", adap_thres_final);

        cv::waitKey(0);

    }
    catch (...)
    {
        std::cout << "Exception Occured! \n";
    }

    return 0;
}

enter image description here

1 个答案:

答案 0 :(得分:-1)

在计算机上运行此代码时,出现以下错误

OpenCV Error: Assertion failed (src.type() == CV_8UC1) in adaptiveThreshold, file /Users/lakshayg/dev/opencv/modules/imgproc/src/thresh.cpp, line 795

adaptiveThreshold接受类型为CV_8UC1的图像,但您传递的是CV_8UC3

解决此问题的一种方法是首先将图像读取为灰度。

imread调用更改为

cv::Mat img = cv::imread("rubikscube.png", CV_LOAD_IMAGE_GRAYSCALE);

此处的CV_LOAD_IMAGE_GRAYSCALE指示函数以灰度读取图像。