• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @function findContours_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
31   src = imread(argv[1]);
32   if (src.empty())
33   {
34     cerr << "No image supplied ..." << endl;
35     return -1;
36   }
37 
38   /// Convert image to gray and blur it
39   cvtColor( src, src_gray, COLOR_BGR2GRAY );
40   blur( src_gray, src_gray, Size(3,3) );
41 
42   /// Create Window
43   const char* source_window = "Source";
44   namedWindow( source_window, WINDOW_AUTOSIZE );
45   imshow( source_window, src );
46 
47   createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
48   thresh_callback( 0, 0 );
49 
50   waitKey(0);
51   return(0);
52 }
53 
54 /**
55  * @function thresh_callback
56  */
thresh_callback(int,void *)57 void thresh_callback(int, void* )
58 {
59   Mat canny_output;
60   vector<vector<Point> > contours;
61   vector<Vec4i> hierarchy;
62 
63   /// Detect edges using canny
64   Canny( src_gray, canny_output, thresh, thresh*2, 3 );
65   /// Find contours
66   findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
67 
68   /// Draw contours
69   Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
70   for( size_t i = 0; i< contours.size(); i++ )
71      {
72        Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
73        drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() );
74      }
75 
76   /// Show in a window
77   namedWindow( "Contours", WINDOW_AUTOSIZE );
78   imshow( "Contours", drawing );
79 }
80