目的
ミッキーマウスをopenCVのテンプレートマッチングを利用して検出します。
準備
python環境と
opencvライブラリを準備します。
テンプレート画像(元画像から切出します) test1.png
コード
sample.py
# coding:utf-8
import cv2
import numpy as np
# 画像をグレースケールで読み込む
fname_img1='test1.png'
fname_img2='test2.png'
img = cv2.imread(fname_img1, 0)
temp = cv2.imread(fname_img2, 0)
# マッチングテンプレートを実行
match_result = cv2.matchTemplate(img, temp, cv2.TM_CCOEFF_NORMED)
# 類似度の設定(0~1)
threshold = 0.9
# 検出結果から検出領域の位置を取得
loc=np.where(match_result >= threshold)
# 検出領域を四角で囲んで保存
w, h = temp.shape[::-1]
for top_left in zip(*loc[::-1]):
bottom_right = (top_left[0] + w, top_left[1] + h)
# 保存
result = cv2.imread(fname_img1)
# height = img.shape[0]
# width = img.shape[1]
# result = cv2.resize(img , (int(width*1.0), int(height*1.0)))
cv2.rectangle(result,top_left, bottom_right, (255, 0, 0), 10)
cv2.imwrite("result.png", result)
テスト
CodingError対策
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
imwriteに指定する元画像のサイズが0になっている。
正しいサイズの画像を指定して解決
参考
テンプレートマッチング
Pythonでテンプレートマッチング、OpenCVサンプルコードと解説
OpenCVで画像サイズの変更をしてみた