版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
模版图片在另一幅图进行匹配
函数:matchTemplate在模板块和输入图像之间寻找匹配,获得匹配结果图像
函数 :minMaxLoc在给定的矩阵中寻找最大和最小值(包括它们的位置)
@Test
public static void matchImg() {
String templateImgPath = "/Users/wuxi/Desktop/tem.png";
String originalImgPath = "/Users/wuxi/Desktop/origin.png";
Mat originalImg = Imgcodecs.imread(originalImgPath, 0);
Mat templateImg = Imgcodecs.imread(templateImgPath, 0);
Mat result = originalImg.clone();
//CV_TM_CCOEFF_NORMED 值越大越匹配
Imgproc.matchTemplate(originalImg, templateImg, result, Imgproc.TM_CCOEFF_NORMED);
//获得最匹配矩阵
Core.MinMaxLocResult mmlr = Core.minMaxLoc(result);
//最大为1
System.out.println(mmlr.maxVal);
//归一化匹配结果
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
//获取矩阵左上角坐标
Point matchLocation = mmlr.maxLoc;
System.out.println(matchLocation.toString());
//画出匹配到的边界矩形
//矩形的右下角坐标 x+该矩阵的列,y+矩阵的行
Imgproc.rectangle(originalImg, matchLocation,
new Point(matchLocation.x + templateImg.cols(), matchLocation.y + templateImg.rows()),
new Scalar(0, 0, 0, 0), 2);
Imgcodecs.imwrite("/Users/wuxi/Pictures/originalImg.jpg", originalImg);
if (mmlr.maxVal >= 0.9) {
System.out.println("匹配成功");
} else {
System.out.println("匹配失败");
}
}
执行结果:
最后查看画出的矩形
opencv官网找出
绘制矩形:
参考: