def find_match(img, tmpl, rect=None, mask=None):
if rect is not None:
h, w = img.shape[:2]
x, y, x1, y1 = rect
if x1 > w or y1 > h:
return 0, None
img = img[y:y1, x:x1, :]
if mask is not None:
img = img.copy()
img[mask!=0] = 0
tmpl = tmpl.copy()
tmpl[mask!=0] = 0
s_bgr = cv2.split(tmpl) # Blue Green Red
i_bgr = cv2.split(img)
weight = (0.3, 0.3, 0.4)
resbgr = [0, 0, 0]
for i in range(3): # bgr
resbgr[i] = cv2.matchTemplate(i_bgr[i], s_bgr[i], cv2.TM_CCOEFF_NORMED)
match = resbgr[0]*weight[0] + resbgr[1]*weight[1] + resbgr[2]*weight[2]
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(match)
confidence = max_val
x, y = max_loc
h, w = tmpl.shape[:2]
if rect is None:
rect = (x, y, x+w, y+h)
# cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0) ,2)
# cv2.imshow('test', img)
# cv2.waitKey(20)
return confidence, rect
评论列表
文章目录