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()
相關文章
相關標籤/搜索