Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/java/tutorial_code/features2D/feature_description/SURFMatchingDemo.java
16344 views
1
import org.opencv.core.Core;
2
import org.opencv.core.Mat;
3
import org.opencv.core.MatOfDMatch;
4
import org.opencv.core.MatOfKeyPoint;
5
import org.opencv.features2d.DescriptorMatcher;
6
import org.opencv.features2d.Features2d;
7
import org.opencv.highgui.HighGui;
8
import org.opencv.imgcodecs.Imgcodecs;
9
import org.opencv.xfeatures2d.SURF;
10
11
class SURFMatching {
12
public void run(String[] args) {
13
String filename1 = args.length > 1 ? args[0] : "../data/box.png";
14
String filename2 = args.length > 1 ? args[1] : "../data/box_in_scene.png";
15
Mat img1 = Imgcodecs.imread(filename1, Imgcodecs.IMREAD_GRAYSCALE);
16
Mat img2 = Imgcodecs.imread(filename2, Imgcodecs.IMREAD_GRAYSCALE);
17
if (img1.empty() || img2.empty()) {
18
System.err.println("Cannot read images!");
19
System.exit(0);
20
}
21
22
//-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors
23
double hessianThreshold = 400;
24
int nOctaves = 4, nOctaveLayers = 3;
25
boolean extended = false, upright = false;
26
SURF detector = SURF.create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright);
27
MatOfKeyPoint keypoints1 = new MatOfKeyPoint(), keypoints2 = new MatOfKeyPoint();
28
Mat descriptors1 = new Mat(), descriptors2 = new Mat();
29
detector.detectAndCompute(img1, new Mat(), keypoints1, descriptors1);
30
detector.detectAndCompute(img2, new Mat(), keypoints2, descriptors2);
31
32
//-- Step 2: Matching descriptor vectors with a brute force matcher
33
// Since SURF is a floating-point descriptor NORM_L2 is used
34
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE);
35
MatOfDMatch matches = new MatOfDMatch();
36
matcher.match(descriptors1, descriptors2, matches);
37
38
//-- Draw matches
39
Mat imgMatches = new Mat();
40
Features2d.drawMatches(img1, keypoints1, img2, keypoints2, matches, imgMatches);
41
42
HighGui.imshow("Matches", imgMatches);
43
HighGui.waitKey(0);
44
45
System.exit(0);
46
}
47
}
48
49
public class SURFMatchingDemo {
50
public static void main(String[] args) {
51
// Load the native OpenCV library
52
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
53
54
new SURFMatching().run(args);
55
}
56
}
57
58