前言
首先,java使用opengCV4.4.0成功搞出来基于SIFT的图像匹配是很开心的,但是还是要吐槽几句下面这块都是吐槽,干货在下面,代码自取哈。
java是要凉了还是咋地,真的没人搞openCV了么,在网上找了快一个星期真就找不到能用的代码。要么是C++要么是Python,,,我吐了。
部分提供出来的代码也是旧的版本的,旧的我也忍了,代码拿过来还是用不了!说是因为版权原因不能直接用,需要去官网拿opencv_contrib 源码自己去编译!但是opencv的模板匹配图像又不能满足我的需求!就只能去度娘看能不能白嫖到了。
网上能找到编译好的,但是版本又低,我又不确定是不是编译的jar,又要收费!我这么抠的人会去搞知识付费么?照着攻略自己干!结果看到要准备的一大堆软件,我又又吐了,,,。然后转身发现4.4.0自带SIFT算法,不需要编译!可是网上找不到能用的代码!于是根据折腾了大半个星期的积累尝试自己动手!
openCV的安装与使用应该不用说吧,都走到这一步了,en,应该是不用说了【主要是懒】
先看效果
原图
模板图 模板图有做缩放和旋转处理
匹配过程
匹配结果
再看代码
public void matchImage(BufferedImage templateImageB, BufferedImage originalImageB) {
Mat resT = new Mat();
Mat resO = new Mat();
//即当detector 又当Detector
SIFT sift = SIFT.create();
Mat templateImage = getMatify(templateImageB);
Mat originalImage = getMatify(originalImageB);
MatOfKeyPoint templateKeyPoints = new MatOfKeyPoint();
MatOfKeyPoint originalKeyPoints = new MatOfKeyPoint();
//获取模板图的特征点
sift.detect(templateImage, templateKeyPoints);
sift.detect(originalImage, originalKeyPoints);
sift.compute(templateImage, templateKeyPoints, resT);
sift.compute(originalImage, originalKeyPoints, resO);
List<MatOfDMatch> matches = new LinkedList();
DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
System.out.println("寻找最佳匹配");
printPic("ptest", templateImage);
printPic("ptesO", originalImage);
printPic("test", resT);
printPic("tesO", resO);
/**
* knnMatch方法的作用就是在给定特征描述集合中寻找最佳匹配
* 使用KNN-matching算法,令K=2,则每个match得到两个最接近的descriptor,然后计算最接近距离和次接近距离之间的比值,当比值大于既定值时,才作为最终match。
*/
descriptorMatcher.knnMatch(resT, resO, matches, 2);
System.out.println("计算匹配结果");
LinkedList<DMatch> goodMatchesList = new LinkedList();
//对匹配结果进行筛选,依据distance进行筛选
matches.forEach(match -> {
DMatch