Advertisement
yamaji14

テンプレートマッチング(パイソン)

Nov 20th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. from matplotlib import pyplot as plt
  4.  
  5. img = cv2.imread('messi5.jpg',0)
  6. img2 = img.copy()
  7. template = cv2.imread('template.jpg',0)
  8. w, h = template.shape[::-1]
  9.  
  10. # All the 6 methods for comparison in a list
  11. methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
  12.             'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
  13.  
  14. for meth in methods:
  15.     img = img2.copy()
  16.     method = eval(meth)
  17.  
  18.     # Apply template Matching
  19.     res = cv2.matchTemplate(img,template,method)
  20.     min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
  21.  
  22.     # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
  23.     if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
  24.         top_left = min_loc
  25.     else:
  26.         top_left = max_loc
  27.     bottom_right = (top_left[0] + w, top_left[1] + h)
  28.  
  29.     cv2.rectangle(img,top_left, bottom_right, 255, 2)
  30.  
  31.     plt.subplot(121),plt.imshow(res,cmap = 'gray')
  32.     plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
  33.     plt.subplot(122),plt.imshow(img,cmap = 'gray')
  34.     plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
  35.     plt.suptitle(meth)
  36.  
  37.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement