goodFeaturesToTrack_Demo.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * @function goodFeaturesToTrack_Demo.cpp
  3. * @brief Demo code for detecting corners using Shi-Tomasi method
  4. * @author OpenCV team
  5. */
  6. #include "opencv2/imgcodecs.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include "opencv2/imgproc.hpp"
  9. #include <iostream>
  10. using namespace cv;
  11. using namespace std;
  12. /// Global variables
  13. Mat src, src_gray;
  14. int maxCorners = 23;
  15. int maxTrackbar = 100;
  16. RNG rng(12345);
  17. const char* source_window = "Image";
  18. /// Function header
  19. void goodFeaturesToTrack_Demo( int, void* );
  20. /**
  21. * @function main
  22. */
  23. int main( int argc, char** argv )
  24. {
  25. /// Load source image and convert it to gray
  26. CommandLineParser parser( argc, argv, "{@input | pic3.png | input image}" );
  27. src = imread( samples::findFile( parser.get<String>( "@input" ) ) );
  28. if( src.empty() )
  29. {
  30. cout << "Could not open or find the image!\n" << endl;
  31. cout << "Usage: " << argv[0] << " <Input image>" << endl;
  32. return -1;
  33. }
  34. cvtColor( src, src_gray, COLOR_BGR2GRAY );
  35. /// Create Window
  36. namedWindow( source_window );
  37. /// Create Trackbar to set the number of corners
  38. createTrackbar( "Max corners:", source_window, &maxCorners, maxTrackbar, goodFeaturesToTrack_Demo );
  39. imshow( source_window, src );
  40. goodFeaturesToTrack_Demo( 0, 0 );
  41. waitKey();
  42. return 0;
  43. }
  44. /**
  45. * @function goodFeaturesToTrack_Demo.cpp
  46. * @brief Apply Shi-Tomasi corner detector
  47. */
  48. void goodFeaturesToTrack_Demo( int, void* )
  49. {
  50. /// Parameters for Shi-Tomasi algorithm
  51. maxCorners = MAX(maxCorners, 1);
  52. vector<Point2f> corners;
  53. double qualityLevel = 0.01;
  54. double minDistance = 10;
  55. int blockSize = 3, gradientSize = 3;
  56. bool useHarrisDetector = false;
  57. double k = 0.04;
  58. /// Copy the source image
  59. Mat copy = src.clone();
  60. /// Apply corner detection
  61. goodFeaturesToTrack( src_gray,
  62. corners,
  63. maxCorners,
  64. qualityLevel,
  65. minDistance,
  66. Mat(),
  67. blockSize,
  68. gradientSize,
  69. useHarrisDetector,
  70. k );
  71. /// Draw corners detected
  72. cout << "** Number of corners detected: " << corners.size() << endl;
  73. int radius = 4;
  74. for( size_t i = 0; i < corners.size(); i++ )
  75. {
  76. circle( copy, corners[i], radius, Scalar(rng.uniform(0,255), rng.uniform(0, 256), rng.uniform(0, 256)), FILLED );
  77. }
  78. /// Show what you got
  79. namedWindow( source_window );
  80. imshow( source_window, copy );
  81. }