简体   繁体   中英

OpenCV: contourArea assertion failed

when I try to start my application it crashes unexpectedly while executing contourArea.

Here is the error:

OpenCV Error: Assertion Failed (contour.checkVector(2) >= 0 && (contour.depth() ==CV_32F || contour.depth() == CV_32S)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\contours.cpp, line 1904

My program is simple: 1.catch frame from camera, 2. gaussian and median filtering, 3. morphological opening, 4. threshold, 5. findContours, 6. draw the contourn with bigger area

Here is my code:

#include <opencv2/opencv.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;

Mat mask(480,640, CV_8UC1);
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
vector<Point> my_contourn;

int main(){
VideoCapture camera(0);

if(!camera.isOpened()){
    return -1;
}

while(1){
    Mat cameraframe,filtered_img,mask2;
    camera >> cameraframe; 

    GaussianBlur(cameraframe,filtered_img,Size(11,11),0,0);
    medianBlur(filtered_img,filtered_img,11);
    cvtColor(filtered_img,filtered_img,CV_BGR2HSV);
    inRange(filtered_img, Scalar(0, 76, 97), Scalar(20, 143, 205), mask);
    morphologyEx(mask,mask,MORPH_OPEN,getStructuringElement(MORPH_RECT,Size(9,9),Point(4,4)));
    GaussianBlur(mask,mask,Size(3,3),0,0);
    dilate(mask,mask,getStructuringElement(MORPH_ELLIPSE,Size(7, 7),Point(0, 0) ));


    mask.copyTo(mask2);
    findContours(mask2,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,Point(0, 0));

    double area,max_area=0.0;


    for(int i=0;i<contours.size();i++){

        area = fabs(contourArea(contours[i]));
        if (area>max_area)
        {
            max_area=area;
            my_contourn=contours[i];
        }
    }

    drawContours( mask, my_contourn, 10, Scalar(255,0,0), 2, 8);

    imshow("my cont",mask);

    if(waitKey(30)>=0)
        break;
}
return 0;
}

How I can fix it??

I confirm that is a VS2012 problem. On VS2010 everythings is fine.

This wierd bug also occurs on VS2013.

Try converting the type of contours[i] from vector to CV::Mat before pass it to contourArea.

Mat conMat(contours[i].size(), 2, CV_32FC1);
for(int i = 0; i < contours[i].size(); i ++)
{
     conMat.at<float>(i, 0) = contours[i].x;
     conMat.at<float>(i, 1) = contours[i].y;
}    
area = fabs(contourArea(conMat));

That works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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