问题
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