OpenCV実験python3 テンプレート比較で特定の形の図が存在するか判定 cv2.matchTemplate実験 その2
引き続きこちらを参考に続けます。
その1ではマッチした形をひとつしか四角で囲っていませんが、次は複数個四角で囲ってみます。
また形のピクセルサイズが違うと基本的にはマッチングできないのですが、閾値(threshold)を使うと多少はピクセルサイズが違っていても検出することが可能なことを実験で確認したいと思います。
こちらが入力画像です。

こちらテンプレート画像です。上記の右下の四角をコピペしたものです。

カラーでマッチングしてみる
サンプルソースコード
import cv2
import numpy as np
infile ='sample.jpg'
templatefile='template.jpg'
outfile='output.jpg'
img = cv2.imread(infile)
img2 = img.copy()
img_template = cv2.imread(templatefile)
s,w,h=img_template.shape[::-1]
res = cv2.matchTemplate(img,img_template,cv2.TM_CCOEFF_NORMED)
threshold = 0.9
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img2, pt, (pt[0] + w, pt[1] + h), (0,0,0), 2)
cv2.imwrite(outfile,img2)
ポイントは以下の3行ですね。まず素人では思いうかべるのが絶対無理なコードですよね。。zip(*loc[::-1])のあたりとか。参考になります。
threshold = 0.9
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
ここでthreshold = 0.9の部分を0から1の範囲で変えて実験してみます。threshold が小さくなるとゆるくマッチングします。0.3だとほとんどマッチングとしては使えない状態になりますね。

th=0.9ですとオリジナルの部分のみがマッチングされます。

th=0.8でもう少しゆるくマッチングすると左上の微妙にサイズの違う四角もマッチングされました。

th=0.3ですと丸い図形でも青色でもマッチングされちゃいますね。
グレースケールでマッチングしてみる
上記のサンプルはカラーでマッチングしましたが、ためしにグレースケールでマッチングすると今度はth=0.8 でも青の四角もマッチングされましたね。

グレースケールマッチングサンプルコード
import cv2
import numpy as np
infile ='sample.jpg'
templatefile='template.jpg'
outfile='output.jpg'
img = cv2.imread(infile)
img2 = img.copy()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_template = cv2.imread(templatefile,cv2.IMREAD_GRAYSCALE)
w,h=img_template.shape[::-1]
res = cv2.matchTemplate(img_gray,img_template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img2, pt, (pt[0] + w, pt[1] + h), (0,0,0), 2)
cv2.imwrite(outfile,img2)