1, the target matching function: cv2.matchTemplate ()
res=cv2.matchTemplate(image, templ, method, result=None, mask=None)
image: Image to be searched
templ: Template image
result: Match result
method: The method of calculating the degree of matching, there are the following
method | meaning |
---|---|
CV_TM_SQDIFF | Squared difference matching method: The method uses matching square difference; best match is 0; matching worse, the larger a matching value. |
CV_TM_CCORR | Related matching method: The method uses the multiplication operation; A greater value indicates better degree of matching. |
CV_TM_CCOEFF | Correlation matching method: 1 indicates a perfect match; -1 indicates the worst match. |
CV_TM_SQDIFF_NORMED | Computing a normalized square is different, the calculated value is closer to 0, the more relevant |
CV_TM_CCORR_NORMED | Calcd normalized correlation calculated closer to 1, the more relevant |
CV_TM_CCOEFF_NORMED | Normalized correlation coefficient is calculated, the calculated value is closer to 1, the more relevant |
2, obtaining results matching function: cv2.minMaxLoc ()
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(ret)
Parameters: min_val, max_val, min_loc, max_loc represent the minimum, maximum, and minimum and maximum values of the corresponding position in the image, that is, RET cv2.matchTemplate () function returns a matrix
# 模板匹配
img = cv2.imread('lena.jpg', 0)
template = cv2.imread('face.jpg', 0)
h, w = template.shape[:2]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
res = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
for meth in methods:
img2 = img.copy()
# 匹配方法的真值
method = eval(meth)
res = cv2.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 如果是平方差匹配TM_SQDIFF或归一化平方差匹配TM_SQDIFF_NORMED,取最小值
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
# 画矩形
cv2.rectangle(img2, top_left, bottom_right, 255, 2)
plt.subplot(121), plt.imshow(res, cmap='gray')
plt.xticks([]), plt.yticks([]) # 隐藏坐标轴
plt.subplot(122), plt.imshow(img2, cmap='gray')
plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
Multi-object matching: We are matching the figure of gold, read two pictures are original and gold template
img_rgb = cv2.imread('mario.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.jpg', 0)
h, w = template.shape[:2]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
# 取匹配程度大于%80的坐标
loc = np.where(res >= threshold)
#np.where返回的坐标值(x,y)是(h,w),注意h,w的顺序
for pt in zip(*loc[::-1]):
bottom_right = (pt[0] + w, pt[1] + h)
cv2.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2)
cv2.imshow('img_rgb', img_rgb)
cv2.waitKey(0)