Skip to content

Instantly share code, notes, and snippets.

@meganvanwelie
Created September 17, 2016 21:19
Show Gist options
  • Save meganvanwelie/90a2b9766a64849d9711d937c3d28331 to your computer and use it in GitHub Desktop.
Save meganvanwelie/90a2b9766a64849d9711d937c3d28331 to your computer and use it in GitHub Desktop.
Template matching on video, not yet using scale or orientation
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
// Based on:
// http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html
int main( int argc, char* argv[])
{
Mat templ;
templ = imread(argv[1], IMREAD_COLOR);
if (templ.empty())
{
cout << "Could not open or find the image" << std::endl;
return 0;
}
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "Cannot open the video cam" << endl;
return -1;
}
Mat frame_prev;
// read a new frame from video
bool bSuccess = cap.read(frame_prev);
//if not successful, break loop
if (!bSuccess)
{
cout << "Cannot read a frame from video stream" << endl;
}
// create windows for display
namedWindow("MyVideo0", WINDOW_AUTOSIZE);
namedWindow("TemplateMatch", WINDOW_AUTOSIZE);
namedWindow("Template", WINDOW_AUTOSIZE);
// create template matching matrix and helper variables
double minVal, maxVal;
Point minLoc, maxLoc, matchLoc;
int cols = frame_prev.cols - templ.cols + 1;
int rows = frame_prev.rows - templ.rows + 1;
cout << cols << " " << rows << endl;
Mat result( rows, cols, CV_32FC1 );
while (1)
{
// read a new frame from video
Mat frame;
bSuccess = cap.read(frame);
//if not successful, break loop
if (!bSuccess)
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
// template match
matchTemplate( frame, templ, result, CV_TM_SQDIFF );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
matchLoc = minLoc;
rectangle( frame, 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("MyVideo0", frame);
//imshow("TemplateMatch", result);
imshow("Template", templ);
// update previous frame
frame_prev = frame;
// Wait for 'esc' key press for 30ms.
// If 'esc' key is pressed, break loop
if (waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
cap.release();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment