2
* @function hull_demo.cpp
3
* @brief Demo code to find contours in an image
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* )
54
Mat src_copy = src.clone();
56
vector<vector<Point> > contours;
57
vector<Vec4i> hierarchy;
59
/// Detect edges using Threshold
60
threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
63
findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
65
/// Find the convex hull object for each contour
66
vector<vector<Point> >hull( contours.size() );
67
for( size_t i = 0; i < contours.size(); i++ )
68
{ convexHull( Mat(contours[i]), hull[i], false ); }
70
/// Draw contours + hull results
71
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
72
for( size_t i = 0; i< contours.size(); i++ )
74
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
75
drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
76
drawContours( drawing, hull, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
80
namedWindow( "Hull demo", WINDOW_AUTOSIZE );
81
imshow( "Hull demo", drawing );