Task: Find the template image in the original image using OpenCV and create a bounding box around the template in original image.
Original Image: (Student.jpg)
Template Image (Template.jpg):
Description:
In this tutorial we will guide you how you can find a face of a person in an image using a technique called Template Matching in OpenCV.
For this purpose, we will be needing two images the first one is our
Code:
Description:
import cv2
import numpy as np
image = cv2.imread('students.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
template = cv2.imread('template.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
print('Original Dimensions : ',image.shape)
resized = cv2.resize(image, (800,800), interpolation = cv2.INTER_AREA)
cv2.imshow("IMAGE",resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('template_matching.png', image
Result (Template_matching.png):