python代码:

import cv2 as cv
import numpy as np


def template_demo():
    src = cv.imread("./test.png")
    tpl = cv.imread("./test01.png")
    cv.imshow("input", src)
    cv.imshow("tpl", tpl)
    th, tw = tpl.shape[:2]
    result = cv.matchTemplate(src, tpl, cv.TM_CCORR_NORMED)
    cv.imshow("result", result)
    cv.imwrite("D:/039_003.png", np.uint8(result*255))
    t = 0.98
    loc = np.where(result > t)

    for pt in zip(*loc[::-1]):
        cv.rectangle(src, pt, (pt[0] + tw, pt[1] + th), (255, 0, 0), 1, 8, 0)
    cv.imshow("llk-demo", src)
    cv.imwrite("D:/039_004.png", src)


template_demo()
cv.waitKey(0)
cv.destroyAllWindows()

e9b49b3975d405819eb2048067e3fc73.png

C++代码:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;
const float t = 0.95;
int main(int artc, char** argv) {
	Mat src = imread("./test01.png");
	Mat tpl = imread("./test.png");
	if (src.empty() || tpl.empty()) {
		printf("could not load image...n");
		return -1;
	}
	imshow("input", src);
	imshow("tpl", tpl);

	int result_h = src.rows - tpl.rows + 1;
	int result_w = src.cols - tpl.cols + 1;
	Mat result = Mat::zeros(Size(result_w, result_h), CV_32FC1);
	matchTemplate(src, tpl, result, TM_CCOEFF_NORMED);
	imshow("result image", result);
	int h = result.rows;
	int w = result.cols;
	for (int row = 0; row < h; row++) {
		for (int col = 0; col < w; col++) {
			float v = result.at<float>(row, col);
			// printf("v = %.2fn", v);
			if (v > t) {
				rectangle(src, Point(col, row), Point(col + tpl.cols, row + tpl.rows), Scalar(255, 0, 0), 1, 8, 0);
			}
		}
	}
	imshow("template matched result", src);

	waitKey(0);
	return 0;
}

模板匹配被称为最简单的模式识别方法、同时也被很多人认为是最没有用的模式识别方法。这里里面有很大的误区,就是模板匹配是工作条件限制比较严格,只有满足理论设置的条件以后,模板匹配才会比较好的开始工作,而且它不是基于特征的匹配,所以有很多弊端,但是不妨碍它成为入门级别模式识别的方法,通过它可以学习到很多相关的原理性内容,为后续学习打下良好的基础。

f81c4167acd5f115bb347818774e7b26.png

OpenCV学习笔记代码,欢迎follow:

MachineLP/OpenCV-​github.com
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