2
* @function generalContours_demo2.cpp
3
* @brief Demo code to obtain ellipses and rotated rectangles that contain detected contours
7
#include "opencv2/imgcodecs.hpp"
8
#include "opencv2/highgui/highgui.hpp"
9
#include "opencv2/imgproc/imgproc.hpp"
17
Mat src; Mat src_gray;
23
void thresh_callback(int, void* );
28
int main( int, char** argv )
30
/// Load source image and convert it to gray
31
src = imread( argv[1], 1 );
33
/// Convert image to gray and blur it
34
cvtColor( src, src_gray, COLOR_BGR2GRAY );
35
blur( src_gray, src_gray, Size(3,3) );
38
const char* source_window = "Source";
39
namedWindow( source_window, WINDOW_AUTOSIZE );
40
imshow( source_window, src );
42
createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );
43
thresh_callback( 0, 0 );
50
* @function thresh_callback
52
void thresh_callback(int, void* )
55
vector<vector<Point> > contours;
56
vector<Vec4i> hierarchy;
58
/// Detect edges using Threshold
59
threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
61
findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
63
/// Find the rotated rectangles and ellipses for each contour
64
vector<RotatedRect> minRect( contours.size() );
65
vector<RotatedRect> minEllipse( contours.size() );
67
for( size_t i = 0; i < contours.size(); i++ )
68
{ minRect[i] = minAreaRect( Mat(contours[i]) );
69
if( contours[i].size() > 5 )
70
{ minEllipse[i] = fitEllipse( Mat(contours[i]) ); }
73
/// Draw contours + rotated rects + ellipses
74
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
75
for( size_t i = 0; i< contours.size(); i++ )
77
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
79
drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
81
ellipse( drawing, minEllipse[i], color, 2, 8 );
83
Point2f rect_points[4]; minRect[i].points( rect_points );
84
for( int j = 0; j < 4; j++ )
85
line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
89
namedWindow( "Contours", WINDOW_AUTOSIZE );
90
imshow( "Contours", drawing );