opencv--使用opencv实现旋转角度的模板匹配

下面的例子是简单的使用opencv 实现的模板匹配流程,其中时间性能和精确度还需要调整,如果直接使用会出问题,所以这个只是例子,根据代码原理可以实现尺度变化的模板匹配和旋转尺度变化同时,具体根据实现的旋转代码进一步实现,但是就结果而言和halcon的模板匹配差距较大,性能更不行,因此仅供参考

cpp 复制代码
struct MatchResult
{
	std::vector<cv::Point> points;
	double angle;
	double score;
	MatchResult(std::vector<cv::Point> points, double angle, double score) :points(points), angle(angle), score(score) {};
};

//旋转图像
cv::Mat ImageRotate(cv::Mat image, double angle)
{
	cv::Mat newImg;
	cv::Point2f pt = cv::Point2f((float)image.cols / 2, (float)image.rows / 2);
	cv::Mat M = cv::getRotationMatrix2D(pt, angle, 1.0);
	cv::warpAffine(image, newImg, M, image.size());
	return newImg;
}
std::vector<cv::Point> GetRotatePoints(cv::Size size, double angle) {
	// 定义模板图像的中心点
	cv::Point2f center(size.width / 2.0, size.height / 2.0);

	// 计算旋转矩阵
	cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, 1.0);

	// 定义模板图像的四个顶点
	std::vector<cv::Point2f> srcPoints = {
		cv::Point2f(0, 0),
		cv::Point2f(size.width, 0),
		cv::Point2f(size.width, size.height),
		cv::Point2f(0, size.height)
	};

	// 存储旋转后的四个顶点
	std::vector<cv::Point2f> dstPoints(4);

	// 进行仿射变换
	cv::transform(srcPoints, dstPoints, rotationMatrix);

	// 将结果转换为cv::Point类型并返回
	std::vector<cv::Point> resultPoints(4);
	for (int i = 0; i < 4; ++i) {
		resultPoints[i] = cv::Point(cvRound(dstPoints[i].x), cvRound(dstPoints[i].y));
	}

	return resultPoints;
}


/*
旋转模板匹配函数(通过图像金字塔、增大旋转步长来提升匹配速度)
Mat src:原图像
Mat model:模板图
double startAngle:旋转的最小角
double endAngle:旋转的最大角
double firstStep:角度旋转时的最大步长
double secondStep:角度旋转时的最小步长
int numLevels = 0:图像金字塔缩放次数
*/
MatchResult rotateMatch(cv::Mat src, cv::Mat model, double startAngle, double endAngle, double firstStep, double secondStep, int numLevels = 0) {
	//对模板图像和待检测图像分别进行图像金字塔下采样
	for (int i = 0; i < numLevels; i++) {
		cv::pyrDown(src, src, cv::Size(src.cols / 2, src.rows / 2));
		cv::pyrDown(model, model, cv::Size(model.cols / 2, model.rows / 2));
	}

	cv::Mat rotatedImg, result;
	double score = -1;
	cv::Point location;
	double angle;

	bool isSecond = false;
	while (true) {
		for (double curAngle = startAngle; curAngle <= endAngle; curAngle += firstStep) {
			rotatedImg = ImageRotate(model, curAngle);
			//imshow("rotated", rotatedImg);
			//imshow("src-pyrDown", src);
			//waitKey();

			matchTemplate(src, rotatedImg, result, cv::TM_CCOEFF_NORMED);
			double minval, maxval;
			cv::Point minloc, maxloc;
			cv::minMaxLoc(result, &minval, &maxval, &minloc, &maxloc);
			if (maxval > score)
			{
				location = maxloc;
				score = maxval;
				angle = curAngle;
			}
		}

		if (isSecond && firstStep<= secondStep) break;

		startAngle = angle - firstStep;
		endAngle = angle + firstStep;

		if ((endAngle - startAngle) / 5 > secondStep) {
			firstStep = (endAngle - startAngle) / 5;
		}
		else {
			firstStep = secondStep;
			isSecond = true;
		}
	}

	cv::Point finalPoint = cv::Point(location.x * pow(2, numLevels), location.y * pow(2, numLevels));
	std::vector<cv::Point> points = GetRotatePoints(cv::Size(model.cols * pow(2, numLevels), model.rows * pow(2, numLevels)), angle);

	for (int j = 0; j < points.size(); j++)
	{
		points[j].x += finalPoint.x;
		points[j].y += finalPoint.y;
	}

	return MatchResult(points, angle, score);
}

