Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Python3.6 + OpenCV3.1.1でテンプレートマッチング

実際のところ

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
import sys

def function(pattern_file, threshold_val,):
  img_rgb = cv.imread('sampleimg.png')
  img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
  template = cv.imread(pattern_file,0)
  w, h = template.shape[::-1]
  res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
  threshold = threshold_val
  loc = np.where( res >= threshold)
  for pt in zip(*loc[::-1]):
    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
  cv.imwrite('res.png',img_rgb)

if __name__ == '__main__':
  args = sys.argv
  function(args[1], float(args[2]))
$ python sample_pattern.py good.png 0.3

使う画像

"good.png"
f:id:shuzo_kino:20180102225000p:plain
"bad.png"
f:id:shuzo_kino:20180102225005p:plain
"sampleimg.png"
f:id:shuzo_kino:20180102225105p:plain

使った結果

パターンファイルのgoodをつかってみます。
程よいパラメータを設定しないと、使いモンにならなくなるので注意。

goodの0.8

f:id:shuzo_kino:20180102225313p:plain

goodの0.6

f:id:shuzo_kino:20180102225340p:plain

goodの0.3

f:id:shuzo_kino:20180102225426p:plain

badの0.9

f:id:shuzo_kino:20180102225647p:plain

badの0.8

f:id:shuzo_kino:20180102225728p:plain

badの0.6

こころなしか線が太くなったような??
f:id:shuzo_kino:20180102225900p:plain