LoginSignup
2
6

More than 3 years have passed since last update.

ミッキーをテンプレートマッチングで検出する(python)

Posted at

目的

ミッキーマウスをopenCVのテンプレートマッチングを利用して検出します。

準備

python環境と
opencvライブラリを準備します。

元画像 test.png
test1.png

テンプレート画像(元画像から切出します) test1.png
test2.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)

テスト

以下のように検出できればOKです result.png
result.png

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で画像サイズの変更をしてみた

2
6
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6