Template Matching
Table of Contents
Prev Tutorial: Back Projection
Next Tutorial: Finding contours in your image
Prev Tutorial: Back Projection
Next Tutorial: Finding contours in your image
| Original author | Ana Huamán |
| Compatibility | OpenCV >= 3.0 |
In this tutorial you will learn how to:
Template matching is a technique for finding areas of an image that match (are similar) to a template image (patch).
While the patch must be a rectangle it may be that not all of the rectangle is relevant. In such a case, a mask can be used to isolate the portion of the patch that should be used to find the match.
We need two primary components:
our goal is to detect the highest matching area:
the image above is the result R of sliding the patch with a metric TM_CCORR_NORMED. The brightest locations indicate the highest matches. As you can see, the location marked by the red circle is probably the one with the highest value, so that location (the rectangle formed by that point as a corner and width and height equal to the patch image) is considered the match.
Good question. OpenCV implements Template matching in the function matchTemplate(). The available methods are 6:
method=TM_SQDIFF
method=TM_SQDIFF_NORMED
method=TM_CCORR
method=TM_CCORR_NORMED
method=TM_CCOEFF
method=TM_CCOEFF_NORMED
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
bool use_mask;
Mat img; Mat templ; Mat mask; Mat result;
const char* image_window = "Source Image";
const char* result_window = "Result window";
int match_method;
int max_Trackbar = 5;
void MatchingMethod( int, void* );
const char* keys =
"{ help h| | Print help message. }"
"{ @input1 | Template_Matching_Original_Image.jpg | image_name }"
"{ @input2 | Template_Matching_Template_Image.jpg | template_name }"
"{ @input3 | | mask_name }";
int main( int argc, char** argv )
{
CommandLineParser parser( argc, argv, keys );
samples::addSamplesDataSearchSubDirectory( "doc/tutorials/imgproc/histograms/template_matching/images" );
img = imread( samples::findFile( parser.get<String>("@input1") ) );
templ = imread( samples::findFile( parser.get<String>("@input2") ), IMREAD_COLOR );
if(argc > 3) {
use_mask = true;
mask = imread(samples::findFile( parser.get<String>("@input3") ), IMREAD_COLOR );
}
if(img.empty() || templ.empty() || (use_mask && mask.empty()))
{
cout << "Can't read one of the images" << endl;
return EXIT_FAILURE;
}
namedWindow( image_window, WINDOW_AUTOSIZE );
namedWindow( result_window, WINDOW_AUTOSIZE );
const char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod );
MatchingMethod( 0, 0 );
waitKey(0);
return EXIT_SUCCESS;
}
void MatchingMethod( int, void* )
{
Mat img_display;
img.copyTo( img_display );
int result_cols = img.cols - templ.cols + 1;
int result_rows = img.rows - templ.rows + 1;
result.create( result_rows, result_cols, CV_32FC1 );
bool method_accepts_mask = (TM_SQDIFF == match_method || match_method == TM_CCORR_NORMED);
if (use_mask && method_accepts_mask)
{ matchTemplate( img, templ, result, match_method, mask); }
else
{ matchTemplate( img, templ, result, match_method); }
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
if( match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
imshow( image_window, img_display );
imshow( result_window, result );
return;
}import java.awt.GridLayout;
import java.awt.Image;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
class MatchTemplateDemoRun implements ChangeListener {
Boolean use_mask = false;
Mat img = new Mat(), templ = new Mat();
Mat mask = new Mat();
int match_method;
JLabel imgDisplay = new JLabel(), resultDisplay = new JLabel();
public void run(String[] args) {
if (args.length < 2) {
System.out.println("Not enough parameters");
System.out.println("Program arguments:\n<image_name> <template_name> [<mask_name>]");
System.exit(-1);
}
img = Imgcodecs.imread(args[0], Imgcodecs.IMREAD_COLOR);
templ = Imgcodecs.imread(args[1], Imgcodecs.IMREAD_COLOR);
if (args.length > 2) {
use_mask = true;
mask = Imgcodecs.imread(args[2], Imgcodecs.IMREAD_COLOR);
}
if (img.empty() || templ.empty() || (use_mask && mask.empty())) {
System.out.println("Can't read one of the images");
System.exit(-1);
}
matchingMethod();
createJFrame();
}
private void matchingMethod() {
Mat result = new Mat();
Mat img_display = new Mat();
img.copyTo(img_display);
int result_cols = img.cols() - templ.cols() + 1;
int result_rows = img.rows() - templ.rows() + 1;
result.create(result_rows, result_cols, CvType.CV_32FC1);
Boolean method_accepts_mask = (Imgproc.TM_SQDIFF == match_method || match_method == Imgproc.TM_CCORR_NORMED);
if (use_mask && method_accepts_mask) {
Imgproc.matchTemplate(img, templ, result, match_method, mask);
} else {
Imgproc.matchTemplate(img, templ, result, match_method);
}
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
Point matchLoc;
Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
matchLoc = mmr.minLoc;
} else {
matchLoc = mmr.maxLoc;
}
Imgproc.rectangle(img_display, matchLoc, new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
new Scalar(0, 0, 0), 2, 8, 0);
Imgproc.rectangle(result, matchLoc, new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
new Scalar(0, 0, 0), 2, 8, 0);
Image tmpImg = HighGui.toBufferedImage(img_display);
ImageIcon icon = new ImageIcon(tmpImg);
imgDisplay.setIcon(icon);
result.convertTo(result, CvType.CV_8UC1, 255.0);
tmpImg = HighGui.toBufferedImage(result);
icon = new ImageIcon(tmpImg);
resultDisplay.setIcon(icon);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
match_method = source.getValue();
matchingMethod();
}
}
private void createJFrame() {
String title = "Source image; Control; Result image";
JFrame frame = new JFrame(title);
frame.setLayout(new GridLayout(2, 2));
frame.add(imgDisplay);
int min = 0, max = 5;
JSlider slider = new JSlider(JSlider.VERTICAL, min, max, match_method);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Set the spacing for the minor tick mark
slider.setMinorTickSpacing(1);
// Customizing the labels
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
labelTable.put(new Integer(0), new JLabel("0 - SQDIFF"));
labelTable.put(new Integer(1), new JLabel("1 - SQDIFF NORMED"));
labelTable.put(new Integer(2), new JLabel("2 - TM CCORR"));
labelTable.put(new Integer(3), new JLabel("3 - TM CCORR NORMED"));
labelTable.put(new Integer(4), new JLabel("4 - TM COEFF"));
labelTable.put(new Integer(5), new JLabel("5 - TM COEFF NORMED : (Method)"));
slider.setLabelTable(labelTable);
slider.addChangeListener(this);
frame.add(slider);
frame.add(resultDisplay);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
public class MatchTemplateDemo {
public static void main(String[] args) {
// load the native OpenCV library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// run code
new MatchTemplateDemoRun().run(args);
}
}from __future__ import print_function
import sys
import cv2 as cv
use_mask = False
img = None
templ = None
mask = None
image_window = "Source Image"
result_window = "Result window"
match_method = 0
max_Trackbar = 5
def main(argv):
if (len(sys.argv) < 3):
print('Not enough parameters')
print('Usage:\nmatch_template_demo.py <image_name> <template_name> [<mask_name>]')
return -1
global img
global templ
img = cv.imread(sys.argv[1], cv.IMREAD_COLOR)
templ = cv.imread(sys.argv[2], cv.IMREAD_COLOR)
if (len(sys.argv) > 3):
global use_mask
use_mask = True
global mask
mask = cv.imread( sys.argv[3], cv.IMREAD_COLOR )
if ((img is None) or (templ is None) or (use_mask and (mask is None))):
print('Can\'t read one of the images')
return -1
cv.namedWindow( image_window, cv.WINDOW_AUTOSIZE )
cv.namedWindow( result_window, cv.WINDOW_AUTOSIZE )
trackbar_label = 'Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED'
cv.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod )
MatchingMethod(match_method)
cv.waitKey(0)
return 0
def MatchingMethod(param):
global match_method
match_method = param
img_display = img.copy()
method_accepts_mask = (cv.TM_SQDIFF == match_method or match_method == cv.TM_CCORR_NORMED)
if (use_mask and method_accepts_mask):
result = cv.matchTemplate(img, templ, match_method, None, mask)
else:
result = cv.matchTemplate(img, templ, match_method)
cv.normalize( result, result, 0, 1, cv.NORM_MINMAX, -1 )
_minVal, _maxVal, minLoc, maxLoc = cv.minMaxLoc(result, None)
if (match_method == cv.TM_SQDIFF or match_method == cv.TM_SQDIFF_NORMED):
matchLoc = minLoc
else:
matchLoc = maxLoc
cv.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[1], matchLoc[1] + templ.shape[0]), (0,0,0), 2, 8, 0 )
cv.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[1], matchLoc[1] + templ.shape[0]), (0,0,0), 2, 8, 0 )
cv.imshow(image_window, img_display)
cv.imshow(result_window, result)
pass
if __name__ == "__main__":
main(sys.argv[1:])Declare some global variables, such as the image, template and result matrices, as well as the match method and the window names:
bool use_mask;
Mat img; Mat templ; Mat mask; Mat result;
const char* image_window = "Source Image";
const char* result_window = "Result window";
int match_method;
int max_Trackbar = 5; Boolean use_mask = false;
Mat img = new Mat(), templ = new Mat();
Mat mask = new Mat();
int match_method;
JLabel imgDisplay = new JLabel(), resultDisplay = new JLabel();use_mask = False
img = None
templ = None
mask = None
image_window = "Source Image"
result_window = "Result window"
match_method = 0
max_Trackbar = 5Load the source image, template, and optionally, if supported for the matching method, a mask:
img = imread( samples::findFile( parser.get<String>("@input1") ) );
templ = imread( samples::findFile( parser.get<String>("@input2") ), IMREAD_COLOR );
if(argc > 3) {
use_mask = true;
mask = imread(samples::findFile( parser.get<String>("@input3") ), IMREAD_COLOR );
}
if(img.empty() || templ.empty() || (use_mask && mask.empty()))
{
cout << "Can't read one of the images" << endl;
;
}Create the Trackbar to enter the kind of matching method to be used. When a change is detected the callback function is called.
const char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod ); int min = 0, max = 5;
JSlider slider = new JSlider(JSlider.VERTICAL, min, max, match_method);Let's check out the callback function. First, it makes a copy of the source image:
Mat img_display;
img.copyTo( img_display ); Mat img_display = new Mat();
img.copyTo(img_display); img_display = img.copy()Perform the template matching operation. The arguments are naturally the input image I, the template T, the result R and the match_method (given by the Trackbar), and optionally the mask image M.
bool method_accepts_mask = (TM_SQDIFF == match_method || match_method == TM_CCORR_NORMED);
if (use_mask && method_accepts_mask)
{ matchTemplate( img, templ, result, match_method, mask); }
else
{ matchTemplate( img, templ, result, match_method); } Boolean method_accepts_mask = (Imgproc.TM_SQDIFF == || == .);
( && ) {
.(, , , , );
} {
.(, , , );
}We normalize the results:
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() ); Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat()); cv.normalize( result, result, 0, 1, cv.NORM_MINMAX, - )We localize the minimum and maximum values in the result matrix R by using minMaxLoc().
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() ); Point matchLoc;
Core.MinMaxLocResult mmr = Core.minMaxLoc(result);For the first two methods ( TM_SQDIFF and MT_SQDIFF_NORMED ) the best match are the lowest values. For all the others, higher values represent better matches. So, we save the corresponding value in the matchLoc variable:
if( match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; } if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
matchLoc = mmr.minLoc;
} else {
matchLoc = mmr.maxLoc;
}Display the source image and the result matrix. Draw a rectangle around the highest possible matching area:
rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
imshow( image_window, img_display );
imshow( result_window, result );
and a template image:
where
img = Imgcodecs.imread(args[0], Imgcodecs.IMREAD_COLOR);
templ = Imgcodecs.imread(args[1], Imgcodecs.IMREAD_COLOR); global img
global templ
img = cv.imread(sys.argv[1], cv.IMREAD_COLOR)
templ = cv.imread(sys.argv[2], cv.IMREAD_COLOR)
if (len(sys.argv) > 3):
global use_mask
use_mask = True
global mask
mask = cv.imread( sys.argv[3], cv.IMREAD_COLOR )
if ((img is None) or (templ is None) or (use_mask and (mask is None))):
print('Can\'t read one of the images')
return -1 trackbar_label = 'Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED'
cv.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod ) method_accepts_mask = (cv.TM_SQDIFF == match_method or match_method == cv.TM_CCORR_NORMED)
if (use_mask and method_accepts_mask):
result = cv.matchTemplate(img, templ, match_method, None, mask)
else:
result = cv.matchTemplate(img, templ, match_method) _minVal, _maxVal, minLoc, maxLoc = cv.minMaxLoc(result, None) if (match_method == cv.TM_SQDIFF or match_method == cv.TM_SQDIFF_NORMED):
matchLoc = minLoc
else:
matchLoc = maxLoc Imgproc.rectangle(img_display, matchLoc, new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
new Scalar(0, 0, 0), 2, 8, 0);
Imgproc.rectangle(result, matchLoc, new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
new Scalar(0, 0, 0), 2, 8, 0);
Image tmpImg = HighGui.toBufferedImage(img_display);
ImageIcon icon = new ImageIcon(tmpImg);
imgDisplay.setIcon(icon);
result.convertTo(result, CvType.CV_8UC1, 255.0);
tmpImg = HighGui.toBufferedImage(result);
icon = new ImageIcon(tmpImg);
resultDisplay.setIcon(icon); cv.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[1], matchLoc[1] + templ.shape[0]), (0,0,0), 2, 8, 0 )
cv.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[1], matchLoc[1] + templ.shape[0]), (0,0,0), 2, 8, 0 )
cv.imshow(image_window, img_display)
cv.imshow(result_window, result)