houghcircles.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @file houghcircles.cpp
  3. * @brief This program demonstrates circle finding with the Hough transform
  4. */
  5. #include "opencv2/imgcodecs.hpp"
  6. #include "opencv2/highgui.hpp"
  7. #include "opencv2/imgproc.hpp"
  8. using namespace cv;
  9. using namespace std;
  10. int main(int argc, char** argv)
  11. {
  12. //![load]
  13. const char* filename = argc >=2 ? argv[1] : "smarties.png";
  14. // Loads an image
  15. Mat src = imread( samples::findFile( filename ), IMREAD_COLOR );
  16. // Check if image is loaded fine
  17. if(src.empty()){
  18. printf(" Error opening image\n");
  19. printf(" Program Arguments: [image_name -- default %s] \n", filename);
  20. return EXIT_FAILURE;
  21. }
  22. //![load]
  23. //![convert_to_gray]
  24. Mat gray;
  25. cvtColor(src, gray, COLOR_BGR2GRAY);
  26. //![convert_to_gray]
  27. //![reduce_noise]
  28. medianBlur(gray, gray, 5);
  29. //![reduce_noise]
  30. //![houghcircles]
  31. vector<Vec3f> circles;
  32. HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
  33. gray.rows/16, // change this value to detect circles with different distances to each other
  34. 100, 30, 1, 30 // change the last two parameters
  35. // (min_radius & max_radius) to detect larger circles
  36. );
  37. //![houghcircles]
  38. //![draw]
  39. for( size_t i = 0; i < circles.size(); i++ )
  40. {
  41. Vec3i c = circles[i];
  42. Point center = Point(c[0], c[1]);
  43. // circle center
  44. circle( src, center, 1, Scalar(0,100,100), 3, LINE_AA);
  45. // circle outline
  46. int radius = c[2];
  47. circle( src, center, radius, Scalar(255,0,255), 3, LINE_AA);
  48. }
  49. //![draw]
  50. //![display]
  51. imshow("detected circles", src);
  52. waitKey();
  53. //![display]
  54. return EXIT_SUCCESS;
  55. }