segmentation fault in findcontours opencv

瘦欲@ 提交于 2020-01-25 13:29:29

问题


I am trying to detect a ball and draw boundaries to it. It shows the error

segmentation fault (core dumped)

The mistake is somewhere here,

vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

   Mat itt = Mat::zeros( imgThresholded.size(), CV_8UC1 );
itt = imgThresholded*255;

Canny( itt ,itt, 10, 30, 3 );
vector<vector<Point> > contours_poly( contours.size() );
vector<Point2f>center( contours.size() );
vector<float>radius( contours.size() );
vector<Rect> boundRect( contours.size() );
imshow("canny", itt);
//CIRCLE HOUGH
//vector<Vec3f> circles;
findContours( itt, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
for( int i = 0; i < contours.size(); i++ )
     {
         Scalar color = Scalar(255,255,255);

       if( contours[i].size() > points )
       {approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
      boundRect[i] = boundingRect( Mat(contours_poly[i]) );
       minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] );
       circle( imgOriginal, center[i], (int)radius[i],color, 2, 8, 0 );
     }
     }

I am not able to understand where there is segfault.


回答1:


Declare other vectors after findContours as shown below. For further reference you can see here. Hope this resolves you error. I have faced the same error and got the solution for this in the link I have mentioned.

findContours( itt, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<vector<Point> > contours_poly( contours.size() );
vector<Point2f>center( contours.size() );
vector<float>radius( contours.size() );
vector<Rect> boundRect( contours.size() );



回答2:


You first do vector boundRect( contours.size() ); Here, contours is still empty. Then you call findContours, which calculates and sets the size of contours, then you try to directly write it to boundRect[i].

Just call boundRect.push_back(boundingRect( Mat(contours_poly[i]) ) ); instead, then you should be fine.

If you are doing prototypical code, it is generally better for debugging to use boundRect.at(i) = ..., because this will give you an understandable error like "out of range".



来源:https://stackoverflow.com/questions/34842547/segmentation-fault-in-findcontours-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!