Python/OpenCV
Template Matching in OpenCV
Tongchun
2017. 11. 8. 18:53
template 이미지를 원본 이미지와 매칭 시키는 sample 입니다.
6가지의 template matching method를 비교해 보는 예제입니다.
원본 이미지는 twice 입니다.
template 이미지는 누군지 모르겠습니다. 복스럽게 생겼네요.
아래와 같이 작성하고 OpenCV가 여러 matching method를 사용해 원본 이미지에서 template 이미지를 찾게해 보겠습니다.
import cv2 import numpy as np from matplotlib import pyplot as plt # 원본 이미지 img = cv2.imread('twice.jpg',0) img2 = img.copy() # 찾으려는 이미지 template = cv2.imread('who-are-you.png',0) w, h = template.shape[::-1] # All the 6 methods for comparison in a list methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] for meth in methods: img = img2.copy() method = eval(meth) # Apply template Matching res = cv2.matchTemplate(img, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) center = (top_left[0] + int(w/2), top_left[1] + int(h/2)) print(top_left, bottom_right, center) cv2.rectangle(img, top_left, bottom_right, 255, 2) cv2.circle(img, center, 3, 0, -1) plt.subplot(121),plt.imshow(res,cmap = 'gray') plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(img,cmap = 'gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) plt.suptitle(meth) plt.show()
실행하면 method별 이미지가 출력됩니다.
TM_CCORR method는 이미지를 찾지 못했네요.