使用 Contour Area-OpenCV 时出现断言错误

Posted

技术标签:

【中文标题】使用 Contour Area-OpenCV 时出现断言错误【英文标题】:Assertion Error when using Contour Area-OpenCV 【发布时间】:2016-06-23 02:44:26 【问题描述】:

每当我在 openCV 中使用 contourArea 函数时都会出现此错误

这是我的代码

while (true)

    Mat imgOriginal;

    bool bSuccess = cap.read(imgOriginal); // read a new frame from video



    if (!bSuccess) //if not success, break loop
    
        cout << "Cannot read a frame from video stream" << endl;
        break;
    

    Mat imgHSV;

    cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

    Mat imgThresholded;

    inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image

                                                                                                  //morphological opening (removes small objects from the foreground)
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

    //morphological closing (removes small holes from the foreground)
    dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));


    int thresh = 100;
    Mat canny_output;
    vector<Vec4i> hierarchy;
    vector<vector<Point> > contours;
    RNG rng(12345);

    Canny(imgThresholded, canny_output, thresh, thresh * 2, 3);
    /// Find contours
    findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    /// Draw contours
    Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
    for (int i = 0; i< contours.size(); i++)
    
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
    


    double area = contourArea(contours);
    std::cout << area;

    imshow("contours", drawing); 

在此之前,我的代码大部分工作正常,但我抓住轮廓区域非常重要,但它一直给我这个错误。 非常感谢任何帮助

【问题讨论】:

放入for循环double area = contourArea(contours[i]); 【参考方案1】:

cv::contourArea() 采用单个轮廓并返回该轮廓的面积,因为在您的情况下 contours 是一个轮廓列表,其中可能包含 0 个或多个轮廓,因此您明确需要访问一个轮廓使用下标为:

if (contours.size() > 0) 
    for (int i=0; i<contours.size(); i++) 
        std::cout << "Contour id : " << i << ", area = " << cv::contourArea(contours[i]) << std::endl;
    
 else 
    std::cout << "No contours found !" << std::endl;

【讨论】:

您可以安全地避开if,因为支票已经在for 是的,但它只是在else 语句中打印出一些错误,我会对其进行编辑以使其更清晰。

以上是关于使用 Contour Area-OpenCV 时出现断言错误的主要内容,如果未能解决你的问题,请参考以下文章

R语言ggplot2可视化:使用ggplot2可视化等值线图(contour plot)并通过breaks参数自定义等值线的水平或者层数(customize levels of contour)

Umbraco Contour 多步表格 - 根据用户输入决定下一步

matlab 等值线函数 contour

Abaqus---contour limit 设置

机器视觉 dev_set_contour_style算子

intersection_line_contour_xld 中的input (contour)报wrong number of value of object parameter(1501)