SURFMatchingDemo.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. class SURFMatching {
  11. public void run(String[] args) {
  12. String filename1 = args.length > 1 ? args[0] : "../data/box.png";
  13. String filename2 = args.length > 1 ? args[1] : "../data/box_in_scene.png";
  14. Mat img1 = Imgcodecs.imread(filename1, Imgcodecs.IMREAD_GRAYSCALE);
  15. Mat img2 = Imgcodecs.imread(filename2, Imgcodecs.IMREAD_GRAYSCALE);
  16. if (img1.empty() || img2.empty()) {
  17. System.err.println("Cannot read images!");
  18. System.exit(0);
  19. }
  20. //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors
  21. double hessianThreshold = 400;
  22. int nOctaves = 4, nOctaveLayers = 3;
  23. boolean extended = false, upright = false;
  24. SURF detector = SURF.create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright);
  25. MatOfKeyPoint keypoints1 = new MatOfKeyPoint(), keypoints2 = new MatOfKeyPoint();
  26. Mat descriptors1 = new Mat(), descriptors2 = new Mat();
  27. detector.detectAndCompute(img1, new Mat(), keypoints1, descriptors1);
  28. detector.detectAndCompute(img2, new Mat(), keypoints2, descriptors2);
  29. //-- Step 2: Matching descriptor vectors with a brute force matcher
  30. // Since SURF is a floating-point descriptor NORM_L2 is used
  31. DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE);
  32. MatOfDMatch matches = new MatOfDMatch();
  33. matcher.match(descriptors1, descriptors2, matches);
  34. //-- Draw matches
  35. Mat imgMatches = new Mat();
  36. Features2d.drawMatches(img1, keypoints1, img2, keypoints2, matches, imgMatches);
  37. HighGui.imshow("Matches", imgMatches);
  38. HighGui.waitKey(0);
  39. System.exit(0);
  40. }
  41. }
  42. public class SURFMatchingDemo {
  43. public static void main(String[] args) {
  44. // Load the native OpenCV library
  45. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  46. new SURFMatching().run(args);
  47. }
  48. }