opencv 模板匹配_OpenCV之图像模板匹配

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()

opencv 模板匹配_OpenCV之图像模板匹配_第1张图片

C++代码:

#include 
#include 

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(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 模板匹配_OpenCV之图像模板匹配_第2张图片

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

MachineLP/OpenCV-​github.com

你可能感兴趣的:(opencv,模板匹配,opencv,模板匹配带角度,opencv模板匹配,opencv模板匹配优化)