Python+OpenCV圖像處理之模板匹配


模板匹配就是在整個圖像區域中發現與給定子圖像匹配的小塊區域

在OpenCV中,提供了相應的函數完成這個操作:

matchTemplate 函數:在模板和輸入圖像之間尋找匹配,獲得匹配結果圖像 
minMaxLoc 函數:在給定的矩陣中尋找最大和最小值,並給出它們的位置

幾種常見的模板匹配算法:

①TM_SQDIFF是平方差匹配;TM_SQDIFF_NORMED是標准平方差匹配。利用平方差來進行匹配,最好匹配為0.匹配越差,匹配值越大。

②TM_CCORR是相關性匹配;TM_CCORR_NORMED是標准相關性匹配。采用模板和圖像間的乘法操作,數越大表示匹配程度較高, 0表示最壞的匹配效果。

③TM_CCOEFF是相關性系數匹配;TM_CCOEFF_NORMED是標准相關性系數匹配。將模版對其均值的相對值與圖像對其均值的相關值進行匹配,1表示完美匹配,-1表示糟糕的匹配,0表示沒有任何相關性(隨機序列)。

python實現

import cv2
import numpy as np

__author__ = "boboa"


def template_demo():
    tpl = cv2.imread("image/tpl.jpg")
    target = cv2.imread("image/target1.jpg")
    # cv2.imshow("template_image", tpl)
    # cv2.imshow("target image", target)
    methods = [cv2.TM_CCOEFF_NORMED, cv2.TM_SQDIFF_NORMED, cv2.TM_CCORR_NORMED]
    th, tw = tpl.shape[:2]
    for md in methods:
        print(md)
        result = cv2.matchTemplate(target, tpl, md)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        if md == cv2.TM_SQDIFF_NORMED:
            tl = min_loc
        else:
            tl = max_loc
        br = (tl[0] + tw, tl[1] + th)
        cv2.rectangle(target, tl, br, (0, 0, 255), 2)
        cv2.imshow("match-" + np.str(md), target)


if __name__ == "__main__":
    img = cv2.imread("img1.jpg")
    # cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
    # cv2.imshow("input image", img)
    template_demo()
    cv2.waitKey(0)
    cv2.destroyAllWindows()

運行結果

 


免責聲明!

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



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