OpenCV如何在C ++

时间:2015-12-24 13:06:47

标签: c++ opencv

有人可以帮我解决这个问题吗?我需要从相同颜色的2个最大的对象中绘制轮廓,但我总是得到错误,这是我的代码。

void showconvex(Mat &thresh,Mat &frame)
{
    int largest_index = 0;
    int largest_contour = 0;
    int second_largest_index = 0;
    int second_largest_contour = 0;
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    //find contours
    findContours(thresh, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

    /// Find the convex hull object for each contour
    vector<vector<Point> >hull(contours.size());
    vector<vector<int> >inthull(contours.size());
    vector<vector<Vec4i> >defects(contours.size());

    for (int i = 0; i < contours.size(); i++)
    {
        convexHull(Mat(contours[i]), hull[i], false);
        convexHull(Mat(contours[i]),inthull[i], false);
        if (inthull[i].size()>3)
            convexityDefects(contours[i], inthull[i], defects[i]);
    }

    //find largest contour
    for (int i = 0; i< contours.size(); i++) // iterate through each contour. 
    {
        double a = contourArea(contours[i].size());  //  Find the area of contour
        if (a>largest_contour)
        {
            second_largest_contour = largest_contour;
            second_largest_index = largest_index;
            largest_contour = a;
            largest_index = i;                
        }
        else if(contours[i].size() > second_largest_contour)
        {
            second_largest_contour = contours[i].size();
            second_largest_index = i;
        }
    }
    drawContours(frame, contours, largest_index, CV_RGB(0,255,0), 2, 8, hierarchy);
    drawContours(frame, contours, second_largest_index, CV_RGB(0,255,0), 2, 8, hierarchy);
}

1 个答案:

答案 0 :(得分:0)

在你的cv :: findContours()调用后,当contours.size()为零时捕获这个案例:

if ( contours.size() == 0 ) return;

否则,您正在绘制不存在的maximum_index(等于0)和second_largest_index(也等于0)的轮廓。