Skip to content

Instantly share code, notes, and snippets.

@aimerneige
Last active May 13, 2022 15:18
Show Gist options
  • Save aimerneige/f886f6c39c8b0aab3e60346a75c6e4fd to your computer and use it in GitHub Desktop.
Save aimerneige/f886f6c39c8b0aab3e60346a75c6e4fd to your computer and use it in GitHub Desktop.
模板匹配
# -*- coding: utf-8 -*-
import cv2
import numpy as np
# 读入图片
img = cv2.imread("./img.jpg")
roi = cv2.imread('./roi.jpg', 0)
# 转化为灰度图
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 展示图像
cv2.imshow("origin", img)
cv2.imshow("roi", roi)
# 模板匹配
res = cv2.matchTemplate(img_gray, roi, cv2.TM_CCOEFF_NORMED)
# 模板图片尺寸
r, c = roi.shape
# 匹配最大值并使用红色框出
_, _, _, maxLoc = cv2.minMaxLoc(res)
x, y = maxLoc
cv2.rectangle(img, (x, y), (x + c, y + r), (0, 0, 255), 3)
# 阈值
threshold = 0.7
# 过滤出匹配程度大于阈值的结果
locs = np.where(res >= threshold)
# 将全部结果用蓝色框出
for point in zip(*locs[::-1]):
x, y = point
cv2.rectangle(img, (x, y), (x+c, y+r), (255, 0, 0), 1)
# 显示结果
cv2.imshow('result', img)
# 将结果保存为文件
cv2.imwrite('./result.jpg', img)
# 等待用户关闭窗口
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment