@Fu Xianjun.All Rights Reserved.
匹配模板:多次选中
需要的图片:
代码如下:
import cv2
import numpy as np
img = cv2.imread("yinhua2.png")#读取原图
template = cv2.imread("yinhua.png")#读取模板
result=cv2.matchTemplate(img,template,cv2.TM_SQDIFF_NORMED)#进行模板匹配
h,w = template.shape[:2]#获取模板的宽和高
threshold =0.01 #定义阈值。 TM_SQDIFF_NORMED越接近于0越匹配
loc = np.where(result <= threshold)#匹配结果小于阈值的位置
print (*loc[::-1])
for pt in zip (*loc [::-1]):#遍历位置。zip把俩个我列表依次打包
right_bottom =(pt[0] + w,pt[1] + h)#右下角位置
cv2.rectangle(img,pt,right_bottom,(0,0,255),2)
cv2.imshow("img",img)
cv2.imshow("temlate",template)
cv2.waitKey()
cv2.destroyAllWindows()
代码结果: