接着上一篇:https://blog.csdn.net/qq_34717531/article/details/107402545
7.模板匹配
import cv2
import numpy as np
import cv2
import numpy as np
img_rgb = cv2.imread('timg.jpeg')#读取原图
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)#转灰度图
template = cv2.imread('hat.jpg',0)#读取要匹配的图
w, h = template.shape[::-1]#获取匹配图的宽,高
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)#做匹配
threshold = 0.7
loc = np.where( res >= threshold)#找到阀值大于0.7的位置
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)#画矩形框
#cv2.rectangle()参数: 图像,左上角坐标,右下角坐标,颜色, 线条粗细。
cv2.imshow('Detected',img_rgb)
cv2.imwrite('0.7.jpg',img_rgb)