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