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()
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yM3MmZzU2N2ADO0AjMiVWOxgTNwQDZ1cTOzIWO0IWOl9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.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;
}
模闆比對被稱為最簡單的模式識别方法、同時也被很多人認為是最沒有用的模式識别方法。這裡裡面有很大的誤區,就是模闆比對是工作條件限制比較嚴格,隻有滿足理論設定的條件以後,模闆比對才會比較好的開始工作,而且它不是基于特征的比對,是以有很多弊端,但是不妨礙它成為入門級别模式識别的方法,通過它可以學習到很多相關的原理性内容,為後續學習打下良好的基礎。
OpenCV學習筆記代碼,歡迎follow:
MachineLP/OpenCV-github.com