int main() {
	//读取所有图像
	std::vector<cv::Mat> imgs;
	std::string imageName;
	std::string path = "E:\\prj\\shape_based_matching-master\\test\\board\\test";
	std::vector<std::string> img_paths;
	cv::glob(path, img_paths);
	for (auto& p : img_paths)
	{
		cv::Mat img = cv::imread(p);
		imgs.push_back(img);
	}
	cv::Mat templateImg = cv::imread("E:\\prj\\shape_based_matching-master\\test\\board\\train.png");
	cv::Rect box(cv::Point(135, 120), cv::Point(470, 365));
	//cv::rectangle(drawFrame, box, cv::Scalar(0, 255, 0), 2);
	templateImg = templateImg(box).clone();
	int i = 0;
	for (cv::Mat img : imgs)
	{
		i += 1;
		MatchResult matchResult = rotateMatch(img, templateImg, 0, 360, 30, 0.1, 0);
		std::vector<cv::Point> points = matchResult.points;
		std::cout << i << "- 角度:" << matchResult.angle << std::endl;
		std::cout << i << "- 得分:" << matchResult.score << std::endl;

		cv::line(img, points[0], points[1], cv::Scalar(255, 0, 0), 2);
		cv::line(img, points[1], points[2], cv::Scalar(255, 0, 0), 2);
		cv::line(img, points[2], points[3], cv::Scalar(255, 0, 0), 2);
		cv::line(img, points[3], points[0], cv::Scalar(255, 0, 0), 2);

		cv::Point pt1 = cv::Point((points[0].x + points[3].x) / 2, (points[0].y + points[3].y) / 2);
		cv::Point pt2 = cv::Point((points[1].x + points[2].x) / 2, (points[1].y + points[2].y) / 2);
		cv::arrowedLine(img, pt2, pt1, cv::Scalar(0, 0, 255), 2);

		cv::imshow("img_" + std::to_string(i), img);
		cv::waitKey(0);
	}

	return 0;
}

结果如下:

相关推荐
飞睿科技13 分钟前
乐鑫代理商飞睿科技,2025年AI智能语音助手市场发展趋势与乐鑫芯片解决方案分析
人工智能
许泽宇的技术分享14 分钟前
从新闻到知识图谱:用大模型和知识工程“八步成诗”打造科技并购大脑
人工智能·科技·知识图谱
坤坤爱学习2.028 分钟前
求医十年,病因不明,ChatGPT:你看起来有基因突变
人工智能·ai·chatgpt·程序员·大模型·ai编程·大模型学
蹦蹦跳跳真可爱5891 小时前
Python----循环神经网络(Transformer ----注意力机制)
人工智能·深度学习·nlp·transformer·循环神经网络
空中湖3 小时前
tensorflow武林志第二卷第九章:玄功九转
人工智能·python·tensorflow
lishaoan773 小时前
使用tensorflow的线性回归的例子(七)
人工智能·tensorflow·线性回归
千宇宙航6 小时前
闲庭信步使用SV搭建图像测试平台:第三十一课——基于神经网络的手写数字识别
图像处理·人工智能·深度学习·神经网络·计算机视觉·fpga开发
onceco7 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
whoarethenext9 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
jndingxin9 小时前
OpenCV CUDA模块设备层-----高效地计算两个 uint 类型值的带权重平均值
人工智能·opencv·计算机视觉