python opencv图像匹配 matchTemplate函数

算法思路

将目标图像在源图像中滑动,计算两个相同大小图像的距离,最后根据距离最小的位置作为匹配结果
其中计算图像距离的算法有多种:TM_SQDIFFTM_SQDIFF_NORMED详细见opencv官网
算法很简单,只用用在图像没有发生变形的情况下

代码

import cv2

def match_image(source, template):
    # 选择匹配算法
    match_method = cv2.TM_SQDIFF

    result = cv2.matchTemplate(source, template, match_method)
    cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)
    # 概率图
    cv2.imshow("rate", result)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result, None)
    if match_method == cv2.TM_SQDIFF or match_method == cv2.TM_SQDIFF_NORMED:
        match_loc = min_loc
    else:
        match_loc = max_loc
    return match_loc


template = cv2.imread("dog.png")
img = cv2.imread("img.png")

location = match_image(img, template)
pt1 = (int(location[0]), int(location[1]))
x = location[0] + img.shape[1] / 2
y = location[1] + img.shape[0] / 2
pt2 = (int(x), int(y))
cv2.rectangle(img, pt1, pt2, (255, 0, 0), 2)
cv2.imshow("img", img)
cv2.waitKey(0)

匹配结果

python opencv图像匹配 matchTemplate函数_第1张图片

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