1.下面的代码是在img中找template,只返回最匹配的
import cv2 def get_sing_loc(img, template): ''' methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] :return: ''' # 模板匹配 template_h, template_w, _ = template.shape method = cv2.TM_CCOEFF_NORMED res = cv2.matchTemplate(img, template, method) # 寻找最值 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + template_w, top_left[1] + template_h) return top_left, bottom_right
2.返回所有相似度查过阈值的匹配
import cv2 import numpy as np def get_sing_loc(img, template): ''' methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] :return: ''' # 模板匹配 template_h, template_w, _ = template.shape method = cv2.TM_CCOEFF_NORMED res = cv2.matchTemplate(img, template, method) threshold = 0.95 loc = np.where(res >= threshold) # np.where返回的坐标值(x,y)是(h,w),注意h,w的顺序 points = [] for pt in zip(*loc[::-1]): points.append(pt) return points