Path: blob/master/samples/java/tutorial_code/features2D/feature_description/SURFMatchingDemo.java
16344 views
import org.opencv.core.Core;1import org.opencv.core.Mat;2import org.opencv.core.MatOfDMatch;3import org.opencv.core.MatOfKeyPoint;4import org.opencv.features2d.DescriptorMatcher;5import org.opencv.features2d.Features2d;6import org.opencv.highgui.HighGui;7import org.opencv.imgcodecs.Imgcodecs;8import org.opencv.xfeatures2d.SURF;910class SURFMatching {11public void run(String[] args) {12String filename1 = args.length > 1 ? args[0] : "../data/box.png";13String filename2 = args.length > 1 ? args[1] : "../data/box_in_scene.png";14Mat img1 = Imgcodecs.imread(filename1, Imgcodecs.IMREAD_GRAYSCALE);15Mat img2 = Imgcodecs.imread(filename2, Imgcodecs.IMREAD_GRAYSCALE);16if (img1.empty() || img2.empty()) {17System.err.println("Cannot read images!");18System.exit(0);19}2021//-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors22double hessianThreshold = 400;23int nOctaves = 4, nOctaveLayers = 3;24boolean extended = false, upright = false;25SURF detector = SURF.create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright);26MatOfKeyPoint keypoints1 = new MatOfKeyPoint(), keypoints2 = new MatOfKeyPoint();27Mat descriptors1 = new Mat(), descriptors2 = new Mat();28detector.detectAndCompute(img1, new Mat(), keypoints1, descriptors1);29detector.detectAndCompute(img2, new Mat(), keypoints2, descriptors2);3031//-- Step 2: Matching descriptor vectors with a brute force matcher32// Since SURF is a floating-point descriptor NORM_L2 is used33DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE);34MatOfDMatch matches = new MatOfDMatch();35matcher.match(descriptors1, descriptors2, matches);3637//-- Draw matches38Mat imgMatches = new Mat();39Features2d.drawMatches(img1, keypoints1, img2, keypoints2, matches, imgMatches);4041HighGui.imshow("Matches", imgMatches);42HighGui.waitKey(0);4344System.exit(0);45}46}4748public class SURFMatchingDemo {49public static void main(String[] args) {50// Load the native OpenCV library51System.loadLibrary(Core.NATIVE_LIBRARY_NAME);5253new SURFMatching().run(args);54}55}565758