手撸模板匹配-C++版本

归一化相关系数

//所有点之和
double EM(Mat img)
{
	double sum = 0;
	for (int i = 0; i < img.rows; i++)
		for (int j = 0; j < img.cols; j++)
			sum += img.at(i, j);
		
	return sum;
}

//手撸模板匹配—cpu
void match_(Mat srcImg, Mat templImg, Mat &resultMat)
{
	int N = templImg.cols * templImg.rows;	
	double templSum = EM(templImg);
	
	for (int xAt = 0; xAt < resultMat.cols; xAt++)
	{
		for (int yAt = 0; yAt < resultMat.rows; yAt++)
		{	
			Mat srcImg_ = srcImg(Rect(xAt, yAt, templImg.cols, templImg.rows));
			double srcMean = EM(srcImg_);

			double numerator = 0;
			double deno1 = 0;
			double deno2 = 0;
			for (int mm = 0; mm < templImg.rows; mm++)
			{
				for (int nn = 0; nn < templImg.cols; nn++)
				{
					double temGray_ = templImg.at(mm, nn) - templSum / N;
					double srcGray_ = srcImg_.at(mm, nn) - srcMean / N;

					numerator += temGray_*srcGray_;		//分子

					deno1 += (temGray_ * temGray_);		//分母
					deno2 += (srcGray_ * srcGray_);
				}
			}

			resultMat.at(yAt, xAt) = numerator / (sqrtf(deno1 * deno2));
		}
	}
}

你可能感兴趣的:(Opencv,C++,c++,计算机视觉,opencv)