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