0% found this document useful (0 votes)
129 views2 pages

Opencv

This C++ code performs template matching to locate a template image within a reference image. It loads two images, converts them to grayscale, performs normalized cross-correlation template matching to generate a matching score image, thresholds the scores, and loops to find local maxima above a threshold, drawing rectangles around each match found. It resizes the images for display and shows the results.

Uploaded by

Tuấn Çhương
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views2 pages

Opencv

This C++ code performs template matching to locate a template image within a reference image. It loads two images, converts them to grayscale, performs normalized cross-correlation template matching to generate a matching score image, thresholds the scores, and loops to find local maxima above a threshold, drawing rectangles around each match found. It resizes the images for display and shows the results.

Uploaded by

Tuấn Çhương
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include

#include
#include
#include

<opencv2/highgui/highgui.hpp>
<opencv2/imgproc/imgproc.hpp>
<iostream>
<stdio.h>

using namespace std;


using namespace cv;
void showImg(Mat image, string name)
{
Mat image_tmp;
image.copyTo(image_tmp);
resize(image_tmp,image_tmp,Size(500,500));
imshow(name,image_tmp);
image_tmp.release();
}
int main()
{
cv::Mat ref = cv::imread("source_6.jpg");
cv::Mat tpl = cv::imread("temple.jpg");
if (ref.empty() || tpl.empty())
return -1;
cv::Mat gref, gtpl;
cv::cvtColor(ref, gref, CV_BGR2GRAY);
cv::cvtColor(tpl, gtpl, CV_BGR2GRAY);
cv::Mat res(ref.rows-tpl.rows+1, ref.cols-tpl.cols+1, CV_32FC1);
cv::matchTemplate(gref, gtpl, res, CV_TM_CCOEFF_NORMED);
showImg(res,"res_src");
cv::threshold(res, res, 0.6, 1., CV_THRESH_TOZERO);
showImg(res,"res");
int count = 0;
while (true)
{
double minval, maxval, threshold = 0.6;
cv::Point minloc, maxloc;
cv::minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);

if (maxval >= threshold)


{
cout<<maxval<<endl;
cv::rectangle(
ref,
maxloc,
cv::Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows),
CV_RGB(0,255,0), 2
);
cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
}
else
break;
cv::resize(ref,ref,cv::Size(700,700*ref.rows/ref.cols));

cv::imshow("reference", ref);
cv::waitKey();
return 0;

You might also like