打开cv寻找凸包

时间:2015-07-10 14:01:23

标签: c++ opencv

OpenCV中的以下代码用于检测黄色球并绘制其凸包。虽然代码不会产生任何编译错误,但在输出窗口中会出现以下错误。 我使用最大面积函数来避免较小的不需要的轮廓。 错误是

断言失败< 0< = contourIdx&& contourIdx<最后>在cv :: drawContours中,文件C:Buildsmasters ..(某些路径),第2299行****

#include <opencv\cv.h>
    #include <opencv2\highgui\highgui.hpp>
    #include<opencv\cvaux.h>
    #include<opencv\cxcore.h>
    #include <opencv2\imgproc\imgproc.hpp>
    #include <iostream>
    #include<conio.h>
    #include <stdlib.h>



    using namespace cv;
    using namespace std;

    int main(){


        Mat img, frame, img2, img3;
        double maxarea = 0;
        int lrgctridx; //largest contour index
        VideoCapture cam(0);
        while (true){
            cam.read(frame);
            cvtColor(frame, img, CV_BGR2HSV);
            //thresholding 
            inRange(img, Scalar(0, 143, 86), Scalar(39, 255, 241), img2);



            //finding contours
            vector<vector<Point>> Contours;
            vector<Vec4i> hier;
            //morphological transformations
            erode(img2, img2, getStructuringElement(MORPH_RECT, Size(3, 3)));
            erode(img2, img2, getStructuringElement(MORPH_RECT, Size(3, 3)));

            dilate(img2, img2, getStructuringElement(MORPH_RECT, Size(8, 8)));
            dilate(img2, img2, getStructuringElement(MORPH_RECT, Size(8, 8)));


            //finding the contours required
            findContours(img2, Contours, hier, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, Point(0, 0));



            //finding the contour of largest area and storing its index
            for (int i = 0; i < Contours.size(); i++)
            {
            double a=contourArea(Contours[i]);
            if (a> maxarea)
            {
                maxarea = a;
             lrgctridx=i;
            }

            }
            //convex hulls
            vector<vector<Point> >hull(Contours.size());
            for (int i = 0; i < Contours.size(); i++)
            {
                convexHull(Contours[i], hull[i], false);
            }
            //REQUIRED contour is detected,then draw a convex hull
            if (maxarea!=0)
           drawContours(frame, hull, lrgctridx, Scalar(255, 255, 255), 1, 8, vector<Vec4i>(), 0, Point());



            imshow("output", frame);
            char key = waitKey(33);
            if (key == 27) break;



        }









    }

任何帮助都会非常感激。提前提醒!

1 个答案:

答案 0 :(得分:0)

您应该在每次迭代时重置lrgctridx

假设您在时间“t”找到了一个计数器,并设置了lrgctridx = 1;。在时间“t + 1”,您找不到任何轮廓,因此Contourshull大小为0,但您尝试访问位置1.

只需将lrgctridx = 0放在for循环之前。与maxarea相同。

lrgctridx = 0;
maxarea = 0;
for (int i = 0; i < Contours.size(); i++)
{
....

现在您绘制轮廓的条件没问题,但最好用

替换它
if(!Contours.empty()) {
    drawContours(...);
    ....
相关问题