Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีจับคู่ Key Points ของสองภาพด้วย OpenCV Java

เมธอด detect() ของคลาส org.opencv.features2d.Feature2D (abstract) ตรวจจับ key points ของภาพที่กำหนด ต้องส่งอ็อบเจ็กต์ Mat แทน source image และอ็อบเจ็กต์ MatOfKeyPoint ว่างเพื่อเก็บ key points

เมธอด drawMatches() ของคลาส org.opencv.features2d.Feature2D หาจุดตรงกันระหว่าง key points ของสองภาพและวาดออกมา เมธอดนี้รับพารามิเตอร์:

  • src1 - Mat object แทน first source image
  • keypoints1 - MatOfKeyPoint object แทน key points ของภาพแรก
  • src2 - Mat object แทน second source image
  • keypoints2 - MatOfKeyPoint object แทน key points ของภาพที่สอง
  • matches1to2 - Matches จากภาพแรกไปภาพที่สอง หมายถึง keypoints1[i] มี corresponding point ใน keypoints2[matches[i]]
  • dst - Mat object แทน destination image

ดังนั้น เพื่อจับคู่ key points ของสองภาพ:

  • อ่านภาพต้นทางสองภาพด้วย imread()
  • ดึง key points ของสองภาพด้วย detect()
  • หาและวาด matches ด้วย 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 {
        // โหลด OpenCV core library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        
        // อ่านภาพต้นทาง
        String file1 = "D:\\Images\\feature1.jpg";
        Mat src1 = Imgcodecs.imread(file1);
        String file2 = "D:\\Images\\feature2.jpg";
        Mat src2 = Imgcodecs.imread(file2);
        
        // สร้าง matrix ว่างสำหรับ destination image
        Mat dst = new Mat();
        
        FastFeatureDetector detector = FastFeatureDetector.create();
        
        // ตรวจจับ key points ในทั้งสองภาพ
        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

Image1 − วิธีจับคู่ Key Points ของสองภาพด้วย OpenCV Java

Image2 − วิธีจับคู่ Key Points ของสองภาพด้วย OpenCV Java

ผลลัพธ์

วิธีจับคู่ Key Points ของสองภาพด้วย OpenCV Java