MomentsDemo.java 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import java.awt.BorderLayout;
  2. import java.awt.Container;
  3. import java.awt.Image;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Random;
  7. import javax.swing.BoxLayout;
  8. import javax.swing.ImageIcon;
  9. import javax.swing.JFrame;
  10. import javax.swing.JLabel;
  11. import javax.swing.JPanel;
  12. import javax.swing.JSlider;
  13. import javax.swing.event.ChangeEvent;
  14. import javax.swing.event.ChangeListener;
  15. import org.opencv.core.Core;
  16. import org.opencv.core.CvType;
  17. import org.opencv.core.Mat;
  18. import org.opencv.core.MatOfPoint;
  19. import org.opencv.core.MatOfPoint2f;
  20. import org.opencv.core.Point;
  21. import org.opencv.core.Scalar;
  22. import org.opencv.core.Size;
  23. import org.opencv.highgui.HighGui;
  24. import org.opencv.imgcodecs.Imgcodecs;
  25. import org.opencv.imgproc.Imgproc;
  26. import org.opencv.imgproc.Moments;
  27. class MomentsClass {
  28. private Mat srcGray = new Mat();
  29. private JFrame frame;
  30. private JLabel imgSrcLabel;
  31. private JLabel imgContoursLabel;
  32. private static final int MAX_THRESHOLD = 255;
  33. private int threshold = 100;
  34. private Random rng = new Random(12345);
  35. public MomentsClass(String[] args) {
  36. //! [setup]
  37. /// Load source image
  38. String filename = args.length > 0 ? args[0] : "../data/stuff.jpg";
  39. Mat src = Imgcodecs.imread(filename);
  40. if (src.empty()) {
  41. System.err.println("Cannot read image: " + filename);
  42. System.exit(0);
  43. }
  44. /// Convert image to gray and blur it
  45. Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_BGR2GRAY);
  46. Imgproc.blur(srcGray, srcGray, new Size(3, 3));
  47. //! [setup]
  48. //! [createWindow]
  49. // Create and set up the window.
  50. frame = new JFrame("Image Moments demo");
  51. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  52. // Set up the content pane.
  53. Image img = HighGui.toBufferedImage(src);
  54. addComponentsToPane(frame.getContentPane(), img);
  55. //! [createWindow]
  56. // Use the content pane's default BorderLayout. No need for
  57. // setLayout(new BorderLayout());
  58. // Display the window.
  59. frame.pack();
  60. frame.setVisible(true);
  61. update();
  62. }
  63. private void addComponentsToPane(Container pane, Image img) {
  64. if (!(pane.getLayout() instanceof BorderLayout)) {
  65. pane.add(new JLabel("Container doesn't use BorderLayout!"));
  66. return;
  67. }
  68. JPanel sliderPanel = new JPanel();
  69. sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS));
  70. //! [trackbar]
  71. sliderPanel.add(new JLabel("Canny threshold: "));
  72. JSlider slider = new JSlider(0, MAX_THRESHOLD, threshold);
  73. slider.setMajorTickSpacing(20);
  74. slider.setMinorTickSpacing(10);
  75. slider.setPaintTicks(true);
  76. slider.setPaintLabels(true);
  77. slider.addChangeListener(new ChangeListener() {
  78. @Override
  79. public void stateChanged(ChangeEvent e) {
  80. JSlider source = (JSlider) e.getSource();
  81. threshold = source.getValue();
  82. update();
  83. }
  84. });
  85. //! [trackbar]
  86. sliderPanel.add(slider);
  87. pane.add(sliderPanel, BorderLayout.PAGE_START);
  88. JPanel imgPanel = new JPanel();
  89. imgSrcLabel = new JLabel(new ImageIcon(img));
  90. imgPanel.add(imgSrcLabel);
  91. Mat blackImg = Mat.zeros(srcGray.size(), CvType.CV_8U);
  92. imgContoursLabel = new JLabel(new ImageIcon(HighGui.toBufferedImage(blackImg)));
  93. imgPanel.add(imgContoursLabel);
  94. pane.add(imgPanel, BorderLayout.CENTER);
  95. }
  96. private void update() {
  97. //! [Canny]
  98. /// Detect edges using Canny
  99. Mat cannyOutput = new Mat();
  100. Imgproc.Canny(srcGray, cannyOutput, threshold, threshold * 2);
  101. //! [Canny]
  102. //! [findContours]
  103. /// Find contours
  104. List<MatOfPoint> contours = new ArrayList<>();
  105. Mat hierarchy = new Mat();
  106. Imgproc.findContours(cannyOutput, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
  107. //! [findContours]
  108. /// Get the moments
  109. List<Moments> mu = new ArrayList<>(contours.size());
  110. for (int i = 0; i < contours.size(); i++) {
  111. mu.add(Imgproc.moments(contours.get(i)));
  112. }
  113. /// Get the mass centers
  114. List<Point> mc = new ArrayList<>(contours.size());
  115. for (int i = 0; i < contours.size(); i++) {
  116. //add 1e-5 to avoid division by zero
  117. mc.add(new Point(mu.get(i).m10 / (mu.get(i).m00 + 1e-5), mu.get(i).m01 / (mu.get(i).m00 + 1e-5)));
  118. }
  119. //! [zeroMat]
  120. /// Draw contours
  121. Mat drawing = Mat.zeros(cannyOutput.size(), CvType.CV_8UC3);
  122. //! [zeroMat]
  123. //! [forContour]
  124. for (int i = 0; i < contours.size(); i++) {
  125. Scalar color = new Scalar(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256));
  126. Imgproc.drawContours(drawing, contours, i, color, 2);
  127. Imgproc.circle(drawing, mc.get(i), 4, color, -1);
  128. }
  129. //! [forContour]
  130. //! [showDrawings]
  131. /// Show in a window
  132. imgContoursLabel.setIcon(new ImageIcon(HighGui.toBufferedImage(drawing)));
  133. frame.repaint();
  134. //! [showDrawings]
  135. /// Calculate the area with the moments 00 and compare with the result of the OpenCV function
  136. System.out.println("\t Info: Area and Contour Length \n");
  137. for (int i = 0; i < contours.size(); i++) {
  138. System.out.format(" * Contour[%d] - Area (M_00) = %.2f - Area OpenCV: %.2f - Length: %.2f\n", i,
  139. mu.get(i).m00, Imgproc.contourArea(contours.get(i)),
  140. Imgproc.arcLength(new MatOfPoint2f(contours.get(i).toArray()), true));
  141. }
  142. }
  143. }
  144. public class MomentsDemo {
  145. public static void main(String[] args) {
  146. // Load the native OpenCV library
  147. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  148. // Schedule a job for the event dispatch thread:
  149. // creating and showing this application's GUI.
  150. javax.swing.SwingUtilities.invokeLater(new Runnable() {
  151. @Override
  152. public void run() {
  153. new MomentsClass(args);
  154. }
  155. });
  156. }
  157. }