OpenCV__Python模板匹配_教程16

大图里面找小图

#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys


#模板匹配方法1,SQDIFF
def match_sqdiff(tpl,target):
    th,tw,_ = tpl.shape
    dst = cv.matchTemplate(target,tpl,cv.TM_SQDIFF_NORMED)
    min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
    tl = min_loc
    #print(tl)
    br = (tl[0]+tw,tl[1]+th)
    cv.rectangle(target,tl,br,(0,0,255),2)
    return target

#模板匹配方法2,CCORR
def match_ccorr(tpl,target):
    th,tw,_ = tpl.shape
    dst = cv.matchTemplate(target,tpl,cv.TM_CCORR_NORMED)
    min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
    tl = max_loc
    #print(tl)
    br = (tl[0]+tw,tl[1]+th)
    cv.rectangle(target,tl,br,(0,0,255),2)
    return target


#模板匹配方法3,CCOEFF
def match_ccoeff(tpl,target):
    th,tw,_ = tpl.shape
    dst = cv.matchTemplate(target,tpl,cv.TM_CCOEFF_NORMED)
    min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
    tl = max_loc
    #print(tl)
    br = (tl[0]+tw,tl[1]+th)
    cv.rectangle(target,tl,br,(0,0,255),2)
    return target

def img_test():
    imgtpl = cv.imread('E:/chenopencvblogimg/zhuqiutpl.jpg')
    imgtarget = cv.imread('E:/chenopencvblogimg/zhuqiu.jpg')    
    #判断是否读取成功
    if imgtpl is None or imgtarget is None:
        print("Could not read the image,may be path error")
        return
    cv.namedWindow("origin imgtpl",cv.WINDOW_NORMAL)
    cv.imshow("origin imgtpl",imgtpl)
    cv.namedWindow("origin imgtarget",cv.WINDOW_NORMAL)
    cv.imshow("origin imgtarget",imgtarget)


    img_show = match_sqdiff(imgtpl,imgtarget)
    cv.namedWindow("match_sqdiff",cv.WINDOW_NORMAL)
    cv.imshow("match_sqdiff",img_show)

    img_show = match_ccorr(imgtpl,imgtarget)
    cv.namedWindow("match_ccorr",cv.WINDOW_NORMAL)
    cv.imshow("match_ccorr",img_show)

    img_show = match_ccoeff(imgtpl,imgtarget)
    cv.namedWindow("match_ccoeff",cv.WINDOW_NORMAL)
    cv.imshow("match_ccoeff",img_show)

    #让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
    cv.waitKey(0)
    #销毁窗口
    cv.destroyAllWindows()

if __name__ == '__main__':
    sys.exit(img_test() or 0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值