OpenCV実験python3 テンプレート比較で特定の形の図が存在するか判定 cv2.matchTemplate実験 その2

引き続きこちらを参考に続けます。

https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html

その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だとほとんどマッチングとしては使えない状態になりますね。

カラーマッチングしきい値0.9
th=0.9 カラーマッチング

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

カラーマッチングしきい値0.8
閾値=0.8  カラーマッチング

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

カラーマッチングしきい値0.3
th=0.3  カラーマッチング

th=0.3ですと丸い図形でも青色でもマッチングされちゃいますね。

グレースケールでマッチングしてみる

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

グレースケールマッチンググしきい値0.8
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)