如何使用 OpenCV Java 库匹配两张图像的关键点?


org.opencv.features2d.Feature2D(抽象)类的detect()方法检测给定图像的关键点。此方法需要传递一个表示源图像的Mat对象和一个空MatOfKeyPoint对象来保存读取的关键点。

org.opencv.features2d.Feature2D类的drawMatches()方法查找两个给定图像的关键点之间的匹配项并绘制它们。此方法接受以下参数:

  • src1 - 表示第一个源图像的Mat类对象。

  • keypoints1 - 表示第一个源图像的关键点的MatOfKeyPoint类对象。

  • src2 - 表示第二个源图像的Mat类对象。

  • keypoints2 - 表示第二个源图像的关键点的MatOfKeyPoint类对象。

  • matches1to2 - 从第一个图像到第二个图像的匹配项,这意味着 keypoints1[i] 在 keypoints2[matches[i]] 中有一个对应的点。

  • dst - 表示目标图像的Mat类对象。

因此,要匹配两张图像的关键点,需要:

  • 使用imread()方法读取两个源图像。

  • 使用detect()方法获取两个图像的关键点。

  • 使用drawMatches()方法查找并绘制匹配项。

示例

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();
   }
}

输入图像

图像1 -

 

图像2 -

输出

更新于: 2020-04-10

846 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.