Python+OpenCV|テンプレート・マッチング

Python+OpenCV

入力画像

テンプレート画像

SSD

%matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
img = cv2.imread('../haruna_kankore.png')
gray=cv2.imread('../haruna_kankore.png', 0)

#テンプレート
temp = cv2.imread('../haruna_kankore_temp.png', 0)

h, w = temp.shape

match = cv2.matchTemplate(gray, temp, cv2.TM_SQDIFF)
min_value, max_value, min_pt, max_pt = cv2.minMaxLoc(match)
pt = min_pt

cv2.rectangle(img, (pt[0], pt[1]), (pt[0] + w, pt[1] + h), (0, 0, 200), 3)
cv2.imwrite('Template_matching_SSD.png', img)

ZNCC

%matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
img = cv2.imread('../haruna_kankore.png')
gray=cv2.imread('../haruna_kankore.png', 0)

#テンプレート
temp = cv2.imread('../haruna_kankore_temp.png', 0)

h, w = temp.shape

match = cv2.matchTemplate(gray, temp, cv2.TM_CCOEFF_NORMED)
min_value, max_value, min_pt, max_pt = cv2.minMaxLoc(match)
pt = max_pt

cv2.rectangle(img, (pt[0], pt[1]), (pt[0] + w, pt[1] + h), (0, 0, 200), 3)
cv2.imwrite('Template_matching_ZNCC.png', img)

出力結果

SSD

ZNCC

計算式

SSD

SSD(Sum of Squared Difference)

$$\displaystyle \sum \displaystyle \sum {I(dx+x,dy+y)T(x,y)}^2$$

SAD

SAD(Sum of Absolute Difference)
$$\displaystyle \sum \displaystyle \sum |I(dx+x,dy+y) – T(x,y)|$$

NCC

NCC(Normalized Cross Correlation)
$$\displaystyle \frac{ \displaystyle \sum \displaystyle \sum I(dx+x,dy+y)T(x,y) }{ \sqrt{ \displaystyle \sum \displaystyle \sum {I(dx+x,dy+y)}^2 } \sqrt{ \displaystyle \sum \displaystyle \sum T(x,y)^2 }}$$

ZNCC

ZNCC(Zero means Normalized Cross Correlation)

$$\displaystyle \frac{ \displaystyle \sum \displaystyle \sum (I(dx+x,dy+y)-\mu_I)(T(x,y)- \mu_T) }{ \sqrt{ \displaystyle \sum \displaystyle \sum (I(dx+x,dy+y)- \mu_I)^2 } \sqrt{ \displaystyle \sum \displaystyle \sum (T(x,y)- \mu_T)^2 }}$$

\(\mu_I\)と\(\mu_T\)は、それぞれ入力画像とテンプレート画像の平均値である。

参考

http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html
https://algorithm.joho.info/image-processing/template-matching-sad-ssd-ncc/