1 /**
2 * @function hull_demo.cpp
3 * @brief Demo code to find contours in an image
4 * @author OpenCV team
5 */
6
7 #include "opencv2/imgcodecs.hpp"
8 #include "opencv2/highgui/highgui.hpp"
9 #include "opencv2/imgproc/imgproc.hpp"
10 #include <iostream>
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 using namespace cv;
15 using namespace std;
16
17 Mat src; Mat src_gray;
18 int thresh = 100;
19 int max_thresh = 255;
20 RNG rng(12345);
21
22 /// Function header
23 void thresh_callback(int, void* );
24
25 /**
26 * @function main
27 */
main(int,char ** argv)28 int main( int, char** argv )
29 {
30 /// Load source image and convert it to gray
31 src = imread( argv[1], 1 );
32
33 /// Convert image to gray and blur it
34 cvtColor( src, src_gray, COLOR_BGR2GRAY );
35 blur( src_gray, src_gray, Size(3,3) );
36
37 /// Create Window
38 const char* source_window = "Source";
39 namedWindow( source_window, WINDOW_AUTOSIZE );
40 imshow( source_window, src );
41
42 createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );
43 thresh_callback( 0, 0 );
44
45 waitKey(0);
46 return(0);
47 }
48
49 /**
50 * @function thresh_callback
51 */
thresh_callback(int,void *)52 void thresh_callback(int, void* )
53 {
54 Mat src_copy = src.clone();
55 Mat threshold_output;
56 vector<vector<Point> > contours;
57 vector<Vec4i> hierarchy;
58
59 /// Detect edges using Threshold
60 threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
61
62 /// Find contours
63 findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
64
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 ); }
69
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++ )
73 {
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() );
77 }
78
79 /// Show in a window
80 namedWindow( "Hull demo", WINDOW_AUTOSIZE );
81 imshow( "Hull demo", drawing );
82 }
83