2 * @function hull_demo.cpp
3 * @brief Demo code to find contours in an image
7 #include "opencv2/highgui/highgui.hpp"
8 #include "opencv2/imgproc/imgproc.hpp"
16 Mat src; Mat src_gray;
22 void thresh_callback(int, void* );
27 int main( int, char** argv )
29 /// Load source image and convert it to gray
30 src = imread( argv[1], 1 );
32 /// Convert image to gray and blur it
33 cvtColor( src, src_gray, COLOR_BGR2GRAY );
34 blur( src_gray, src_gray, Size(3,3) );
37 const char* source_window = "Source";
38 namedWindow( source_window, WINDOW_AUTOSIZE );
39 imshow( source_window, src );
41 createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );
42 thresh_callback( 0, 0 );
49 * @function thresh_callback
51 void thresh_callback(int, void* )
53 Mat src_copy = src.clone();
55 vector<vector<Point> > contours;
56 vector<Vec4i> hierarchy;
58 /// Detect edges using Threshold
59 threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
62 findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
64 /// Find the convex hull object for each contour
65 vector<vector<Point> >hull( contours.size() );
66 for( size_t i = 0; i < contours.size(); i++ )
67 { convexHull( Mat(contours[i]), hull[i], false ); }
69 /// Draw contours + hull results
70 Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
71 for( size_t i = 0; i< contours.size(); i++ )
73 Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
74 drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
75 drawContours( drawing, hull, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
79 namedWindow( "Hull demo", WINDOW_AUTOSIZE );
80 imshow( "Hull demo", drawing );