OpenCV-はじめに:テンプレートマッチング(cv2.matchTemplate())



Opencv Introduction Notes



1.定義:

テンプレートは既知の小さな画像であり、テンプレートマッチングは、大きな画像内のターゲットを検索することです。画像内にターゲットがあり、ターゲットのサイズ、方向、画像要素はテンプレートと同じであることがわかっています。特定のアルゴリズムがグラフ内のターゲットを見つけることができます
画像

2.テンプレートマッチング方法:

  • cv2.TM_CCOEFF(係数マッチング法)
  • cv2.TM_CCOEFF_NORMED(相関係数マッチング法)
  • cv2.TM_CCORR(相関マッチング法)
  • cv2.TM_CCORR_NORMED(正規化された相関マッチング法)
  • cv2.TM_SQDIFF(二乗の差のマッチング方法)
  • cv2.TM_SQDIFF_NORMED(正規化された二乗の差のマッチング方法)

3.コード:

-Appear only once for the template (eg: Messi's face) -You can use the cv2.minMaxLoc() function import numpy as np import cv2 as cv img = cv.imread('messi5.jpg') img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) template = cv.imread('messi_face.jpg',0) w,h = template.shape[::-1] res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res) top_left = max_loc # (If the template method is square difference or normalized square difference, use min_loc) bottom_right = (top_left[0] + w,top_left[1] + h) cv.rectangle(img,top_left,bottom_right,255,2) cv.imshow('image',img) cv.imshow('template',template) cv.waitKey(0) cv.destroyAllWindows()

画像



-Repeatedly appear for the template (eg: Super Mario-gold coins) -Need to define threshold img = cv.imread('messi5.jpg') img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) template = cv.imread('messi_face.jpg',0) w,h = template.shape[::-1] res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cv.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) cv.imshow('image',img) cv.imshow('template',template) cv.waitKey(0) cv.destroyAllWindows()

画像

# The box of the second method should be thicker, because the threshold we defined is 0.8, (only for the cv.TM_CCOEFF_NORMED matching method in the code) loc detects 9 points, which is equivalent to drawing the box three times, so it should be thicker (I understand it myself, brothers and sisters are welcome to correct me~ thank you~)

公式ドキュメントに従うことを強くお勧めします〜