基于c++ opencv的图像多模板匹配
时间: 2023-05-23 08:03:31 浏览: 192
可以使用OpenCV中的模板匹配函数进行图像多模板匹配。该函数需要输入待匹配图像和模板图像,并返回匹配结果的坐标信息。以下是一个基于C语言和OpenCV的图像多模板匹配的示例代码:
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc_c.h>
void multi_template_match(IplImage* src, IplImage* tem[], int n_template)
{
// Define match method and threshold
int match_method = CV_TM_CCOEFF_NORMED;
double threshold = 0.8;
// Loop through all templates and perform matching
for (int i = 0; i < n_template; i++)
{
IplImage* result = cvCreateImage(cvSize(src->width - tem[i]->width + 1, src->height - tem[i]->height + 1), IPL_DEPTH_32F, 1);
cvMatchTemplate(src, tem[i], result, match_method);
// Find best match
CvPoint max_loc;
double max_val;
cvMinMaxLoc(result, 0, &max_val, 0, &max_loc, 0);
if (max_val >= threshold)
{
// Draw rectangle around matched area
cvRectangle(src, cvPoint(max_loc.x, max_loc.y), cvPoint(max_loc.x + tem[i]->width, max_loc.y + tem[i]->height), CV_RGB(255, 0, 0), 2);
}
cvReleaseImage(&result);
}
}
int main()
{
// Load source image and templates
IplImage* src = cvLoadImage("source.jpg");
IplImage* tem[2];
tem[0] = cvLoadImage("template1.jpg");
tem[1] = cvLoadImage("template2.jpg");
// Perform multi-template matching
multi_template_match(src, tem, 2);
// Show result image
cvShowImage("Result", src);
cvWaitKey(0);
// Release resources
cvReleaseImage(&src);
cvReleaseImage(&tem[0]);
cvReleaseImage(&tem[1]);
return 0;
}