Life2Coding
Template Matching using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to match template with original images and find the exact match using OpenCV and Python coding.

Documentation:

Python: cv2.matchTemplate(image, templ, method[, result]) → result

Compares a template against overlapped image regions.

Parameters:          

  • image – Image where the search is running. It must be 8-bit or 32-bit floating-point.
  • templ – Searched template. It must be not greater than the source image and have the same data type.
  • result – Map of comparison results. It must be single-channel 32-bit floating-point. If image is W x H and templ is w x h, then result is (W-w+1) x (H-h+1)
  • method – Parameter specifying the comparison method.

There are six matching methods: CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, CV_TM_CCOEFF and CV_TM_CCOEFF_NORMED.

Steps:

  • Load the Original and Template images using cv2.imread()
  • Converting the both images to gray using cv2.cvtColor()
  • Match the template using cv2.matchTemplate()
  • Draw boundary around the face using cv2.rectangle()
  • Display both images using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

Output:

template3 Template Matching using OpenCV in Python

life2coding_icon [] Template Matching using OpenCV in Python

Life2Coding

Technology Related Blog at Life2Coding
Feel free to contact us for your any kind of technical problems. We are here to help you.
life2coding_icon [] Template Matching using OpenCV in Python

Leave a Reply

Your email address will not be published. Required fields are marked *