繁体   English   中英

OpenCV如何在C ++中从网络摄像头(跟踪)绘制2个最大对象的轮廓

[英]OpenCV how to draw a contour of 2 largest Object from webcam(tracking) in C++

有人可以帮我解决这个问题吗? 我需要使用相同的颜色从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);
}

在您的cv :: findContours()调用之后,当contours.size()为零时,情况发生了:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM