HoughCircles.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package sample;
  2. /**
  3. * @file HoughCircles.java
  4. * @brief This program demonstrates circle finding with the Hough transform
  5. */
  6. import org.opencv.core.*;
  7. import org.opencv.core.Point;
  8. import org.opencv.highgui.HighGui;
  9. import org.opencv.imgcodecs.Imgcodecs;
  10. import org.opencv.imgproc.Imgproc;
  11. class HoughCirclesRun {
  12. public void run(String[] args) {
  13. //! [load]
  14. String default_file = "../../../../data/smarties.png";
  15. String filename = ((args.length > 0) ? args[0] : default_file);
  16. // Load an image
  17. Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);
  18. // Check if image is loaded fine
  19. if( src.empty() ) {
  20. System.out.println("Error opening image!");
  21. System.out.println("Program Arguments: [image_name -- default "
  22. + default_file +"] \n");
  23. System.exit(-1);
  24. }
  25. //! [load]
  26. //! [convert_to_gray]
  27. Mat gray = new Mat();
  28. Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
  29. //! [convert_to_gray]
  30. //![reduce_noise]
  31. Imgproc.medianBlur(gray, gray, 5);
  32. //![reduce_noise]
  33. //! [houghcircles]
  34. Mat circles = new Mat();
  35. Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
  36. (double)gray.rows()/16, // change this value to detect circles with different distances to each other
  37. 100.0, 30.0, 1, 30); // change the last two parameters
  38. // (min_radius & max_radius) to detect larger circles
  39. //! [houghcircles]
  40. //! [draw]
  41. for (int x = 0; x < circles.cols(); x++) {
  42. double[] c = circles.get(0, x);
  43. Point center = new Point(Math.round(c[0]), Math.round(c[1]));
  44. // circle center
  45. Imgproc.circle(src, center, 1, new Scalar(0,100,100), 3, 8, 0 );
  46. // circle outline
  47. int radius = (int) Math.round(c[2]);
  48. Imgproc.circle(src, center, radius, new Scalar(255,0,255), 3, 8, 0 );
  49. }
  50. //! [draw]
  51. //! [display]
  52. HighGui.imshow("detected circles", src);
  53. HighGui.waitKey();
  54. //! [display]
  55. System.exit(0);
  56. }
  57. }
  58. public class HoughCircles {
  59. public static void main(String[] args) {
  60. // Load the native library.
  61. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  62. new HoughCirclesRun().run(args);
  63. }
  64. }