1 /**
2  * @function cornerHarris_Demo.cpp
3  * @brief Demo code for detecting corners using Harris-Stephens method
4  * @author OpenCV team
5  */
6 
7 #include "opencv2/highgui.hpp"
8 #include "opencv2/imgproc.hpp"
9 #include <iostream>
10 
11 using namespace cv;
12 using namespace std;
13 
14 /// Global variables
15 Mat src, src_gray;
16 int thresh = 200;
17 int max_thresh = 255;
18 
19 const char* source_window = "Source image";
20 const char* corners_window = "Corners detected";
21 
22 /// Function header
23 void cornerHarris_demo( int, void* );
24 
25 /**
26  * @function main
27  */
main(int argc,char ** argv)28 int main( int argc, char** argv )
29 {
30     /// Load source image and convert it to gray
31     CommandLineParser parser( argc, argv, "{@input | building.jpg | input image}" );
32     src = imread( samples::findFile( parser.get<String>( "@input" ) ) );
33     if ( src.empty() )
34     {
35         cout << "Could not open or find the image!\n" << endl;
36         cout << "Usage: " << argv[0] << " <Input image>" << endl;
37         return -1;
38     }
39     cvtColor( src, src_gray, COLOR_BGR2GRAY );
40 
41     /// Create a window and a trackbar
42     namedWindow( source_window );
43     createTrackbar( "Threshold: ", source_window, &thresh, max_thresh, cornerHarris_demo );
44     imshow( source_window, src );
45 
46     cornerHarris_demo( 0, 0 );
47 
48     waitKey();
49     return 0;
50 }
51 
52 /**
53  * @function cornerHarris_demo
54  * @brief Executes the corner detection and draw a circle around the possible corners
55  */
cornerHarris_demo(int,void *)56 void cornerHarris_demo( int, void* )
57 {
58     /// Detector parameters
59     int blockSize = 2;
60     int apertureSize = 3;
61     double k = 0.04;
62 
63     /// Detecting corners
64     Mat dst = Mat::zeros( src.size(), CV_32FC1 );
65     cornerHarris( src_gray, dst, blockSize, apertureSize, k );
66 
67     /// Normalizing
68     Mat dst_norm, dst_norm_scaled;
69     normalize( dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat() );
70     convertScaleAbs( dst_norm, dst_norm_scaled );
71 
72     /// Drawing a circle around corners
73     for( int i = 0; i < dst_norm.rows ; i++ )
74     {
75         for( int j = 0; j < dst_norm.cols; j++ )
76         {
77             if( (int) dst_norm.at<float>(i,j) > thresh )
78             {
79                 circle( dst_norm_scaled, Point(j,i), 5,  Scalar(0), 2, 8, 0 );
80             }
81         }
82     }
83 
84     /// Showing the result
85     namedWindow( corners_window );
86     imshow( corners_window, dst_norm_scaled );
87 }
88