python 影像與影像模型匹配

Como0413發表於2019-03-07
#-*- coding: utf-8 -*-

import os
import cv2 as cv
import numpy as np

tpl = cv.imdecode(np.fromfile("static/ym.jpg",dtype=np.uint8),1)
cv.imshow("ym", tpl)
target = cv.imdecode(np.fromfile("static/3.jpg",dtype=np.uint8),1)
# methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]   #3種模板匹配方法
methods = cv.TM_SQDIFF_NORMED
th, tw = tpl.shape[:2]
#模板匹配
result = cv.matchTemplate(target, tpl, methods)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
if methods == cv.TM_SQDIFF_NORMED:
    tl = min_loc
else:
    tl = max_loc
br = (tl[0]+tw, tl[1]+th)   #br是矩形右下角的點的座標
cv.putText(target,str([tl[0]+(tw/2),br[1]]), (tl), cv.FONT_HERSHEY_SIMPLEX, 2, (98, 170, 255), 2)
cv.rectangle(target, tl, br, (0, 255, 0), 2)
img = target[:tl[1]+th,:]
cv.namedWindow("match" ,cv.WINDOW_NORMAL)
cv.imshow("match" , target)
cv.waitKey(0)
cv.destroyAllWindows()

顯示結果如下:

相關文章