OpenCV 模板匹配

模板匹配

核心语法

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)

实例:查找docx文件图标

  1 import cv2
  2 import numpy as np
  3 
  4 img_bgr = cv2.imread('./target.png')
  5 img_gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY)
  6 
  7 template = cv2.imread('./template.png',0)
  8 w,h = template.shape[::-1]		#确定捕捉框长宽
  9 
 10 res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
 11 threshold = 0.8		#越高越准,越小越多
 12 loc = np.where(res>=threshold)
 13 
 14 for pt in zip(*loc[::-1]):
 15     cv2.rectangle(img_bgr,pt,(pt[0]+w,pt[1]+h),(0,255,0),2)
 16 
 17 result = cv2.resize(img_bgr,None,fx=1,fy=1)
 18 cv2.imshow('detected',result)
 19 cv2.waitKey()
 20 cv2.destroyAllWindows()                          

捕捉效果

实测阈值低时可以检测到左侧doc文件。
OpenCV 模板匹配_第1张图片

你可能感兴趣的:(Python,OpenCV,opencv,python)