Template matching – OpenCV 3.4 with python 3 Tutorial 20

Template matching image:

[python]
import cv2
import numpy as np

img = cv2.imread("simpsons.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("barts_face.jpg", cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]

result = cv2.matchTemplate(gray_img, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(result >= 0.4)

for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 3)

cv2.imshow("img", img)

cv2.waitKey(0)
cv2.destroyAllWindows()
[/python]

 

Template matching Video real time:

[python]
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
template = cv2.imread("pen.png", cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]

while True:
_, frame = cap.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

res = cv2.matchTemplate(gray_frame, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(res >= 0.7)

for pt in zip(*loc[::-1]):
cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 3)

cv2.imshow("Frame", frame)

key = cv2.waitKey(1)

if key == 27:
break

cap.release()
cv2.destroyAllWindows()
[/python]

 

Files:

  1. simpsons.jpg
  2. barts_face.jpg
Blueprint

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE