import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.DMatch;
导入 org.opencv.core.Mat;
导入 org.opencv.core.MatOfByte;
导入 org.opencv.core.MatOfDMatch;
导入 org.opencv.core.MatOfKeyPoint;
导入 org.opencv.core.Scalar;
导入 org.opencv.features2d.DescriptorMatcher;
导入 org.opencv.features2d.Features2d;
导入 org.opencv.highgui.HighGui;
导入 org.opencv.imgcodecs.Imgcodecs;
导入 org.opencv.xfeatures2d.SURF;
类 SURFFLANNMatching {
公共无效运行(字符串[] args) {
字符串 filename1 = args.length > 1 ? args[0] : "../data/box.png";
字符串 filename2 = args.length > 1 ? args[1] : "../data/box_in_scene.png";
Mat img1 = Imgcodecs.imread(filename1, Imgcodecs.IMREAD_GRAYSCALE);
Mat img2 = Imgcodecs.imread(filename2, Imgcodecs.IMREAD_GRAYSCALE);
如果 (img1.empty() || img2.empty()) {
System.err.println("无法读取图像!");
System.exit(0);
}
双精度 hessianThreshold = 400;
整数 nOctaves = 4, nOctaveLayers = 3;
布尔 extended = 假, upright = 假;
SURF detector = SURF.create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright);
MatOfKeyPoint keypoints1 = 新 MatOfKeyPoint(), keypoints2 = 新 MatOfKeyPoint();
Mat descriptors1 = 新 Mat(), descriptors2 = 新 Mat();
detector.detectAndCompute(img1, 新 Mat(), keypoints1, descriptors1);
detector.detectAndCompute(img2, 新 Mat(), keypoints2, descriptors2);
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
列表<MatOfDMatch> knnMatches = 新 ArrayList<>();
matcher.knnMatch(descriptors1, descriptors2, knnMatches, 2);
浮点数 ratioThresh = 0.7f;
列表<DMatch> listOfGoodMatches = 新 ArrayList<>();
对于 (整数 i = 0; i < knnMatches.size(); i++) {
如果 (knnMatches.get(i).rows() > 1) {
DMatch[] matches = knnMatches.get(i).toArray();
如果 (matches[0].distance < ratioThresh * matches[1].distance) {
listOfGoodMatches.add(matches[0]);
}
}
}
MatOfDMatch goodMatches = 新 MatOfDMatch();
goodMatches.fromList(listOfGoodMatches);
Mat imgMatches = 新 Mat();
Features2d.drawMatches(img1, keypoints1, img2, keypoints2, goodMatches, imgMatches, Scalar.all(-1),
Scalar.all(-1), 新 MatOfByte(), Features2d.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS);
HighGui.imshow("良好匹配", imgMatches);
HighGui.waitKey(0);
System.exit(0);
}
}
公共类 SURFFLANNMatchingDemo {
公共静态无效主函数(字符串[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
新 SURFFLANNMatching().run(args);
}
}
静态 Scalar_< _Tp > all(_Tp v0)
返回所有元素都设置为 v0 的标量
Scalar_< double > Scalar
**定义** types.hpp:709