欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

模板匹配

程序员文章站 2022-04-01 09:44:23
...
/*在一副图像中寻找另一幅图像最匹配(相似)部分的技术
通过在输入图像上华东图像块,对实际图像块和输入图像进行匹配

Void mathcTemplate(inputarray image,//带搜索图像 8位或者32位 浮点图像
				Inputarray temp1,//搜索模板 一样的数据类型,不能大于原图尺寸
				Outputarray result,//比较结果的映射图像,必须为单通道,32浮点图像,
				Int method 匹配方法 6种
				);
				
平方差匹配方法:最好匹配为0 ,匹配越差值越大 TM_SQDIFF

归一化平方差 :TM_SQDIFF_NORME

相关匹配:TM_CCORR  越大越相似 乘法操作

归一化相关匹配 TM_CCORR_NORMED

系数匹配 TM_CCOEFF 1 完美  -1 糟糕 0 没有任何关系

化相系数匹配 TM_CCOEFF_NORMED
*/
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/photo/photo.hpp>
using namespace std;
using namespace cv;

//*********************************
//("C:/Users/hasee-pc/Desktop/women.jpg");	
//*********************************

#define WINDOW_NAME1 "【原始图片】"
#define WINDOW_NAME2 "【效果窗口】"

Mat g_srcImage;
Mat g_templateImage;
Mat g_resultImage;
int g_nMatchMehod;
int g_nMaxTrackbarNum = 5;

void on_Matching(int, void *);

int main()
{
	g_srcImage = imread("C:/Users/hasee-pc/Desktop/girl.jpg", 1);
	g_templateImage = imread("C:/Users/hasee-pc/Desktop/face.jpg", 1);

	namedWindow(WINDOW_NAME1, WINDOW_AUTOSIZE);
	namedWindow(WINDOW_NAME2, WINDOW_AUTOSIZE);

	createTrackbar("方法", WINDOW_NAME1, &g_nMatchMehod, g_nMaxTrackbarNum, on_Matching);
	on_Matching(0, 0);

	waitKey(0);
}

void on_Matching(int, void *)
{
	Mat srcImage;
	g_srcImage.copyTo(srcImage);

	//初始化输出矩阵
	int resultImage_cols = g_srcImage.cols - g_templateImage.cols + 1;
	int resultImage_rows = g_srcImage.rows - g_templateImage.rows + 1;
	g_resultImage.create(resultImage_cols, resultImage_rows, CV_32FC1);

	//匹配和标准化
	matchTemplate(g_srcImage, g_templateImage, g_resultImage, g_nMatchMehod);
	normalize(g_resultImage, g_resultImage, 0, 1, NORM_MINMAX, -1, Mat());

	//定位最匹配位置
	double minValue;
	double maxValue;
	Point minLocation;
	Point maxLocation;
	Point matchLocation;
	minMaxLoc(g_resultImage, &minValue, &maxValue, &minLocation, &maxLocation, Mat());

	//值越小匹配程度越高
	if (g_nMatchMehod == CV_TM_SQDIFF || g_nMatchMehod == CV_TM_SQDIFF_NORMED)
	{
		matchLocation = minLocation;
	}//值越大匹配程度越高
	else
	{
		matchLocation = maxLocation;
	}

	//绘制矩形
	rectangle(srcImage,
		matchLocation,
		Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows),
		Scalar(0, 0, 255),
		2,
		8,
		0
	);

	rectangle(g_resultImage,
		matchLocation,
		Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows),
		Scalar(0, 0, 255),
		2,
		8,
		0
	);

	imshow(WINDOW_NAME1, srcImage);
	imshow(WINDOW_NAME2, g_resultImage);
}