gedefet
gedefet

Reputation: 83

OpenCV: Assertion failed with drawContours()

I'm trying to draw contours from an image. I got a frame from my webcam an extract its contours. Then, I filter them by area, and calling drawContours() to show them. The problem is when I try to draw the filtered contours...if I draw the original ones everything works fine. Here is the code:

    size_t contours_size=contours.size();
    bool contour_is_valid[contours_size];
    size_t filtered_contours=0;
    size_t copied_contours=0;
    size_t i;
    double area;
    for(i=0;i<contours_size;i++){
        area=contourArea(contours.at(i),false);
        if(area>minArea && area<maxArea){
            contour_is_valid[i]=true;
            filtered_contours++;
        }
        else{
            contour_is_valid[i]=false;
        }
    }
    area_filtered_contours.resize(filtered_contours);
    for(i=0;i<contours_size;i++){
    if(contour_is_valid[i]==true){
            area_filtered_contours.at(copied_contours).resize(contours.at(i).size());
            copy(contours.at(i).begin(),contours.at(i).end(),back_inserter(area_filtered_contours.at(copied_contours)));
            copied_contours++;
        }
    }

contours is the output of findContours() and thus, its a vector< vector < Point > > data as equal as area_filtered_contours. What i am trying to do is to generate another structure like that that have the useful contours in an area sense. Then

drawContours(cnt_img2,contours,_levels <= 0 ? 3 : -1, 255,1,8,hierarchy, std::abs(_levels) );

works fine but

drawContours(cnt_img2,area_filtered_contours,_levels <= 0 ? 3 : -1, 255,1,8,hierarchy, std::abs(_levels) );

give me an assertion error. What could be the problem?

Thanks in advance,

Federico

Upvotes: 1

Views: 2773

Answers (1)

&#216;ystein W.
&#216;ystein W.

Reputation: 517

As your assertion says: OpenCV Error: Assertion failed (hierarchy.total() == ncontours && hierarchy.type() == CV_32SC4)

Info about the hierarchy from findContours() (opencv.org): Optional output vector, containing information about the image topology. It has as many elements as the number of contours.

When you change the number of countures you also have to edit the hierarchy. This is an optional input. Edit this as well or don't use it.

Upvotes: 4

Related Questions