Opencv模板匹配(Template)

import cv2

global method = 

img = cv2.imread(img_path)

template = cv2.imread(img_path)

 

def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def get_match_rec(template, img, method):
    # 计算出模板宽高
    th, tw = template.shape[:2]
    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]+tw, top_left[1] + th)
    return top_left, bottom_right


template = cv2.imread(template_path)
img = cv2.imread(img_path)

top_left, bottom_right = get_match_rec(img, template, method=cv2.TM_CCOEFF)
print(top_left)
cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
# 裁剪匹配区域
crop_img = img[top_left[1]:(top_left[1]+ template.shape[0]),
                top_left[0]:(top_left[0] + template.shape[1])]

cv_show('template',crop_img)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值