cv2.matchTemplate()函數的應用,匹配圖片后畫出矩形


import cv2 as cv
import numpy as np


"""
matchTemplate():
參數image:待搜索的圖像(大圖)
參數temple:搜索模板,需要和原圖一樣的數據類型且尺寸不能大於源圖像
參數result:比較結果的映射圖像,其必須為單通道,32位浮點型圖像,如果原圖(待搜索圖像)尺寸為W*H,而temple尺寸為w*h,則result尺寸一定是
    (W-w+1)*(H-h+1)
參數method:指定匹配方法,有如下幾種:
    CV_TM_SQDIFF:平方差匹配法
    CV_TM_SQDIFF_NORMED:歸一化平方差匹配法
    CV_TM_CCORR:相關匹配法
    CV_TM_CCORR_NORMED:歸一化相關匹配法
    CV_TM_CCOEFF:系數匹配法
    CV_TM_CCOEFF_NORMED:化相關系數匹配法
"""
"""
minMaxLoc()函數
作用:一維數組當作向量,尋找矩陣中最小值和最大值位置
"""

def match_image():
    target = cv.imread(r"C:\Users\lenovo\Desktop\test\2.jpg")
    temple = cv.imread(r"C:\Users\lenovo\Desktop\test\1.png")
    # shape是獲取矩陣的長度
    print(temple.shape)
    # 獲取到小圖的尺寸
    th, tw = temple.shape[:2]
    result = cv.matchTemplate(target, temple, cv.TM_SQDIFF_NORMED)
    # 返回匹配的最小坐標
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
    tl=min_loc
    print(tl)
    br = (int(tl[0]) + tw, int(tl[1]) + th)
    print('br==',br)
    cv.rectangle(target, tl, br, [0, 255, 0])
    cv.imshow("匹配結果" + np.str(cv.TM_SQDIFF_NORMED), target)


match_image()
cv.waitKey(0)
cv.destroyAllWindows()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM