1. 程式人生 > >opencv_tutorial_code學習——畫最小包圍旋轉矩形&畫最小包圍橢圓

opencv_tutorial_code學習——畫最小包圍旋轉矩形&畫最小包圍橢圓

tutorial_code\ShapeDescriptors\generalContours_demo2.cpp

步驟:

1、灰度化

2、濾波

3、二值化

4、畫輪廓 findContours()

5、畫最小包圍旋轉矩形和最小包圍橢圓

vector<RotatedRect> minRect( contours.size() );

vector<RotatedRect> minEllipse( contours.size() );

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

{ minRect[i] = minAreaRect( Mat(contours[i]) );

if( contours[i].size() > 5 )

{ minEllipse[i] = fitEllipse( Mat(contours[i]) ); }

}

Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );

Mat drawing1 = Mat::zeros(threshold_output.size(), CV_8UC3);

Mat drawing2 = Mat::zeros(threshold_output.size(), CV_8UC3);

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

{

Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );

// contour
drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );

// ellipse
ellipse( drawing1, minEllipse[i], color, 2, 8 );

// rotated rectangle
Point2f rect_points[4]; minRect[i].points( rect_points );

for( int j = 0; j < 4; j++ )

line( drawing2, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );

}

結果影象: