2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

scikit-image でテンプレートマッチング

Last updated at Posted at 2019-07-27

match_template というそのものズバリな関数があります。

skimage.feature.match_template(image, template, pad_input=False, mode='constant', constant_values=0)

公式ドキュメント

Module: feature — skimage docs
Template Matching — skimage docs

使用例1

第1引数に入力画像、第2引数にテンプレート画像を指定すればOK。

import matplotlib.pyplot as plt
import numpy as np
import skimage
import skimage.feature
import skimage.io
from matplotlib.patches import Rectangle

img = skimage.io.imread('img.png', as_gray=True)
img = skimage.img_as_ubyte(img)
templ = skimage.io.imread('templ.png', as_gray=True)
templ = skimage.img_as_ubyte(templ)

result = skimage.feature.match_template(img, templ)
r, c = np.unravel_index(np.argmax(result), result.shape)

plt.figure()
plt.subplot(2, 1, 1)
plt.imshow(templ, vmin=0, vmax=255, cmap='gray')

plt.subplot(2, 2, 3)
plt.imshow(img, vmin=0, vmax=255, cmap='gray')
rect = Rectangle((c, r),
                 templ.shape[1],
                 templ.shape[0],
                 fill=False,
                 color='red')
plt.gca().add_patch(rect)

plt.subplot(2, 2, 4)
plt.imshow(result, vmin=-1, vmax=1, cmap='bwr')

plt.savefig('figure.png')
plt.close()

figure.png

使用例2

pad_input=True とすると、テンプレート画像が入力画像から多少はみ出していても検出できるようになります。

import matplotlib.pyplot as plt
import numpy as np
import skimage
import skimage.feature
import skimage.io
from matplotlib.patches import Rectangle

img = skimage.io.imread('img.png', as_gray=True)
img = skimage.img_as_ubyte(img)
templ = skimage.io.imread('templ.png', as_gray=True)
templ = skimage.img_as_ubyte(templ)

result = skimage.feature.match_template(img, templ, pad_input=True)
r, c = np.unravel_index(np.argmax(result), result.shape)

plt.figure()
plt.subplot(2, 1, 1)
plt.imshow(templ, vmin=0, vmax=255, cmap='gray')

plt.subplot(2, 2, 3)
plt.imshow(img, vmin=0, vmax=255, cmap='gray')
rect = Rectangle((c - templ.shape[1] // 2, r - templ.shape[0] // 2),
                 templ.shape[1],
                 templ.shape[0],
                 fill=False,
                 color='red')
plt.gca().add_patch(rect)

plt.subplot(2, 2, 4)
plt.imshow(result, vmin=-1, vmax=1, cmap='bwr')

plt.savefig('figure.png')
plt.close()

figure.png

2
4
0

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?