In [31]:
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
In [62]:
#reading in the images
img_bgr = cv2.imread('opencv-template-matching-python-tutorial.jpg')
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
template = cv2.imread('opencv-template-for-matching.jpg', 0)
template_bgr = cv2.imread('opencv-template-for-matching.jpg')
template_rgb = cv2.cvtColor(template_bgr, cv2.COLOR_BGR2RGB)
In [63]:
#showing the template
plt.figure(figsize=(1,1))
plt.axis('off')
plt.title('The template')
plt.imshow(template_rgb)
plt.show()
In [64]:
#showing the image
plt.figure(figsize=(14,16))
plt.axis('off')
plt.title('The image where we are looking for the template')
plt.imshow(img_rgb)
plt.show()
In [65]:
w, h = template.shape[::-1]
In [66]:
#performing matching
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
#setting threshold
threshold = 0.8
#finding matches
loc = np.where(res >= threshold)
#marking matches on the image
for pt in zip(*loc[::-1]):
cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0, 255, 0), 1)
In [67]:
#showing the results
plt.figure(figsize=(14,16))
plt.axis('off')
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.show()