Interface2017年05月号新画像処理101を読む

11-8 探したいパターンと比べる代表的な物体検出「テンプレート・マッチング」

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

img_src = cv2.imread("data/img_11-8.bmp")
img_src2 = cv2.cvtColor(img_src,cv2.COLOR_RGB2GRAY) 
img_dst = cv2.imread("data/img_11-8.bmp")
template = cv2.imread('data/img_temp.bmp',0)
w, h = template.shape[::-1]


res = cv2.matchTemplate(img_src2,template,cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)

cv2.rectangle(img_dst,top_left, bottom_right, 255, 2)

cv2.imshow("img_src",img_src)
cv2.imshow("img_dst",img_dst)
cv2.imshow("img_temp",template)

cv2.waitKey(0)
cv2.destroyAllWindows()

f:id:bitop:20180401081055p:plain

f:id:bitop:20180401081122p:plain

テンプレート画像
f:id:bitop:20180401081209p:plain