How to match the key points of two images using OpenCV Java library?


The detect() method of the org.opencv.features2d.Feature2D (abstract) class detects the key points of the given image. To this method, you need to pass a Mat object representing the source image and an empty MatOfKeyPoint object to hold the read key points.

The drawMatches() method of the org.opencv.features2d.Feature2D class finds the matches between the key points of the two given images and draws them. This method accepts the following parameters −

  • src1 − An object of the Mat class representing the first source image.

  • keypoints1 − An object of the MatOfKeyPoint class representing the Key points of the first source image.

  • src2 − An object of the Mat class representing the second source image.

  • keypoints2 − An object of the MatOfKeyPoint class representing the Key points of the second source image.

  • matches1to2 − Matches from the first image to the second one, which means that keypoints1[i] has a corresponding point in keypoints2[matches[i]].

  • dst − An object of the Mat class representing the destination image.

Therefore, to match the key points of two images −

  • Read the two source images using the imread() method.

  • Get the key points of the two images using the detect() method.

  • Find and draw the matches using the drawMatches() method.

Example

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.features2d.FastFeatureDetector;
import org.opencv.features2d.Features2d;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
public class MatchingKeypoints {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the source images
      String file1 ="D:\Images\feature1.jpg";
      Mat src1 = Imgcodecs.imread(file1);
      String file2 ="D:\Images\feature2.jpg";
      Mat src2 = Imgcodecs.imread(file2);
      //Creating an empty matrix to store the destination image
      Mat dst = new Mat();
      FastFeatureDetector detector = FastFeatureDetector.create();
      //Detecting the key points in both images
      MatOfKeyPoint keyPoints1 = new MatOfKeyPoint();
      detector.detect(src1, keyPoints1);
      MatOfKeyPoint keyPoints2 = new MatOfKeyPoint();
      detector.detect(src2, keyPoints2);
      MatOfDMatch matof1to2 = new MatOfDMatch();
      Features2d.drawMatches(src1, keyPoints1, src2, keyPoints2, matof1to2, dst);
      HighGui.imshow("Feature Matching", dst);
      HighGui.waitKey();
   }
}

Input Images

Image1

 

Image2 − 

Output

Updated on: 10-Apr-2020

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements