打开cv查找凸包

Open cv finding convex hull

本文关键字:凸包 查找 cv 打开      更新时间:2023-10-16

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

断言失败<0<=contourIdx&amp;contourIdx<最后>在cv::drawContours,文件C:Buildsmasters中。。(某些路径(,线路2299***

#include <opencvcv.h>
    #include <opencv2highguihighgui.hpp>
    #include<opencvcvaux.h>
    #include<opencvcxcore.h>
    #include <opencv2imgprocimgproc.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;

        }




    }

任何帮助都将不胜感激。提前解冻!

您应该在每次迭代时重置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(...);
    ....